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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
stream-chat-android-offline/src/test/java/io/getstream/chat/android/offline/utils/MessageDiffCallback.kt
|
GetStream
| 177,873,527 | false |
{"Kotlin": 8578375, "MDX": 2150736, "Java": 271477, "JavaScript": 6737, "Shell": 5229}
|
/*
* Copyright (c) 2014-2022 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-chat-android/blob/main/LICENSE
*
* 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.getstream.chat.android.offline.utils
import androidx.recyclerview.widget.DiffUtil
import io.getstream.chat.android.models.Message
internal data class MessageDiffCallback(
var old: List<Message>,
var new: List<Message>,
) :
DiffUtil.Callback() {
override fun getOldListSize(): Int {
return old.size
}
override fun getNewListSize(): Int {
return new.size
}
override fun areItemsTheSame(
oldItemPosition: Int,
newItemPosition: Int,
): Boolean {
return old[oldItemPosition].id == new[newItemPosition].id
}
override fun areContentsTheSame(
oldItemPosition: Int,
newItemPosition: Int,
): Boolean {
return old[oldItemPosition] == new[newItemPosition]
}
}
| 24 |
Kotlin
|
273
| 1,451 |
8e46f46a68810d8086c48a88f0fff29faa2629eb
| 1,404 |
stream-chat-android
|
FSF All Permissive License
|
app/src/main/java/com/spitchenko/pokeapp/component/lifecycle/ViewModelProperty.kt
|
Onotole1
| 212,967,916 | false | null |
package com.spitchenko.pokeapp.component.lifecycle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import kotlin.reflect.KClass
class ViewModelProperty<VM : ViewModel>(
private val viewModelClass: KClass<VM>,
private val ownerProducer: () -> ViewModelStoreOwner,
private val factoryProducer: () -> ViewModelProvider.Factory
) : Lazy<VM> {
private var cached: VM? = null
override val value: VM
get() {
return cached
?: ViewModelProvider(ownerProducer(), factoryProducer()).get(viewModelClass.java).also {
cached = it
}
}
override fun isInitialized() = cached != null
}
| 1 |
Kotlin
|
0
| 1 |
e8576bd4aa9bb91b5ea82d9c79b6f1fc2290e3d2
| 754 |
PokeApp
|
Apache License 2.0
|
archive/765/solve.kt
|
daniellionel01
| 435,306,139 | false | null |
/*
=== #765 Trillionaire - Project Euler ===
Starting with 1 gram of gold you play a game. Each round you bet a certain amount of your gold: if you have $x$ grams you can bet $b$ grams for any $0 \le b \le x$. You then toss an unfair coin: with a probability of $0.6$ you double your bet (so you now have $x+b$), otherwise you lose your bet (so you now have $x-b$).
Choosing your bets to maximize your probability of having at least a trillion $(10^{12})$ grams of gold after $1000$ rounds, what is the probability that you become a trillionaire?
All computations are assumed to be exact (no rounding), but give your answer rounded to 10 digits behind the decimal point.
Difficulty rating: 65%
*/
fun solve(x: Int): Int {
return x*2;
}
fun main() {
val a = solve(10);
println("solution: $a");
}
| 0 |
Kotlin
|
0
| 1 |
1ad6a549a0a420ac04906cfa86d99d8c612056f6
| 808 |
euler
|
MIT License
|
org.librarysimplified.audiobook.views/src/main/java/org/librarysimplified/audiobook/views/toc/PlayerTOCChapterAdapter.kt
|
ThePalaceProject
| 379,956,255 | false |
{"Kotlin": 718883, "Java": 2554}
|
package org.librarysimplified.audiobook.views.toc
import android.content.Context
import android.content.DialogInterface
import android.content.res.Resources
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import org.joda.time.Duration
import org.joda.time.format.PeriodFormatter
import org.joda.time.format.PeriodFormatterBuilder
import org.librarysimplified.audiobook.api.PlayerDownloadTaskType
import org.librarysimplified.audiobook.api.PlayerSpineElementDownloadStatus.PlayerSpineElementDownloadExpired
import org.librarysimplified.audiobook.api.PlayerSpineElementDownloadStatus.PlayerSpineElementDownloadFailed
import org.librarysimplified.audiobook.api.PlayerSpineElementDownloadStatus.PlayerSpineElementDownloaded
import org.librarysimplified.audiobook.api.PlayerSpineElementDownloadStatus.PlayerSpineElementDownloading
import org.librarysimplified.audiobook.api.PlayerSpineElementDownloadStatus.PlayerSpineElementNotDownloaded
import org.librarysimplified.audiobook.api.PlayerSpineElementType
import org.librarysimplified.audiobook.api.PlayerUIThread
import org.librarysimplified.audiobook.views.PlayerCircularProgressView
import org.librarysimplified.audiobook.views.PlayerTimeStrings
import org.librarysimplified.audiobook.views.R
/**
* A Recycler view adapter used to display and control the chapters of the table of contents.
*/
class PlayerTOCChapterAdapter(
private val context: Context,
private val spineElements: List<PlayerSpineElementType>,
private val downloadTasks: List<PlayerDownloadTaskType>,
private val onSelect: (PlayerSpineElementType) -> Unit,
) :
RecyclerView.Adapter<PlayerTOCChapterAdapter.ViewHolder>() {
private val listener: View.OnClickListener
private var currentSpineElement: Int = -1
private val periodFormatter: PeriodFormatter =
PeriodFormatterBuilder()
.printZeroAlways()
.minimumPrintedDigits(2)
.appendHours()
.appendLiteral(":")
.appendMinutes()
.appendLiteral(":")
.appendSeconds()
.toFormatter()
private val timeStrings: PlayerTimeStrings.SpokenTranslations
init {
this.timeStrings =
PlayerTimeStrings.SpokenTranslations.createFromResources(this.context.resources)
this.listener = View.OnClickListener { v -> this.onSelect(v.tag as PlayerSpineElementType) }
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): ViewHolder {
PlayerUIThread.checkIsUIThread()
val view =
LayoutInflater.from(parent.context)
.inflate(R.layout.player_toc_chapter_item_view, parent, false)
return this.ViewHolder(view)
}
override fun onBindViewHolder(
holder: ViewHolder,
position: Int
) {
PlayerUIThread.checkIsUIThread()
val item = this.spineElements[position]
val normalIndex = item.index + 1
val title = item.title ?: this.context.getString(
R.string.audiobook_player_toc_track_n,
normalIndex
)
holder.titleText.text = title
holder.titleText.isEnabled = false
holder.downloadedDurationText.text =
item.duration?.let {
this.periodFormatter.print(it.toPeriod())
}.orEmpty()
holder.view.isEnabled = item.book.supportsStreaming
var requiresDownload = false
var failedDownload = false
var downloading = false
val status = item.downloadStatus
holder.buttons.visibility = if (status !is PlayerSpineElementDownloaded) {
VISIBLE
} else {
GONE
}
when (status) {
is PlayerSpineElementNotDownloaded -> {
holder.buttonsDownloading.visibility = INVISIBLE
holder.buttonsDownloadFailed.visibility = INVISIBLE
if (item.book.supportsStreaming) {
holder.buttonsNotDownloadedNotStreamable.visibility = INVISIBLE
holder.buttonsNotDownloadedStreamable.visibility = VISIBLE
if (item.downloadTasksSupported) {
holder.notDownloadedStreamableRefresh.setOnClickListener {
downloadTasks.firstOrNull { task ->
task.fulfillsSpineElement(item)
}?.fetch()
}
holder.notDownloadedStreamableRefresh.contentDescription =
this.context.getString(
R.string.audiobook_accessibility_toc_download,
normalIndex
)
holder.notDownloadedStreamableRefresh.isEnabled = true
} else {
holder.notDownloadedStreamableRefresh.contentDescription = null
holder.notDownloadedStreamableRefresh.isEnabled = false
}
} else {
holder.buttonsNotDownloadedNotStreamable.visibility = VISIBLE
holder.buttonsNotDownloadedStreamable.visibility = INVISIBLE
if (item.downloadTasksSupported) {
holder.notDownloadedStreamableRefresh.setOnClickListener {
downloadTasks.firstOrNull { task ->
task.fulfillsSpineElement(item)
}?.fetch()
}
holder.notDownloadedStreamableRefresh.contentDescription =
this.context.getString(
R.string.audiobook_accessibility_toc_download,
normalIndex
)
holder.notDownloadedStreamableRefresh.isEnabled = true
} else {
holder.notDownloadedStreamableRefresh.contentDescription = null
holder.notDownloadedStreamableRefresh.isEnabled = false
}
requiresDownload = true
}
}
is PlayerSpineElementDownloading -> {
holder.buttonsDownloading.visibility = VISIBLE
holder.buttonsDownloadFailed.visibility = INVISIBLE
holder.buttonsNotDownloadedStreamable.visibility = INVISIBLE
holder.buttonsNotDownloadedNotStreamable.visibility = INVISIBLE
if (item.downloadTasksSupported) {
holder.downloadingProgress.setOnClickListener { this.onConfirmCancelDownloading(item) }
holder.downloadingProgress.isEnabled = true
} else {
holder.downloadingProgress.isEnabled = false
}
holder.downloadingProgress.contentDescription =
this.context.getString(R.string.audiobook_accessibility_toc_progress, normalIndex, status.percent)
holder.downloadingProgress.visibility = VISIBLE
holder.downloadingProgress.progress = status.percent.toFloat() * 0.01f
downloading = true
requiresDownload = item.book.supportsStreaming == false
}
is PlayerSpineElementDownloaded -> {
holder.view.isEnabled = true
}
is PlayerSpineElementDownloadFailed -> {
holder.buttonsDownloading.visibility = INVISIBLE
holder.buttonsDownloadFailed.visibility = VISIBLE
holder.buttonsNotDownloadedStreamable.visibility = INVISIBLE
holder.buttonsNotDownloadedNotStreamable.visibility = INVISIBLE
if (item.downloadTasksSupported) {
holder.downloadFailedRefresh.setOnClickListener {
val task = downloadTasks.firstOrNull { task ->
task.fulfillsSpineElement(item)
}
task?.cancel()
task?.fetch()
}
holder.downloadFailedRefresh.contentDescription =
this.context.getString(R.string.audiobook_accessibility_toc_retry, normalIndex)
holder.downloadFailedRefresh.isEnabled = true
} else {
holder.downloadFailedRefresh.contentDescription = null
holder.downloadFailedRefresh.isEnabled = false
}
failedDownload = true
requiresDownload = item.book.supportsStreaming == false
}
is PlayerSpineElementDownloadExpired -> {
// Nothing to do.
}
}
val view = holder.view
view.tag = item
view.setOnClickListener([email protected])
view.contentDescription =
contentDescriptionOf(
resources = context.resources,
title = title,
duration = item.duration,
playing = position == this.currentSpineElement,
requiresDownload = requiresDownload,
failedDownload = failedDownload,
downloading = downloading
)
if (position == this.currentSpineElement) {
holder.isCurrent.visibility = VISIBLE
} else {
holder.isCurrent.visibility = INVISIBLE
}
}
private fun contentDescriptionOf(
resources: Resources,
title: String,
duration: Duration?,
playing: Boolean,
requiresDownload: Boolean,
failedDownload: Boolean,
downloading: Boolean
): String {
val builder = StringBuilder(128)
if (playing) {
builder.append(resources.getString(R.string.audiobook_accessibility_toc_chapter_is_current))
builder.append(" ")
}
builder.append(title)
builder.append(". ")
if (duration != null) {
builder.append(resources.getString(R.string.audiobook_accessibility_toc_chapter_duration_is))
builder.append(" ")
builder.append(
PlayerTimeStrings.hourMinuteSecondSpokenFromDuration(this.timeStrings, duration)
)
builder.append(". ")
}
if (requiresDownload) {
builder.append(resources.getString(R.string.audiobook_accessibility_toc_chapter_requires_download))
builder.append(".")
}
if (failedDownload) {
builder.append(resources.getString(R.string.audiobook_accessibility_toc_chapter_failed_download))
builder.append(".")
}
if (downloading) {
builder.append(resources.getString(R.string.audiobook_accessibility_toc_chapter_downloading))
builder.append(".")
}
return builder.toString()
}
private fun onConfirmCancelDownloading(item: PlayerSpineElementType) {
val dialog =
MaterialAlertDialogBuilder(this.context)
.setCancelable(true)
.setMessage(R.string.audiobook_part_download_stop_confirm)
.setPositiveButton(
R.string.audiobook_part_download_stop,
{ _: DialogInterface, _: Int ->
downloadTasks.firstOrNull { task ->
task.fulfillsSpineElement(item)
}?.cancel()
}
)
.setNegativeButton(
R.string.audiobook_part_download_continue,
{ _: DialogInterface, _: Int -> }
)
.create()
dialog.show()
}
override fun getItemCount(): Int = this.spineElements.size
fun setCurrentSpineElement(index: Int) {
PlayerUIThread.checkIsUIThread()
val previous = this.currentSpineElement
this.currentSpineElement = index
this.notifyItemChanged(index)
if (previous != -1) {
this.notifyItemChanged(previous)
}
}
inner class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
val buttons: ViewGroup =
this.view.findViewById(R.id.player_toc_chapter_end_controls)
val buttonsDownloadFailed: ViewGroup =
this.buttons.findViewById(R.id.player_toc_chapter_item_buttons_error)
val buttonsNotDownloadedNotStreamable: ViewGroup =
this.buttons.findViewById(R.id.player_toc_chapter_item_buttons_not_downloaded_not_streamable)
val buttonsNotDownloadedStreamable: ViewGroup =
this.buttons.findViewById(R.id.player_toc_chapter_item_buttons_not_downloaded_streamable)
val buttonsDownloading: ViewGroup =
this.buttons.findViewById(R.id.player_toc_chapter_item_buttons_downloading)
val titleText: TextView =
this.view.findViewById(R.id.player_toc_chapter_item_view_title)
val isCurrent: ImageView =
this.view.findViewById(R.id.player_toc_chapter_item_is_current)
val downloadFailedErrorIcon: ImageView =
this.buttonsDownloadFailed.findViewById(R.id.player_toc_item_download_failed_error_icon)
val downloadFailedRefresh: ImageView =
this.buttonsDownloadFailed.findViewById(R.id.player_toc_item_download_failed_refresh)
val downloadedDurationText: TextView =
this.view.findViewById(R.id.player_toc_chapter_item_duration)
val notDownloadedStreamableRefresh: ImageView =
this.buttonsNotDownloadedStreamable.findViewById(
R.id.player_toc_item_not_downloaded_streamable_refresh
)
val notDownloadedStreamableProgress: PlayerCircularProgressView =
this.buttonsNotDownloadedStreamable.findViewById(
R.id.player_toc_item_not_downloaded_streamable_progress
)
val notDownloadedNotStreamableRefresh: ImageView =
this.buttonsNotDownloadedNotStreamable.findViewById(
R.id.player_toc_item_not_downloaded_not_streamable_refresh
)
val downloadingProgress: PlayerCircularProgressView =
this.buttonsDownloading.findViewById(R.id.player_toc_item_downloading_progress)
init {
this.downloadingProgress.thickness = 8.0f
this.notDownloadedStreamableProgress.thickness = 8.0f
}
}
}
| 1 |
Kotlin
|
1
| 1 |
d8e2d9dde4c20391075fcc6c527c9b9845b92a8e
| 13,051 |
android-audiobook
|
Apache License 2.0
|
log4j-api-kotlin/src/main/kotlin/org/apache/logging/log4j/kotlin/Logging.kt
|
apache
| 74,950,517 | false |
{"Kotlin": 80800, "FreeMarker": 18977, "Java": 893}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache license, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package org.apache.logging.log4j.kotlin
/**
* An interface-based "mixin" to easily add a log val to a class, named by the enclosing class. This allows
* code like this:
*
* ```
* import org.apache.logging.log4j.kotlin.Logging
*
* class MyClass: Logging {
* // use `logger` as necessary
* }
*
* ```
*
* Or declaring the interface on a companion object works just as well:
*
* ```
* import org.apache.logging.log4j.kotlin.logger
*
* class MyClass {
* companion object: Logging
*
* // use `logger` as necessary
* }
*
* ```
*
* Note that this is significantly slower than creating a logger explicitly, as it requires a lookup of the
* logger on each call via the property getter, since we cannot store any state in an interface. We attempt to
* minimize the overhead of this by caching the loggers, but according to microbenchmarks, it is still about
* 3.5 times slower than creating a logger once and using it (about 4.2 nanoseconds per call instead of 1.2
* nanoseconds).
*/
interface Logging {
/**
* Provides a logger automatically named after the class that extends this mixin interface.
*/
val logger
get() = cachedLoggerOf(this.javaClass)
}
| 7 |
Kotlin
|
13
| 48 |
ab27519c29d83612025e3864505703097abe3976
| 1,996 |
logging-log4j-kotlin
|
Apache License 2.0
|
feature/push/src/main/kotlin/de/tum/informatics/www1/artemis/native_app/feature/push/service/PushNotificationJobService.kt
|
ls1intum
| 537,104,541 | false |
{"Kotlin": 1958120, "Dockerfile": 1306, "Shell": 1187}
|
package de.tum.informatics.www1.artemis.native_app.feature.push.service
/**
* Service that can schedule jobs related to the push notification synchronization with the server.
* These jobs need to be guaranteed to be completed because otherwise weird behaviour can occur (e.g. users receiving push notifications for accounts they have already logged out from.)
*/
interface PushNotificationJobService {
/**
* Schedule a job that will upload the firebase id token and the AES key to the server.
*/
fun scheduleUploadPushNotificationDeviceConfigurationToServer()
/**
* Cancels the job that tries to upload the configuration to the server.
*/
suspend fun cancelPendingUploadPushNotificationDeviceConfigurationToServer()
/**
* Schedule a task that will tell the server that the user with the specified auth token no longer wants to receive
* push notifications.
*/
fun scheduleUnsubscribeFromNotifications(
serverUrl: String,
authToken: String,
firebaseToken: String
)
}
| 21 |
Kotlin
|
0
| 6 |
ef1ce4b9f87f09f4271f87ca6912b093bcad11a5
| 1,060 |
artemis-android
|
MIT License
|
feature/push/src/main/kotlin/de/tum/informatics/www1/artemis/native_app/feature/push/service/PushNotificationJobService.kt
|
ls1intum
| 537,104,541 | false |
{"Kotlin": 1958120, "Dockerfile": 1306, "Shell": 1187}
|
package de.tum.informatics.www1.artemis.native_app.feature.push.service
/**
* Service that can schedule jobs related to the push notification synchronization with the server.
* These jobs need to be guaranteed to be completed because otherwise weird behaviour can occur (e.g. users receiving push notifications for accounts they have already logged out from.)
*/
interface PushNotificationJobService {
/**
* Schedule a job that will upload the firebase id token and the AES key to the server.
*/
fun scheduleUploadPushNotificationDeviceConfigurationToServer()
/**
* Cancels the job that tries to upload the configuration to the server.
*/
suspend fun cancelPendingUploadPushNotificationDeviceConfigurationToServer()
/**
* Schedule a task that will tell the server that the user with the specified auth token no longer wants to receive
* push notifications.
*/
fun scheduleUnsubscribeFromNotifications(
serverUrl: String,
authToken: String,
firebaseToken: String
)
}
| 21 |
Kotlin
|
0
| 6 |
ef1ce4b9f87f09f4271f87ca6912b093bcad11a5
| 1,060 |
artemis-android
|
MIT License
|
app/src/main/java/com/bonacode/securehome/ui/feature/setup/enterphonenumber/PhoneNumberValidator.kt
|
clooss95
| 327,694,923 | false | null |
package com.bonacode.securehome.ui.feature.setup.enterphonenumber
fun CharSequence.isValidPhoneNumber(): Boolean =
android.util.Patterns.PHONE.matcher(this).matches()
| 0 |
Kotlin
|
1
| 2 |
1c51da1e85e1a80aac491abe07b878ed61fe032d
| 172 |
secure_home_2.0
|
MIT License
|
app/src/main/java/io/github/sauvio/ocr/utils/Constants.kt
|
Sauvio
| 737,247,604 | false |
{"Kotlin": 165743, "Java": 55038}
|
package io.github.sauvio.ocr.utils
class Constants {
companion object {
const val KEY_GRAYSCALE: String = "key_grayscale"
const val KEY_ADAPTIVE_THRESHOLD_MEAN: String = "key_adaptive_threshold_mean"
const val KEY_ADAPTIVE_THRESHOLD_BLOCK_SIZE: String = "key_adaptive_threshold_block_size"
const val KEY_ADAPTIVE_THRESHOLD_TYPE: String = "key_adaptive_threshold_type"
const val KEY_ADAPTIVE_THRESHOLD_METHOD: String = "key_adaptive_threshold_method"
const val KEY_ADAPTIVE_THRESHOLD_MAX_VALUE: String = "key_adaptive_threshold_max_value"
const val KEY_CONTRAST = "process_contrast"
const val KEY_UN_SHARP_MASKING = "un_sharp_mask"
const val KEY_OTSU_THRESHOLD = "otsu_threshold"
const val KEY_FIND_SKEW_AND_DESKEW = "deskew_img"
const val KEY_ADAPTIVE_THRESHOLD = "adaptive_threshold"
const val KEY_PERSIST_DATA = "persist_data"
const val VALUE_ADAPTIVE_THRESHOLD_MAX_VALUE_DEFAULT = "200.0"
const val VALUE_ADAPTIVE_THRESHOLD_METHOD_DEFAULT = "0"
const val VALUE_ADAPTIVE_THRESHOLD_TYPE_DEFAULT = "0"
const val VALUE_ADAPTIVE_THRESHOLD_BLOCK_SIZE_DEFAULT = "25"
const val VALUE_ADAPTIVE_THRESHOLD_MEAN_DEFAULT = "10.0"
}
}
| 0 |
Kotlin
|
0
| 0 |
7e7ddb2225887f18ce4b8d61480fee64ea6ed2ba
| 1,268 |
taskerplugin-ocr
|
Apache License 2.0
|
Interface.kt
|
2003MADHAV
| 832,573,227 | false |
{"Kotlin": 23931, "Java": 98}
|
fun main() {
dargObject(arrayOf(Circle(4.0),Square(4.0),Triangle2(3.0,4.0),Player("mukesh")))
}
fun dargObject(arrayOf: Array<Any>) {
TODO("Not yet implemented")
}
fun dargObj(objects:Array<Draggable>){
for (obj in objects){
obj.drag()
}
}
interface Draggable{
fun drag()
}
/*
interface Cloneable{
fun clone()
}
*/
abstract class Shape2 : Draggable{
abstract fun area():Double
}
class Circle2(val radius:Double): Shape(){
override fun area(): Double =Math.PI*radius*radius
override fun drag()= println("circle is draing")
}
class Square2(val side:Double):Shape(){
override fun area(): Double=side*side
override fun drag()= println("square is draing")
}
class Triangle2(val base:Double,val height:Double):Shape(){
override fun area(): Double =0.5*base*height
override fun drag()= println("tiangle is draing")
}
class Player(val name:String):Draggable{
override fun drag()= println("$name is dragging")
}
| 0 |
Kotlin
|
0
| 0 |
c3b16ef8bca31b80044836dfb51e99596e8b485c
| 976 |
Basic-Kotlin-Program-for-Beginner
|
MIT License
|
stream-chat-android-ui-components/src/main/kotlin/io/getstream/chat/android/ui/feature/messages/composer/attachment/picker/factory/AttachmentsPickerTabFactories.kt
|
GetStream
| 177,873,527 | false |
{"Kotlin": 8217338, "MDX": 2135421, "Java": 271311, "JavaScript": 6624, "Shell": 5229}
|
/*
* Copyright (c) 2014-2022 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-chat-android/blob/main/LICENSE
*
* 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.getstream.chat.android.ui.feature.messages.composer.attachment.picker.factory
import io.getstream.chat.android.ui.feature.messages.composer.attachment.picker.factory.camera.AttachmentsPickerCameraTabFactory
import io.getstream.chat.android.ui.feature.messages.composer.attachment.picker.factory.file.AttachmentsPickerFileTabFactory
import io.getstream.chat.android.ui.feature.messages.composer.attachment.picker.factory.media.AttachmentsPickerMediaTabFactory
/**
* Provides the default list of tab factories for the attachment picker.
*/
public object AttachmentsPickerTabFactories {
/**
* Creates a list of factories for the tabs that will be displayed in the attachment picker.
*
* @param mediaAttachmentsTabEnabled If the media attachments tab will be displayed in the picker.
* @param fileAttachmentsTabEnabled If the file attachments tab will be displayed in the picker.
* @param cameraAttachmentsTabEnabled If the camera attachments tab will be displayed in the picker.
* @return The list factories for the tabs that will be displayed in the attachment picker.
*/
public fun defaultFactories(
mediaAttachmentsTabEnabled: Boolean,
fileAttachmentsTabEnabled: Boolean,
cameraAttachmentsTabEnabled: Boolean,
): List<AttachmentsPickerTabFactory> {
return listOfNotNull(
if (mediaAttachmentsTabEnabled) AttachmentsPickerMediaTabFactory() else null,
if (fileAttachmentsTabEnabled) AttachmentsPickerFileTabFactory() else null,
if (cameraAttachmentsTabEnabled) AttachmentsPickerCameraTabFactory() else null,
)
}
}
| 34 |
Kotlin
|
263
| 1,403 |
696caf3a25eb8db4fc98326cdb0faa17ffe7a877
| 2,277 |
stream-chat-android
|
FSF All Permissive License
|
buildSrc/src/main/kotlin/Dependencies.kt
|
e1i2
| 649,003,109 | false | null |
object Dependencies {
const val KTLINT = "com.pinterest:ktlint:${DependencyVersions.KTLINT_VERSION}"
const val SPRING_VALIDATION = "org.springframework.boot:spring-boot-starter-validation"
const val SECURITY_JWT = "com.nimbusds:nimbus-jose-jwt:${DependencyVersions.NIMBUS_VERSION}"
const val WEBFLUX = "org.springframework.boot:spring-boot-starter-webflux"
const val KOTLIN_JACKSON = "com.fasterxml.jackson.module:jackson-module-kotlin"
const val COROUTINE_REACTOR_EXTENSION = "io.projectreactor.kotlin:reactor-kotlin-extensions"
const val COROUTINE_REACTOR = "org.jetbrains.kotlinx:kotlinx-coroutines-reactor"
const val CIRCUIT_BREAKER = "org.springframework.cloud:spring-cloud-starter-circuitbreaker-reactor-resilience4j"
const val SPRING_CLOUD_GATEWAY = "org.springframework.cloud:spring-cloud-starter-gateway"
const val KOTLIN_REFLECT = "org.jetbrains.kotlin:kotlin-reflect"
const val KOTLIN_STDLIB = "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
const val SPRING_BOOT_TEST = "org.springframework.boot:spring-boot-starter-test"
const val ACTUATOR = "org.springframework.boot:spring-boot-starter-actuator"
const val ANNOTATION_PROCESSOR = "org.springframework.boot:spring-boot-configuration-processor"
const val MICROMETER = "io.micrometer:micrometer-registry-prometheus"
const val HTTP_CLIENT = "org.apache.httpcomponents:httpclient:${DependencyVersions.HTTP_CLIENT_VERSION}"
}
| 0 |
Kotlin
|
0
| 0 |
386afb1e2e9dc77e84664ed1d3f9dc16b0a37423
| 1,442 |
api-gateway
|
MIT License
|
src/main/kotlin/net/spleefx/api/paste/PasteBody.kt
|
SpleefX
| 285,096,963 | false | null |
/*
* * Copyright 2019-2020 github.com/ReflxctionDev
*
* 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 net.spleefx.api.paste
/**
* A simple data class representing a paste content. Deserialized by Spring to
* fetch response bodies
*/
class PasteBody(val paste: String = "")
| 0 |
Kotlin
|
0
| 0 |
891a400bc09d648cdda62371f0d6b026561265e9
| 797 |
spleefx-web
|
Apache License 2.0
|
src/main/kotlin/com/tqi/challenge/backend/marketplace/dtos/responses/ProductResponseDTO.kt
|
Dev-JeanSantos
| 667,074,197 | false | null |
package com.tqi.challenge.backend.marketplace.dtos.responses
data class ProductResponseDTO(
val id: Long?,
val name: String,
val unityMeasure: String,
val price: Double,
val nameCategory: String
)
| 0 |
Kotlin
|
1
| 1 |
04654eeb518dd5b8c6fd599cb560e608f1319579
| 218 |
tqi_kotlin_backend_developer_2023
|
MIT License
|
app/src/main/java/com/example/radiola/player/extentions/PlaybackStateCompatExt.kt
|
geocdias
| 331,162,907 | false |
{"Kotlin": 44081}
|
package com.example.radiola.player
import android.os.SystemClock
import android.support.v4.media.session.PlaybackStateCompat
import android.support.v4.media.session.PlaybackStateCompat.STATE_PLAYING
inline val PlaybackStateCompat.isPrepared
get() = state == PlaybackStateCompat.STATE_BUFFERING ||
state == PlaybackStateCompat.STATE_PLAYING ||
state == PlaybackStateCompat.STATE_PAUSED
inline val PlaybackStateCompat.isPlaying
get() = state == PlaybackStateCompat.STATE_BUFFERING ||
state == PlaybackStateCompat.STATE_PLAYING
inline val PlaybackStateCompat.isPlayEnable
get() = actions and PlaybackStateCompat.ACTION_PLAY != 0L ||
(actions and PlaybackStateCompat.ACTION_PLAY_PAUSE != 0L &&
state == PlaybackStateCompat.STATE_PAUSED)
inline val PlaybackStateCompat.currentPlaybackPosition: Long
get() = if(state == STATE_PLAYING) {
val timeDelta = SystemClock.elapsedRealtime() - lastPositionUpdateTime
(position + (timeDelta * playbackSpeed)).toLong()
} else position
| 1 |
Kotlin
|
0
| 0 |
a87b7395979cee7a084ba1b22e0f973befe6cdd5
| 1,026 |
Radiola
|
MIT License
|
src/main/kotlin/possible_triangle/divide/logic/Bases.kt
|
PssbleTrngle
| 275,110,821 | false |
{"Kotlin": 272874, "TypeScript": 118166, "Java": 7745, "CSS": 6874, "HTML": 1620, "mcfunction": 1102, "Dockerfile": 856}
|
package possible_triangle.divide.logic
import net.minecraft.core.BlockPos
import net.minecraft.nbt.CompoundTag
import net.minecraft.nbt.NbtOps
import net.minecraft.nbt.NbtUtils
import net.minecraft.network.chat.Style
import net.minecraft.network.chat.TextComponent
import net.minecraft.resources.ResourceKey
import net.minecraft.server.MinecraftServer
import net.minecraft.server.level.ServerLevel
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.item.ItemStack
import net.minecraft.world.item.Items
import net.minecraft.world.item.enchantment.Enchantments
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.Blocks
import net.minecraft.world.level.block.CropBlock
import net.minecraft.world.phys.AABB
import net.minecraft.world.scores.Team
import net.minecraftforge.event.TickEvent
import net.minecraftforge.eventbus.api.SubscribeEvent
import net.minecraftforge.fml.common.Mod
import possible_triangle.divide.Config
import possible_triangle.divide.DivideMod
import possible_triangle.divide.reward.actions.TeamBuff
import possible_triangle.divide.data.ModSavedData
import possible_triangle.divide.data.Util
import possible_triangle.divide.reward.Reward
import java.util.*
@Mod.EventBusSubscriber
object Bases {
const val COMPASS_TAG = "${DivideMod.ID}:base_compass"
private const val IN_BASE_TAG = "${DivideMod.ID}:in_base"
private val TICK_RANDOM = Random()
@SubscribeEvent
fun playerTick(event: TickEvent.PlayerTickEvent) {
if (Util.shouldSkip(event, { it.player.level }, ticks = 1)) return
val player = event.player
if (player !is ServerPlayer) return
val data = Util.persistentData(player)
val lastState = data.getBoolean(IN_BASE_TAG)
val currentState = isInBase(player)
if (lastState != currentState) {
data.putBoolean(IN_BASE_TAG, currentState)
}
}
@SubscribeEvent
fun worldTick(event: TickEvent.WorldTickEvent) {
if (Util.shouldSkip(event, { event.world }, ticks = 200, onlyOverworld = false)) return
val world = event.world as ServerLevel
Data[world.server]
.filterKeys { TeamBuff.isBuffed(world.server, it, Reward.BUFF_CROPS) }
.filterValues { (_, dim) -> dim == world.dimension() }
.forEach { (_, pos) ->
if (world.isAreaLoaded(pos.first, 1)) {
val blocks = Util.blocksIn(baseBox(pos.first))
blocks.forEach {
val state = world.getBlockState(it)
if (state.block is CropBlock) {
(state.block as CropBlock).randomTick(state, world, it, TICK_RANDOM)
}
}
}
}
}
fun removeBase(team: Team, server: MinecraftServer) {
Data.modify(server) {
remove(team)
}
}
fun setBase(player: ServerPlayer) {
val team = player.team ?: return
val oldBase = Data[player.server][team]
if (oldBase != null) {
player.server.getLevel(oldBase.second)?.setBlock(
oldBase.first.atY(player.level.minBuildHeight),
Blocks.BEDROCK.defaultBlockState(), 2
)
}
player.level.setBlock(
player.blockPosition().atY(player.level.minBuildHeight),
Blocks.LODESTONE.defaultBlockState(), 2
)
Data.modify(player.server) {
set(team, player.blockPosition() to player.level.dimension())
}
val compass = createCompass(player) ?: return
Teams.teammates(player).forEach { teammate ->
val compassSlot = teammate.inventory.items.indexOfFirst { it.tag?.getBoolean(COMPASS_TAG) == true }
if (compassSlot >= 0) teammate.inventory.setItem(compassSlot, compass)
else if (oldBase == null) teammate.addItem(compass)
}
}
fun getBase(server: MinecraftServer, team: Team): Pair<BlockPos, ResourceKey<Level>>? {
return Data[server][team]
}
fun baseBox(pos: BlockPos): AABB {
return AABB(pos).inflate(Config.CONFIG.bases.radius)
}
fun createCompass(player: ServerPlayer): ItemStack? {
val team = player.team ?: return null
val (pos, dimension) = getBase(player.server, team) ?: return null
val stack = ItemStack(Items.COMPASS)
stack.orCreateTag.putBoolean(COMPASS_TAG, true)
stack.enchant(Enchantments.VANISHING_CURSE, 1)
stack.hoverName = TextComponent("Base Compass").withStyle(Style.EMPTY.withItalic(false))
stack.orCreateTag.put("LodestonePos", NbtUtils.writeBlockPos(pos.atY(player.level.minBuildHeight)))
Level.RESOURCE_KEY_CODEC.encodeStart(NbtOps.INSTANCE, dimension).result().ifPresent {
stack.orCreateTag.put("LodestoneDimension", it)
}
stack.orCreateTag.putBoolean("LodestoneTracked", true)
return stack
}
fun isInBase(player: ServerPlayer, useTag: Boolean = false): Boolean {
val persistent = Util.persistentData(player)
if(useTag && persistent.contains(IN_BASE_TAG)) return persistent.getBoolean(IN_BASE_TAG)
val team = player.team ?: return false
val (pos, dimension) = getBase(player.server, team) ?: return false
if (dimension != player.level.dimension()) return false
return baseBox(pos).contains(player.position())
}
private val Data = object : ModSavedData<MutableMap<Team, Pair<BlockPos, ResourceKey<Level>>>>("bases") {
override fun save(nbt: CompoundTag, value: MutableMap<Team, Pair<BlockPos, ResourceKey<Level>>>) {
value.forEach { (team, pos) ->
with(NbtUtils.writeBlockPos(pos.first)) {
Level.RESOURCE_KEY_CODEC.encodeStart(NbtOps.INSTANCE, pos.second).result().ifPresent {
put("dimension", it)
nbt.put(team.name, this)
}
}
}
}
override fun load(
nbt: CompoundTag,
server: MinecraftServer
): MutableMap<Team, Pair<BlockPos, ResourceKey<Level>>> {
return nbt.allKeys.mapNotNull { server.scoreboard.getPlayerTeam(it) }.associateWith { team ->
val tag = nbt.getCompound(team.name)
val pos = NbtUtils.readBlockPos(tag)
val dimension = Level.RESOURCE_KEY_CODEC.decode(NbtOps.INSTANCE, tag.get("dimension")).result()
dimension.map { pos to it.first }
}.filterValues { it.isPresent }.mapValues { it.value.get() }.toMutableMap()
}
override fun default(): MutableMap<Team, Pair<BlockPos, ResourceKey<Level>>> {
return mutableMapOf()
}
}
}
| 17 |
Kotlin
|
0
| 0 |
e0cc0532307557d509f177ac9d80dc97e1353d72
| 6,836 |
Divide
|
MIT License
|
src/main/kotlin/ink/ptms/adyeshach/common/entity/EntityFireball.kt
|
TabooLib
| 284,936,010 | false | null |
package ink.ptms.adyeshach.common.entity
/**
* @Author sky
* @Since 2020-08-15 15:51
*/
interface EntityFireball
| 6 | null |
22
| 50 |
1d55b42bd6866ff709aef8d79bb2a8de36beeb0d
| 116 |
Adyeshach
|
MIT License
|
src/main/kotlin/playground/common/messaging/logicalTypes/MoxLogicalTypes.kt
|
dtkmn
| 596,118,171 | false |
{"Kotlin": 333222, "Dockerfile": 763}
|
package playground.common.messaging.logicalTypes
import org.apache.avro.Conversion
import org.apache.avro.LogicalType
import org.apache.avro.LogicalTypes
import org.apache.avro.specific.SpecificData
/**
* Using custom logical types is tedious and lot can go wrong. They need to be registered at
* several places. We abstract the registration using [MoxLogicalTypes.registerAll]
* and we group all logical in this enum class, which mitigates the issues partially.
*
* To create a new logical type add new [MoxLogicalTypes] enum value to this file and provide
* the implementation in a standalone file (in this folder).
*
* **WARNING: Be careful, because avro template record relies on the fully quantified name of [MoxLogicalTypes.registerAll]!**
*/
enum class MoxLogicalTypes(
val logicalType: LogicalType,
val avroConversion: Conversion<*>
) {
MOX_DECIMAL(MoxDecimalLogicalType(), MoxDecimalAvroConversion()),
MOX_MONEY(MoxMoneyLogicalType(), MoxMoneyAvroConversion()),
MOX_CURRENCY(MoxCurrencyLogicalType(), MoxCurrencyAvroConversion())
;
val avroLogicalTypeFactory = LogicalTypes.LogicalTypeFactory { logicalType }
val logicalName: String = logicalType.name
companion object {
/**
* True, if logical types have already been registered.
*/
private var alreadyRegistered = false
/**
* Registers all custom logical types defined by this class.
*
* Registers the logical type represented by this interface, so avro converter is able to generate
* these fields or serialize/deserialize the type correctly.
*
* There are several places where we need to register the custom logical types.
* 1. At runtime of client services which use the generated code. The conversion for custom logical types
* is done by parsing the inlined avro schema (which is part of the generated files as a string) and using
* converters obtained from the registered types. To make sure they are available, we register the types
* before the inlined schema is parsed.
* 2. In [dragon-contracts](https://github.com/ProjectDrgn/dragon-contracts) because there are checks
* verifying the correctness of the schemas.
* 3. In contract gradle plugins code generator which generates the code from the schema.
*
* Logical types need to be registered only once, but this function might be called multiple times,
* because it will be called when initializing static fields in avro generated files. If this function
* was already called in current runtime, it will immediately return.
*
* There was a lot of effort spent with the implementation of the registration of custom logical types.
* The technical document highlighting alternatives considered can be found at
* [https://projectdrgn.atlassian.net/wiki/x/MQCZHg](https://projectdrgn.atlassian.net/wiki/x/MQCZHg).
*/
fun registerAll() {
if (alreadyRegistered) return
values().forEach {
LogicalTypes.register(it.logicalName, it.avroLogicalTypeFactory)
}
}
/**
* Registering all logical types in [registerAll] is not enough for
* [kotlin avro generator](https://github.com/ProjectDrgn/contract-gradle-plugins/blob/master/src/main/kotlin/com/projectdrgn/common/avro/codegen/KotlinGenerator.kt),
* which needs to have the converters also in it's [SpecificData].
*
* @param kotlinGeneratorData data for kotlin generator, which needs to be initialized with
* all logical type conversions.
*/
fun addAllCustomLogicalTypeConversions(kotlinGeneratorData: SpecificData) {
values().forEach {
kotlinGeneratorData.addLogicalTypeConversion(it.avroConversion)
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
49b517c2197a6fa79a8532225ce294b213f2356a
| 3,987 |
kotlin-playground
|
MIT License
|
bytecode/samples/src/main/kotlin/com/legacycode/eureka/samples/LateinitVar.kt
|
LegacyCodeHQ
| 546,118,669 | false | null |
@file:Suppress("unused")
package com.legacycode.eureka.samples
class LateinitVar {
lateinit var bingo: String
}
| 1 |
Kotlin
|
5
| 90 |
184f6be4b23ac7446fde524ffccd99a452f2b43a
| 116 |
eureka
|
Apache License 2.0
|
comments-app-common/src/commonMain/kotlin/package.kt
|
crowdproj
| 508,567,511 | false |
{"Kotlin": 52564, "Dockerfile": 344}
|
package ru.crowdproj.comments.app.common
| 0 |
Kotlin
|
2
| 1 |
9f71bc697ed6f968caaf936433741cad2f23b317
| 40 |
crowdproj-comments
|
Apache License 2.0
|
lithic-kotlin-core/src/main/kotlin/com/lithic/api/errors/RateLimitException.kt
|
lithic-com
| 658,974,440 | false |
{"Kotlin": 5250834, "Shell": 3630, "Dockerfile": 399}
|
package com.lithic.api.errors
import com.google.common.collect.ListMultimap
class RateLimitException
constructor(
headers: ListMultimap<String, String>,
private val error: LithicError,
) : LithicServiceException(headers, "${error}") {
override fun statusCode(): Int = 429
fun error(): LithicError = error
}
| 1 |
Kotlin
|
0
| 2 |
6a0e13311fb5dd6c6f0b3a665e4a2e5796b6711e
| 326 |
lithic-kotlin
|
Apache License 2.0
|
oss-license-view/src/main/java/dev/leonlatsch/osslicenseview/Utils.kt
|
leonlatsch
| 333,586,969 | false | null |
/*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 dev.leonlatsch.osslicenseview
import android.content.Context
import android.content.Intent
import android.net.Uri
internal fun openUrl(context: Context, url: String?) {
url ?: return
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(url)
context.startActivity(intent)
}
| 0 |
Kotlin
|
0
| 1 |
aeeb9501cce3627777cad26f79457ab9d3b57647
| 922 |
OssLicenseView
|
Apache License 2.0
|
demo/src/main/kotlin/dev/hotwire/demo/features/numbers/NumberBottomSheetFragment.kt
|
hotwired
| 771,533,412 | false |
{"Kotlin": 319790, "JavaScript": 10089}
|
package dev.hotwire.demo.features.numbers
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.material.textview.MaterialTextView
import dev.hotwire.core.turbo.config.PathConfigurationProperties
import dev.hotwire.demo.R
import dev.hotwire.navigation.destinations.HotwireDestinationDeepLink
import dev.hotwire.navigation.fragments.HotwireBottomSheetFragment
@HotwireDestinationDeepLink(uri = "hotwire://fragment/numbers/sheet")
class NumberBottomSheetFragment : HotwireBottomSheetFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_number_bottom_sheet, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initView(view)
}
private fun initView(view: View) {
view.findViewById<MaterialTextView>(R.id.number).apply {
text = Uri.parse(location).lastPathSegment
}
view.findViewById<MaterialTextView>(R.id.number_description).apply {
text = pathProperties.description
}
}
private val PathConfigurationProperties.description: String?
get() = get("description")
}
| 11 |
Kotlin
|
3
| 32 |
218a7f799d4a4a5c721aa7f1aadff598970320d8
| 1,389 |
hotwire-native-android
|
MIT License
|
app/src/main/java/com/ando/chathouse/domain/entity/ChatEntity.kt
|
Ando-Lin
| 624,359,996 | false | null |
package com.ando.chathouse.domain.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.PrimaryKey
import com.ando.chathouse.strategy.impl.FixedWindowCarryMessageStrategy
@Entity(
tableName = "chat",
foreignKeys = [ForeignKey(
entity = UserEntity::class,
parentColumns = ["id"],
childColumns = ["uid"],
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.NO_ACTION,
deferred = false
)]
)
data class ChatEntity(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
@ColumnInfo(name = "msg_strategy")
val messageStrategy: String,
@ColumnInfo(index = true)
val uid: Int,
// val title:String
) {
companion object {
//uid和chatId一一对应
fun individual(uid: Int): ChatEntity =
ChatEntity(id = uid, messageStrategy = FixedWindowCarryMessageStrategy.NAME, uid = uid)
}
}
| 0 |
Kotlin
|
0
| 0 |
1978552779fc0b76ab87a7d1bfe498cb544466d4
| 947 |
chat-house
|
MIT License
|
me-api/src/main/kotlin/shop/hyeonme/domain/exercise/usecase/data/res/QueryExerciseResponseData.kt
|
TEAM-hyeonme
| 776,784,109 | false |
{"Kotlin": 120635, "Dockerfile": 204}
|
package shop.hyeonme.domain.exercise.usecase.data.res
import shop.hyeonme.domain.exercise.model.enums.ExerciseType
data class QueryExerciseResponseData(
val exerciseType: ExerciseType,
val calorie: Int
)
| 0 |
Kotlin
|
0
| 0 |
646621f5577418523de44ed3a229d19879ee7193
| 213 |
ME-server
|
MIT License
|
app/src/main/java/site/panda2134/thssforum/ui/home/postlist/PostListRecyclerViewHolder.kt
|
panda2134-thss-android-team
| 488,254,653 | false | null |
package site.panda2134.thssforum.ui.home.postlist
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.MediaController
import android.widget.Toast
import androidx.core.app.ShareCompat
import androidx.core.content.ContextCompat
import androidx.core.content.ContextCompat.startActivity
import androidx.core.view.isVisible
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.RecyclerView
import cn.bingoogolapple.photopicker.activity.BGAPhotoPreviewActivity
import cn.bingoogolapple.photopicker.widget.BGANinePhotoLayout
import com.arges.sepan.argmusicplayer.Models.ArgAudio
import com.bumptech.glide.Glide
import com.github.kittinunf.fuel.core.FuelError
import kotlinx.coroutines.*
import net.yslibrary.android.keyboardvisibilityevent.KeyboardVisibilityEvent
import site.panda2134.thssforum.R
import site.panda2134.thssforum.api.APIWrapper
import site.panda2134.thssforum.databinding.PostItemBinding
import site.panda2134.thssforum.models.*
import site.panda2134.thssforum.ui.home.comments.CommentRecyclerViewAdapter
import site.panda2134.thssforum.ui.profile.ProfileUserHomepage
import site.panda2134.thssforum.utils.toTimeAgo
class PostListRecyclerViewHolder(val binding: PostItemBinding, val api: APIWrapper, val recyclerView: RecyclerView,
val activity: Activity, val lifecycleOwner: LifecycleOwner): RecyclerView.ViewHolder(binding.root), BGANinePhotoLayout.Delegate {
private var post: Post? = null
var onDeleteCallback: ((post: Post, bindingAdapterPosition: Int)->Unit)? = null
var mediaController: MediaController? = null
private set
private var replyTo: Comment? = null
private val inputMethodManager = ContextCompat.getSystemService(binding.root.context, InputMethodManager::class.java)!!
init {
MainScope().launch {
while (true) {
delay(5 * 1000)
post?.run {
binding.postTime.text = postContent.createdAt?.toTimeAgo() ?: return@run
}
}
}
}
fun setPost(p: Post) {
post = p
binding.likeButton.isChecked = false // default to false
binding.location.text = ""
binding.location.visibility = View.GONE
binding.commentInput.text?.clear()
binding.commentInput.visibility = View.GONE
val commentAdapter = (binding.commentView.adapter as CommentRecyclerViewAdapter)
commentAdapter.postId = p.postContent.id!!
commentAdapter.clear()
val scope = MainScope()
scope.launch(Dispatchers.IO) {
try {
commentAdapter.fetchComments()
val likes = api.getNumOfLikes(p.postContent.id)
val likeNicknames = getLikeNicknames(scope)
val followingUsers = api.getFollowingUsers()
withContext(Dispatchers.Main) {
binding.likeList.text = likeNicknames.joinToString(", ")
binding.likeWrapper.isVisible = binding.likeList.text.isNotBlank()
binding.likeButton.isChecked = likes.likedByMe
binding.followedButton.visibility =
if (followingUsers.contains(p.author)) View.VISIBLE else View.GONE
}
} catch (e: Throwable) {
e.printStackTrace()
}
}
Glide.with(binding.root).load(p.author.avatar).placeholder(R.drawable.ic_baseline_account_circle_24).into(binding.userAvatar)
binding.userName.text = p.author.nickname
binding.removePostButton.visibility =
if (p.author.uid == api.currentUserId) {
View.VISIBLE
} else {
View.GONE
}
p.postContent.location?.let {
binding.location.visibility = View.VISIBLE
binding.location.text = it.description
}
p.postContent.createdAt?.let {
binding.postTime.text = it.toTimeAgo()
}
val gotoPostAuthorPage = {
post?.let {
val intent = Intent(binding.root.context, ProfileUserHomepage::class.java)
.putExtra("author", it.author.uid)
binding.root.context.startActivity(intent)
}
}
binding.userAvatar.setOnClickListener { gotoPostAuthorPage() }
binding.userName.setOnClickListener { gotoPostAuthorPage() }
when(p.postContent.type) {
PostType.normal -> {
val content = p.postContent.imageTextContent!!
binding.postTitle.text = content.title
binding.postContent.text = content.text
binding.postContent.visibility = View.VISIBLE
binding.postImages.visibility = View.VISIBLE
binding.audioPlayer.visibility = View.GONE
binding.videoPlayerWrapper.visibility = View.GONE
binding.postImages.data = content.images
binding.postImages.setDelegate(this)
}
PostType.audio -> {
val content = p.postContent.mediaContent!!
binding.postTitle.text = content.title
binding.postContent.visibility = View.GONE
binding.postImages.visibility = View.GONE
binding.audioPlayer.visibility = View.VISIBLE
binding.videoPlayerWrapper.visibility = View.GONE
binding.audioPlayer.apply {
disableNextPrevButtons()
setProgressMessage(context.getString(R.string.loading))
disableRepeatButton()
setPlaylistRepeat(false)
playAudioAfterPercent(10)
play(ArgAudio.createFromURL(
p.author.nickname, p.postContent.mediaContent.title,
p.postContent.mediaContent.media[0]
))
// 加载完成后不马上开始播放
var firstPlayed = false
this.setOnPlayingListener {
if (!firstPlayed) {
firstPlayed = true
pause()
}
}
}
}
PostType.video -> {
val content = p.postContent.mediaContent!!
binding.postTitle.text = content.title
binding.postContent.visibility = View.GONE
binding.postImages.visibility = View.GONE
binding.audioPlayer.visibility = View.GONE
binding.videoPlayerWrapper.visibility = View.VISIBLE
binding.videoPlayer.setVideoURI(Uri.parse(content.media[0]))
binding.videoPlayer.seekTo(1)
mediaController = MediaController(binding.videoPlayerWrapper.context)
mediaController!!.setAnchorView(binding.videoPlayer)
binding.videoPlayer.setMediaController(mediaController)
binding.videoPlayer.setOnPreparedListener {
binding.videoPlayer.postDelayed({
mediaController!!.hide()
},1)
}
}
}
binding.likeButton.setOnClickListener {
MainScope().launch(Dispatchers.IO) {
try {
if (binding.likeButton.isChecked) {
api.likeThisPost(p.postContent.id).count
} else {
api.unlikeThisPost(p.postContent.id).count
}
val likeNicknames = getLikeNicknames(scope)
withContext(Dispatchers.Main) {
binding.likeList.text = likeNicknames.joinToString(", ")
binding.likeWrapper.isVisible = binding.likeList.text.isNotBlank()
}
} catch (e: Throwable) {
e.printStackTrace()
}
}
}
binding.removePostButton.setOnClickListener {
MainScope().launch(Dispatchers.IO) {
try {
api.deletePost(p.postContent.id)
withContext(Dispatchers.Main) {
Toast.makeText(binding.root.context, R.string.delete_success, Toast.LENGTH_SHORT).show()
onDeleteCallback?.invoke(p, bindingAdapterPosition)
}
} catch (e: Throwable) {
e.printStackTrace()
}
}
}
binding.shareButton.setOnClickListener {
val intentBuilder = ShareCompat.IntentBuilder(itemView.context)
intentBuilder.setType("text/plain").setText(shareString).startChooser()
}
commentAdapter.commentClickedHandler = { comment, _ ->
replyTo = comment
showCommentEditText()
}
binding.commentButton.setOnClickListener {
showCommentEditText()
}
binding.commentInput.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_SEND) {
MainScope().launch(Dispatchers.IO) {
try {
api.newComment(post!!.postContent.id!!, NewCommentRequest(
binding.commentInput.text.toString(),
replyTo?.data?.id
))
replyTo = null
withContext(Dispatchers.Main) {
hideCommentEditText()
(binding.commentView.adapter as? CommentRecyclerViewAdapter)?.apply {
clear()
fetchComments {
Toast.makeText(binding.root.context, R.string.comment_success, Toast.LENGTH_SHORT).show()
}
}
}
} catch (e: FuelError) {
e.printStackTrace()
}
}
return@setOnEditorActionListener true
}
false
}
KeyboardVisibilityEvent.setEventListener(activity, lifecycleOwner) { visible ->
if (!visible) {
hideCommentEditText()
}
}
}
private suspend fun getLikeNicknames(scope: CoroutineScope): List<String> {
val blockedUid = api.getBlacklist().map { blocked -> blocked.uid }
val likes = api.getNumOfLikes(post!!.postContent.id!!)
return likes.likesUidList
.filter { it !in blockedUid }
.map { scope.async { api.getUserInfo(it) } }
.awaitAll().map { it.nickname }
}
private fun showCommentEditText() {
binding.commentInput.visibility = View.VISIBLE
MainScope().launch {
delay(50)
binding.commentInput.requestFocus()
inputMethodManager.showSoftInput(binding.commentInput, 0)
if (bindingAdapterPosition != bindingAdapter!!.itemCount - 2) {
recyclerView.scrollToPosition(bindingAdapterPosition + 1)
}
delay(50)
if (bindingAdapterPosition == bindingAdapter!!.itemCount - 2) {
recyclerView.scrollToPosition(bindingAdapterPosition + 1)
} else {
recyclerView.scrollBy(0, -100)
}
}
}
private fun hideCommentEditText() {
binding.commentInput.visibility = View.GONE
inputMethodManager.hideSoftInputFromWindow(binding.root.windowToken, 0)
}
// share的时候只分享文字部分
private val shareString: String
get() {
if(post!!.postContent.type == PostType.normal) {
if(binding.postContent.text.isNotBlank()) {
return "${binding.userName.text} :\n 标题:${binding.postTitle.text}\n 内容:${binding.postContent.text}\n 时间:${binding.postTime.text}"
}
else {
return "${binding.userName.text} :\n 标题:${binding.postTitle.text}\n 时间:${binding.postTime.text}"
}
} else{
return "${binding.userName.text} :\n 标题:${binding.postTitle.text}\n 链接:${Uri.parse(post!!.postContent.mediaContent!!.media[0])}\n 时间:${binding.postTime.text}"
}
}
override fun onClickNinePhotoItem(
ninePhotoLayout: BGANinePhotoLayout?,
view: View?,
position: Int,
model: String?,
models: MutableList<String>?
) {
if (ninePhotoLayout == null) return
val intentBuilder = BGAPhotoPreviewActivity.IntentBuilder(binding.root.context)
if (ninePhotoLayout.itemCount == 1) {
intentBuilder.previewPhoto(ninePhotoLayout.currentClickItem)
} else {
intentBuilder.previewPhotos(ninePhotoLayout.data).currentPosition(ninePhotoLayout.currentClickItemPosition)
}
startActivity(binding.root.context, intentBuilder.build(), Bundle())
}
override fun onClickExpand(
ninePhotoLayout: BGANinePhotoLayout?,
view: View?,
position: Int,
model: String?,
models: MutableList<String>?
) {
ninePhotoLayout?.setIsExpand(true)
ninePhotoLayout?.flushItems()
}
}
| 0 |
Kotlin
|
0
| 2 |
a5c527b0073158a38ee658842dc2a759bb499268
| 13,642 |
thss-forum-android
|
MIT License
|
filehub/core/src/main/kotlin/org/jointwork/filehub/core/filesystem/FileSystemFile.kt
|
MockyJoke
| 288,097,110 | false | null |
package org.jointwork.filehub.core.filesystem
import org.jointwork.filehub.core.File
import org.jointwork.filehub.core.FileAccessor
import org.jointwork.filehub.core.FileConstants
import java.lang.IllegalArgumentException
import java.lang.IllegalStateException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.stream.Collectors
/**
* class property:
* - workingDirectory: represents actual Windows/Linux filesystem path
* - parentFile:
* */
class FileSystemFile(val workingDirectory : String, val filename : String, val parentFile : File) : File {
override fun listChild(): List<File> {
// Q: How "Paths.get()" works?
// The Path is obtained by invoking the getPath method of the default FileSystem.
val path = Paths.get(workingDirectory)
val temp : List<FileSystemFile> = Files.list(path)
.map { p -> FileSystemFile(p.fileName.toAbsolutePath().toString(), p.fileName.toString(), this) }
.collect(Collectors.toList())
return temp
}
override fun getName(): String {
return filename
}
// /root/photo/1.jpg
override fun getPath(): String {
return getParent().getPath() + FileConstants.FILE_DELIMITER +getName()
}
override fun getParent(): File {
return parentFile
}
override fun getAccessor(): FileAccessor {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun createFile(fileName: String): File {
// step :
// 1. create new java File object -> File file = new FIle('1.jpg')
// 2. Create new FileSystem File /photo/1.jpg
//
if(isDirectory()) {
throw IllegalStateException("creating a file on a file is not allowed")
}
val path : String = workingDirectory + FileConstants.FILE_DELIMITER + fileName
java.io.File(path).createNewFile()
return FileSystemFile(path, fileName, this )
}
override fun deleteFile(fileName: String) {
val path : String = workingDirectory + FileConstants.FILE_DELIMITER +fileName
java.io.File(path).delete()
}
override fun isDirectory(): Boolean {
return java.io.File(workingDirectory).isDirectory()
}
}
| 0 |
Kotlin
|
0
| 0 |
7b8c2811a4718bfdd92da9f09e5cc88bdc97ae4d
| 2,357 |
filehub
|
MIT License
|
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/persistence/entity/GameCancelableEventEntity.kt
|
Giancarmine
| 302,138,019 | true |
{"Kotlin": 1583986, "Java": 35534, "Shell": 2544, "Dockerfile": 2048, "TSQL": 1048}
|
package com.github.shynixn.blockball.core.logic.persistence.entity
open class GameCancelableEventEntity(var isCancelled: Boolean = false) {
}
| 0 | null |
0
| 0 |
bb7a65745440ef5578f6495a7380354cb64870c4
| 142 |
BlockBall
|
Apache License 2.0
|
src/commonMain/kotlin/com/adyen/model/legalentitymanagement/VerificationErrorMinusRecursive.kt
|
tjerkw
| 733,432,442 | false |
{"Kotlin": 5043126, "Makefile": 6356}
|
/**
* Legal Entity Management API
*
* The Legal Entity Management API enables you to manage legal entities that contain information required for verification. ## Authentication Your Adyen contact will provide your API credential and an API key. To connect to the API, add an `X-API-Key` header with the API key as the value. For example: ``` curl -H \"X-API-Key: YOUR_API_KEY\" \\ -H \"Content-Type: application/json\" \\ ... ``` Alternatively, you can use the username and password of your API credential to connect to the API using basic authentication. For example: ``` curl -U \"[email protected]_YOUR_COMPANY_ACCOUNT\":\"YourWsPassword\" \\ -H \"Content-Type: application/json\" \\ ... ``` ## Versioning The Legal Entity Management API supports [versioning](https://docs.adyen.com/development-resources/versioning) using a version suffix in the endpoint URL. This suffix has the following format: \"vXX\", where XX is the version number. For example: ``` https://kyc-test.adyen.com/lem/v3/legalEntities ``` >If you are using hosted onboarding, [only use v2](https://docs.adyen.com/release-notes/platforms-and-financial-products#releaseNote=2023-05-01-legal-entity-management-api-3) for your API requests. ## Going live When going live, your Adyen contact will provide your API credential for the live environment. You can then use the API key or the username and password to send requests to `https://kyc-live.adyen.com/lem/v3`.
*
* The version of the OpenAPI document: 3
*
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package com.adyen.model.legalentitymanagement
import com.adyen.model.legalentitymanagement.RemediatingAction
import com.adyen.model.legalentitymanagement.VerificationErrorMinusRecursive
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
/**
*
*
* @param capabilities Contains key-value pairs that specify the actions that the legal entity can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing.The value is an object containing the settings for the capability.
* @param code The general error code.
* @param message The general error message.
* @param remediatingActions An object containing possible solutions to fix a verification error.
* @param subErrors An array containing more granular information about the cause of the verification error.
* @param type The type of error.
*/
@Serializable
data class VerificationError (
/* Contains key-value pairs that specify the actions that the legal entity can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing.The value is an object containing the settings for the capability. */
@SerialName(value = "capabilities") val capabilities: kotlin.collections.List<VerificationError.Capabilities>? = null,
/* The general error code. */
@SerialName(value = "code") val code: kotlin.String? = null,
/* The general error message. */
@SerialName(value = "message") val message: kotlin.String? = null,
/* An object containing possible solutions to fix a verification error. */
@SerialName(value = "remediatingActions") val remediatingActions: kotlin.collections.List<RemediatingAction>? = null,
/* An array containing more granular information about the cause of the verification error. */
@SerialName(value = "subErrors") val subErrors: kotlin.collections.List<VerificationErrorMinusRecursive>? = null,
/* The type of error. */
@SerialName(value = "type") val type: VerificationError.Type? = null
) {
/**
* Contains key-value pairs that specify the actions that the legal entity can do in your platform. The key is a capability required for your integration. For example, **issueCard** for Issuing.The value is an object containing the settings for the capability.
*
* Values: AcceptExternalFunding,AcceptPspFunding,AcceptTransactionInRestrictedCountries,AcceptTransactionInRestrictedCountriesCommercial,AcceptTransactionInRestrictedCountriesConsumer,AcceptTransactionInRestrictedIndustries,AcceptTransactionInRestrictedIndustriesCommercial,AcceptTransactionInRestrictedIndustriesConsumer,Acquiring,AtmWithdrawal,AtmWithdrawalCommercial,AtmWithdrawalConsumer,AtmWithdrawalInRestrictedCountries,AtmWithdrawalInRestrictedCountriesCommercial,AtmWithdrawalInRestrictedCountriesConsumer,AuthorisedPaymentInstrumentUser,GetGrantOffers,IssueBankAccount,IssueCard,IssueCardCommercial,IssueCardConsumer,LocalAcceptance,Payout,PayoutToTransferInstrument,Processing,ReceiveFromBalanceAccount,ReceiveFromPlatformPayments,ReceiveFromThirdParty,ReceiveFromTransferInstrument,ReceiveGrants,ReceivePayments,SendToBalanceAccount,SendToThirdParty,SendToTransferInstrument,ThirdPartyFunding,UseCard,UseCardCommercial,UseCardConsumer,UseCardInRestrictedCountries,UseCardInRestrictedCountriesCommercial,UseCardInRestrictedCountriesConsumer,UseCardInRestrictedIndustries,UseCardInRestrictedIndustriesCommercial,UseCardInRestrictedIndustriesConsumer,WithdrawFromAtm,WithdrawFromAtmCommercial,WithdrawFromAtmConsumer,WithdrawFromAtmInRestrictedCountries,WithdrawFromAtmInRestrictedCountriesCommercial,WithdrawFromAtmInRestrictedCountriesConsumer
*/
@Serializable
enum class Capabilities(val value: kotlin.String) {
@SerialName(value = "acceptExternalFunding") AcceptExternalFunding("acceptExternalFunding"),
@SerialName(value = "acceptPspFunding") AcceptPspFunding("acceptPspFunding"),
@SerialName(value = "acceptTransactionInRestrictedCountries") AcceptTransactionInRestrictedCountries("acceptTransactionInRestrictedCountries"),
@SerialName(value = "acceptTransactionInRestrictedCountriesCommercial") AcceptTransactionInRestrictedCountriesCommercial("acceptTransactionInRestrictedCountriesCommercial"),
@SerialName(value = "acceptTransactionInRestrictedCountriesConsumer") AcceptTransactionInRestrictedCountriesConsumer("acceptTransactionInRestrictedCountriesConsumer"),
@SerialName(value = "acceptTransactionInRestrictedIndustries") AcceptTransactionInRestrictedIndustries("acceptTransactionInRestrictedIndustries"),
@SerialName(value = "acceptTransactionInRestrictedIndustriesCommercial") AcceptTransactionInRestrictedIndustriesCommercial("acceptTransactionInRestrictedIndustriesCommercial"),
@SerialName(value = "acceptTransactionInRestrictedIndustriesConsumer") AcceptTransactionInRestrictedIndustriesConsumer("acceptTransactionInRestrictedIndustriesConsumer"),
@SerialName(value = "acquiring") Acquiring("acquiring"),
@SerialName(value = "atmWithdrawal") AtmWithdrawal("atmWithdrawal"),
@SerialName(value = "atmWithdrawalCommercial") AtmWithdrawalCommercial("atmWithdrawalCommercial"),
@SerialName(value = "atmWithdrawalConsumer") AtmWithdrawalConsumer("atmWithdrawalConsumer"),
@SerialName(value = "atmWithdrawalInRestrictedCountries") AtmWithdrawalInRestrictedCountries("atmWithdrawalInRestrictedCountries"),
@SerialName(value = "atmWithdrawalInRestrictedCountriesCommercial") AtmWithdrawalInRestrictedCountriesCommercial("atmWithdrawalInRestrictedCountriesCommercial"),
@SerialName(value = "atmWithdrawalInRestrictedCountriesConsumer") AtmWithdrawalInRestrictedCountriesConsumer("atmWithdrawalInRestrictedCountriesConsumer"),
@SerialName(value = "authorisedPaymentInstrumentUser") AuthorisedPaymentInstrumentUser("authorisedPaymentInstrumentUser"),
@SerialName(value = "getGrantOffers") GetGrantOffers("getGrantOffers"),
@SerialName(value = "issueBankAccount") IssueBankAccount("issueBankAccount"),
@SerialName(value = "issueCard") IssueCard("issueCard"),
@SerialName(value = "issueCardCommercial") IssueCardCommercial("issueCardCommercial"),
@SerialName(value = "issueCardConsumer") IssueCardConsumer("issueCardConsumer"),
@SerialName(value = "localAcceptance") LocalAcceptance("localAcceptance"),
@SerialName(value = "payout") Payout("payout"),
@SerialName(value = "payoutToTransferInstrument") PayoutToTransferInstrument("payoutToTransferInstrument"),
@SerialName(value = "processing") Processing("processing"),
@SerialName(value = "receiveFromBalanceAccount") ReceiveFromBalanceAccount("receiveFromBalanceAccount"),
@SerialName(value = "receiveFromPlatformPayments") ReceiveFromPlatformPayments("receiveFromPlatformPayments"),
@SerialName(value = "receiveFromThirdParty") ReceiveFromThirdParty("receiveFromThirdParty"),
@SerialName(value = "receiveFromTransferInstrument") ReceiveFromTransferInstrument("receiveFromTransferInstrument"),
@SerialName(value = "receiveGrants") ReceiveGrants("receiveGrants"),
@SerialName(value = "receivePayments") ReceivePayments("receivePayments"),
@SerialName(value = "sendToBalanceAccount") SendToBalanceAccount("sendToBalanceAccount"),
@SerialName(value = "sendToThirdParty") SendToThirdParty("sendToThirdParty"),
@SerialName(value = "sendToTransferInstrument") SendToTransferInstrument("sendToTransferInstrument"),
@SerialName(value = "thirdPartyFunding") ThirdPartyFunding("thirdPartyFunding"),
@SerialName(value = "useCard") UseCard("useCard"),
@SerialName(value = "useCardCommercial") UseCardCommercial("useCardCommercial"),
@SerialName(value = "useCardConsumer") UseCardConsumer("useCardConsumer"),
@SerialName(value = "useCardInRestrictedCountries") UseCardInRestrictedCountries("useCardInRestrictedCountries"),
@SerialName(value = "useCardInRestrictedCountriesCommercial") UseCardInRestrictedCountriesCommercial("useCardInRestrictedCountriesCommercial"),
@SerialName(value = "useCardInRestrictedCountriesConsumer") UseCardInRestrictedCountriesConsumer("useCardInRestrictedCountriesConsumer"),
@SerialName(value = "useCardInRestrictedIndustries") UseCardInRestrictedIndustries("useCardInRestrictedIndustries"),
@SerialName(value = "useCardInRestrictedIndustriesCommercial") UseCardInRestrictedIndustriesCommercial("useCardInRestrictedIndustriesCommercial"),
@SerialName(value = "useCardInRestrictedIndustriesConsumer") UseCardInRestrictedIndustriesConsumer("useCardInRestrictedIndustriesConsumer"),
@SerialName(value = "withdrawFromAtm") WithdrawFromAtm("withdrawFromAtm"),
@SerialName(value = "withdrawFromAtmCommercial") WithdrawFromAtmCommercial("withdrawFromAtmCommercial"),
@SerialName(value = "withdrawFromAtmConsumer") WithdrawFromAtmConsumer("withdrawFromAtmConsumer"),
@SerialName(value = "withdrawFromAtmInRestrictedCountries") WithdrawFromAtmInRestrictedCountries("withdrawFromAtmInRestrictedCountries"),
@SerialName(value = "withdrawFromAtmInRestrictedCountriesCommercial") WithdrawFromAtmInRestrictedCountriesCommercial("withdrawFromAtmInRestrictedCountriesCommercial"),
@SerialName(value = "withdrawFromAtmInRestrictedCountriesConsumer") WithdrawFromAtmInRestrictedCountriesConsumer("withdrawFromAtmInRestrictedCountriesConsumer");
}
/**
* The type of error.
*
* Values: DataMissing,DataReview,InvalidInput,PendingStatus,Rejected
*/
@Serializable
enum class Type(val value: kotlin.String) {
@SerialName(value = "dataMissing") DataMissing("dataMissing"),
@SerialName(value = "dataReview") DataReview("dataReview"),
@SerialName(value = "invalidInput") InvalidInput("invalidInput"),
@SerialName(value = "pendingStatus") PendingStatus("pendingStatus"),
@SerialName(value = "rejected") Rejected("rejected");
}
}
| 0 |
Kotlin
|
0
| 0 |
2da5aea5519b2dfa84454fe1665e9699edc87507
| 11,926 |
adyen-kotlin-multiplatform-api-library
|
MIT License
|
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/Geometry.kt
|
walter-juan
| 868,046,028 | false |
{"Kotlin": 20416825}
|
package com.woowla.compose.icon.collections.tabler.tabler.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup
import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound
import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound
public val OutlineGroup.Geometry: ImageVector
get() {
if (_geometry != null) {
return _geometry!!
}
_geometry = Builder(name = "Geometry", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(7.0f, 21.0f)
lineToRelative(4.0f, -12.0f)
moveToRelative(2.0f, 0.0f)
lineToRelative(1.48f, 4.439f)
moveToRelative(0.949f, 2.847f)
lineToRelative(1.571f, 4.714f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(12.0f, 7.0f)
moveToRelative(-2.0f, 0.0f)
arcToRelative(2.0f, 2.0f, 0.0f, true, false, 4.0f, 0.0f)
arcToRelative(2.0f, 2.0f, 0.0f, true, false, -4.0f, 0.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(4.0f, 12.0f)
curveToRelative(1.526f, 2.955f, 4.588f, 5.0f, 8.0f, 5.0f)
curveToRelative(3.41f, 0.0f, 6.473f, -2.048f, 8.0f, -5.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(12.0f, 5.0f)
verticalLineToRelative(-2.0f)
}
}
.build()
return _geometry!!
}
private var _geometry: ImageVector? = null
| 0 |
Kotlin
|
0
| 1 |
b037895588c2f62d069c724abe624b67c0889bf9
| 2,974 |
compose-icon-collections
|
MIT License
|
kotlin-electron/src/jsMain/generated/electron/core/HandlerDetailsDisposition.kt
|
JetBrains
| 93,250,841 | false | null |
package electron.core
@Suppress(
"NAME_CONTAINS_ILLEGAL_CHARS",
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
@JsName("""(/*union*/{default: 'default', foregroundTab: 'foreground-tab', backgroundTab: 'background-tab', newWindow: 'new-window', other: 'other'}/*union*/)""")
sealed external interface HandlerDetailsDisposition {
companion object {
val default: HandlerDetailsDisposition
val foregroundTab: HandlerDetailsDisposition
val backgroundTab: HandlerDetailsDisposition
val newWindow: HandlerDetailsDisposition
val other: HandlerDetailsDisposition
}
}
| 32 | null |
174
| 1,252 |
8f788651776064a30ce1688160b7ef9c314a6fe9
| 609 |
kotlin-wrappers
|
Apache License 2.0
|
src/main/kotlin/no/nav/familie/ef/iverksett/økonomi/grensesnitt/GrensesnittavstemmingDto.kt
|
navikt
| 357,821,728 | false |
{"Kotlin": 810975, "Gherkin": 73692, "Dockerfile": 193}
|
package no.nav.familie.ef.iverksett.økonomi.grensesnitt
import no.nav.familie.kontrakter.felles.ef.StønadType
import no.nav.familie.kontrakter.felles.objectMapper
import no.nav.familie.prosessering.domene.Task
import no.nav.familie.util.VirkedagerProvider
import java.time.LocalDate
import java.time.LocalDateTime
data class GrensesnittavstemmingDto(
val stønadstype: StønadType,
val fraDato: LocalDate,
val triggerTid: LocalDateTime? = null,
)
fun GrensesnittavstemmingDto.tilTask(): Task {
val nesteVirkedag: LocalDateTime = triggerTid ?: VirkedagerProvider.nesteVirkedag(fraDato).atTime(8, 0)
val payload =
objectMapper.writeValueAsString(
GrensesnittavstemmingPayload(
fraDato = this.fraDato,
stønadstype = this.stønadstype,
),
)
return Task(
type = GrensesnittavstemmingTask.TYPE,
payload = payload,
triggerTid = nesteVirkedag,
)
}
| 3 |
Kotlin
|
0
| 0 |
cc2ef2e5f83f202a8029f7a1b39c43c8f6b30652
| 965 |
familie-ef-iverksett
|
MIT License
|
app/src/main/java/net/ballmerlabs/lesnoop/MainActivity.kt
|
fmeef
| 562,555,257 | false |
{"Kotlin": 74449}
|
package net.ballmerlabs.lesnoop
import android.Manifest
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.material3.TopAppBarDefaults.pinnedScrollBehavior
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.rxjava3.subscribeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.VerticalAlignmentLine
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.unit.dp
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import androidx.datastore.preferences.rxjava3.rxPreferencesDataStore
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.dialog
import androidx.navigation.compose.rememberNavController
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.PermissionState
import com.google.accompanist.permissions.rememberPermissionState
import net.ballmerlabs.lesnoop.db.OuiParser
import net.ballmerlabs.lesnoop.ui.theme.BlerfTheme
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.launch
import javax.inject.Inject
const val NAV_SCAN = "scan"
const val NAV_DB = "database"
const val NAV_DIALOG = "dialog"
const val PREF_NAME = "scanprefs"
val Context.rxPrefs by rxPreferencesDataStore(PREF_NAME)
val PREF_BACKGROUND_SCAN = booleanPreferencesKey("background_scan")
@OptIn(ExperimentalPermissionsApi::class)
data class PermissionText(
val permission: PermissionState,
val excuse: String
)
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
@Inject
lateinit var scanSnoopService: ScanSnoopService
@OptIn(ExperimentalPermissionsApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
BlerfTheme {
Body {
scanSnoopService
}
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TopBar() {
val model = hiltViewModel<ScanViewModel>()
TopAppBar(
title = {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(end = 8.dp),
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(model.topText.value, style = MaterialTheme.typography.headlineLarge)
val d = model.scanInProgress.value
if (d != null) {
Button(
onClick = {
model.scanInProgress.value = null
d.dispose()
}
) {
Text(text = stringResource(id = R.string.stop_scan))
}
}
}
},
scrollBehavior = pinnedScrollBehavior()
)
}
@Composable
@ExperimentalPermissionsApi
fun ScopePermissions(
modifier: Modifier = Modifier,
content: @Composable () -> Unit
) {
val permissions = mutableListOf(
PermissionText(
permission = rememberPermissionState(permission = Manifest.permission.ACCESS_FINE_LOCATION),
excuse = "Blerf needs the ACCESS_FINE_LOCATION permission for performing offline bluetooth scans in the background" +
" and locally geotagging the discovered devices. This information is never shared or transmitted in any way."
)
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
for (x in listOf(
Manifest.permission.BLUETOOTH_SCAN,
Manifest.permission.BLUETOOTH_CONNECT
)) {
val p = PermissionText(
permission = rememberPermissionState(permission = x),
excuse = "The $x permission is required for" +
" discovering bluetooth devices in the background"
)
permissions.add(p)
}
}
val granted = permissions.all { s ->
s.permission.status == com.google.accompanist.permissions.PermissionStatus.Granted
}
if (granted) {
Box(modifier = modifier) {
content()
}
} else {
Box(
modifier = modifier,
contentAlignment = Alignment.Center
) {
val p =
permissions.first { p -> p.permission.status != com.google.accompanist.permissions.PermissionStatus.Granted }
Button(
onClick = { p.permission.launchPermissionRequest() }
) {
Text(modifier = Modifier.padding(8.dp),text = p.excuse)
}
}
}
}
@OptIn(ExperimentalCoroutinesApi::class)
@Composable
@ExperimentalPermissionsApi
fun ScanDialog(s: () -> ScanSnoopService) {
val service by remember { derivedStateOf(s) }
val legacy = remember { mutableStateOf(false) }
val selected = remember {
mutableStateOf("")
}
val started: Boolean? by service.serviceState().observeAsState()
// val p = context.rxPrefs.data().map { p -> p[PREF_BACKGROUND_SCAN]?: false }.subscribeAsState(initial = false)
ScopePermissions {
Surface(
modifier = Modifier
.background(
color = MaterialTheme.colorScheme.background,
shape = RoundedCornerShape(8.dp)
)
.padding(8.dp)
) {
Column {
Text(
text = stringResource(id = R.string.background_scan),
style = MaterialTheme.typography.headlineSmall
)
Text(text = stringResource(id = R.string.scan_disclaimer))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(text = stringResource(id = R.string.legacy_toggle))
Switch(checked = legacy.value, onCheckedChange = { v -> legacy.value = v })
}
Row {
Button(
onClick = { service.startScanToDb(legacy.value) },
enabled = !(started?:false)
) {
Text(text = stringResource(id = R.string.start_scan))
}
Button(
onClick = { service.stopScan() },
enabled = started?:false
) {
Text(text = stringResource(id = R.string.stop_scan))
}
}
}
}
}
}
@Composable
fun BottomBar(navController: NavController) {
BottomAppBar {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Row(horizontalArrangement = Arrangement.Start) {
Button(
modifier = Modifier.padding(start = 5.dp, end = 5.dp),
onClick = { navController.navigate(NAV_SCAN) }
) {
Text(text = stringResource(id = R.string.scan))
}
Button(
modifier = Modifier.padding(start = 5.dp, end = 5.dp),
onClick = { navController.navigate(NAV_DB) }
) {
Text(text = stringResource(id = R.string.database))
}
}
Button(
onClick = { navController.navigate(NAV_DIALOG) }
) {
Icon(
imageVector = ImageVector.vectorResource(R.drawable.ic_baseline_perm_scan_wifi_24),
stringResource(id = R.string.toggle)
)
}
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@ExperimentalPermissionsApi
fun Body(service: () -> ScanSnoopService) {
val navController = rememberNavController()
val model = hiltViewModel<ScanViewModel>()
Scaffold(
content = { padding ->
NavHost(navController = navController, startDestination = NAV_SCAN) {
composable(NAV_SCAN) {
model.topText.value = stringResource(id = R.string.nearby)
ScopePermissions(modifier = Modifier.fillMaxSize()) {
DeviceList(padding, model)
}
}
composable(NAV_DB) {
model.topText.value = stringResource(id = R.string.database)
EmptyTest(padding, model)
}
dialog(NAV_DIALOG) { ScanDialog(service) }
}
},
bottomBar = { BottomBar(navController) },
topBar = { TopBar() }
)
}
| 0 |
Kotlin
|
0
| 1 |
e727c895dbf42ac8967c648c2adcc0f3ab1a703e
| 9,814 |
blerf
|
Apache License 2.0
|
src/test/kotlin/aoc15/day3/TestDay3.kt
|
chezbazar
| 728,404,822 | false |
{"Kotlin": 100278}
|
package aoc15.day3
import fr.chezbazar.aoc15.day3.distribute
import fr.chezbazar.aoc15.day3.getHousesSetFrom
import kotlin.test.Test
import kotlin.test.assertEquals
class TestDay3 {
@Test
fun testHouseDelivery() {
assertEquals(2, getHousesSetFrom(">").size)
assertEquals(4, getHousesSetFrom("^>v<").size)
assertEquals(2, getHousesSetFrom("^v^v^v^v^v").size)
}
@Test
fun testRobotHouseDelivery() {
val testValues = listOf("^v" to 3, "^>v<" to 3, "^v^v^v^v^v" to 11)
testValues.forEach { (path, expectedVal) ->
val (santaPath, robotSantaPath) = path.distribute()
assertEquals(expectedVal, getHousesSetFrom(santaPath).union(getHousesSetFrom(robotSantaPath)).size)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
6d8a40f2cf8b56fb36ad2aae77bfd1e4142ab92e
| 765 |
adventofcode
|
MIT License
|
src/commonMain/kotlin/guru/zoroark/pangoro/PangoroParsingContext.kt
|
utybo
| 261,469,155 | false | null |
package guru.zoroark.pangoro
import guru.zoroark.lixy.LixyToken
/**
* This object contains the information that is passed to expectations, and is
* global over a single parser run.
*
* @property tokens The list of tokens that should be parsed
*
* @property typeMap A map with all of the known declared types and their
* description
*/
class PangoroParsingContext(
val tokens: List<LixyToken>,
val typeMap: Map<PangoroNodeDeclaration<*>, PangoroDescribedType>
)
| 1 |
Kotlin
|
0
| 8 |
963e63771452e0efcffcfe47e5513e980477fb91
| 478 |
Pangoro
|
Apache License 2.0
|
src/test/kotlin/com/wcarmon/codegen/httpclient/OkHttpClientTest.kt
|
wcarmon
| 382,707,115 | false | null |
package com.wcarmon.codegen.httpclient
import com.fasterxml.jackson.databind.ObjectMapper
import okhttp3.OkHttpClient
import org.junit.jupiter.api.AfterAll
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.mockserver.model.HttpRequest
import org.mockserver.model.HttpRequest.request
import org.mockserver.model.HttpResponse
import org.testcontainers.containers.MockServerContainer
import java.net.URL
//@Testcontainers
internal class OkHttpClientTest {
companion object {
private lateinit var container: MockServerContainer
@BeforeAll
@JvmStatic
fun beforeClass() {
container = buildMockServerContainer()
container.start()
}
@AfterAll
@JvmStatic
fun afterClass() = container.stop()
}
lateinit var subject: ExampleGeneratedHTTPClient
@BeforeEach
fun setUp() {
val objectMapper = ObjectMapper()
val okhttpClient = OkHttpClient()
subject = ExampleGeneratedHTTPClient(
baseUrl = URL("http://${container.host}:${container.serverPort}/api/v1"),
objectReader = objectMapper.reader(),
objectWriter = objectMapper.writer(),
okHttpClient = okhttpClient,
)
}
@Test
fun aaa() {
// -- Arrange
val uri = "/api/v1/chrono-board"
val mockConfig = getMockConfig(container)
mockConfig
.`when`(
request()
// .withBody("""{"entity":7}""")
.withMethod("POST")
.withPath(uri)
)
.respond(
HttpResponse.response()
.withBody("whatever")
.withStatusCode(201)
)
// .verify(
// request()
// .withPath("$baseUrl/chrono-board"),
// VerificationTimes.atLeast(2)
// )
val entity = "foo"
// -- Act
subject.doCreateEntity(entity)
// -- Assert
val recorded = mockConfig.retrieveRecordedRequests(
request()
.withMethod("POST")
.withPath(uri)
)
assertEquals(1, recorded.size)
assertTrue(recorded[0] is HttpRequest)
val recordedReq = recorded[0] as HttpRequest
//TODO: something like this
// assertEquals("""{"a": 123}""", recordedReq.body)
//TODO: clear things on the mock server (or run tests one at a time or make multiple servers)
}
}
| 0 |
Kotlin
|
0
| 0 |
c79fc1bb2a6f748b3fdd09e3e64fe854fa85f650
| 2,415 |
codegen
|
MIT License
|
app/src/main/java/com/rathanak/khmerroman/view/dialog/EnableKeyboardDialog.kt
|
khmerlang
| 244,078,839 | false |
{"Kotlin": 162074}
|
package com.rathanak.khmerroman.view.dialog
import androidx.appcompat.app.AlertDialog
import android.app.Dialog
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import androidx.fragment.app.DialogFragment
import com.rathanak.khmerroman.R
import kotlinx.android.synthetic.main.enable_keyboard_dialog.view.*
class EnableKeyboardDialog : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
val builder = AlertDialog.Builder(it)
val inflater = requireActivity().layoutInflater
val rkDialogView = inflater.inflate(R.layout.enable_keyboard_dialog, null)
rkDialogView.btn_ok.setOnClickListener {
dismiss()
startActivity(Intent(Settings.ACTION_INPUT_METHOD_SETTINGS))
}
builder.setView(rkDialogView)
builder.create()
} ?: throw IllegalStateException("Activity cannot be null")
}
companion object {
const val TAG = "enable_keyboard_dialog_tag"
}
}
| 0 |
Kotlin
|
0
| 19 |
e4c414fbd62596dbb9f704915cf904c819cc572c
| 1,132 |
Khmerlang-Keyboard
|
MIT License
|
src/main/kotlin/online/bingzi/database/typeimpl/DatabaseSQL.kt
|
BingZi-233
| 404,354,499 | false | null |
package online.bingzi.database.typeimpl
import online.bingzi.database.Database
import online.bingzi.util.Tools.confDatabase
import taboolib.module.database.*
/**
* MySQL链接
*/
class DatabaseSQL : Database() {
private val host = confDatabase.getHost("MySQL")
private val tableVar = Table("${confDatabase.getString("MySQL.TablePrefix")}_player_oxygen", host) {
add { id() }
// 唯一主键
add("username") {
type(ColumnTypeSQL.VARCHAR, 64) {
options(ColumnOptionSQL.KEY)
}
}
add("data") {
type(ColumnTypeSQL.TEXT)
}
add("count") {
type(ColumnTypeSQL.INT)
}
}
override fun host(): Host<*> {
return host
}
override fun tableVar(): Table<*, *> {
return tableVar
}
}
| 0 |
Kotlin
|
0
| 1 |
2df835f6d5c0a17ab9b7a7709b63024d426702dc
| 829 |
OxygenVault
|
Creative Commons Zero v1.0 Universal
|
src/main/kotlin/Day06.kt
|
JPQuirmbach
| 572,636,904 | false | null |
fun main() {
fun parseInput(input: String, markerSize: Int): Int {
return input.windowed(markerSize)
.indexOfFirst { it ->
it.groupingBy { it }
.eachCount()
.values
.max() == 1
} + markerSize
}
fun part1(input: String): Int {
return parseInput(input, 4)
}
fun part2(input: String): Int {
return parseInput(input, 14)
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day06_test")
check(part1(testInput) == 7)
check(part2(testInput) == 19)
val input = readInput("Day06")
println(part1(input))
println(part2(input))
}
| 0 |
Kotlin
|
0
| 0 |
829e11bd08ff7d613280108126fa6b0b61dcb819
| 746 |
advent-of-code-Kotlin-2022
|
Apache License 2.0
|
src/aoc2023/Day9.kt
|
RobertMaged
| 573,140,924 | false |
{"Kotlin": 219797}
|
package aoc2023
import utils.checkEquals
import utils.readInput
fun main(): Unit = with(Day9) {
part1(testInput).checkEquals(114)
part1(input)
.checkEquals(1980437560)
// .sendAnswer(part = 1, day = "9", year = 2023)
part2(testInput).checkEquals(2)
part2(input)
.checkEquals(977)
// .sendAnswer(part = 2, day = "9", year = 2023)
}
object Day9 {
fun String.buildHistoryHierarchy(transform: (List<Long>) -> Long): List<Long> {
val sequence = this.split(' ').map { it.toLong() }
val history = mutableListOf<List<Long>>(sequence)
while (history.last().any { it != 0L }) {
val diff = history.last().zipWithNext { a, b -> b - a }
history.add(diff)
}
return history.map(transform)
}
fun part1(input: List<String>): Long = input.sumOf { line ->
val lastStepInHistoryHierarchy = line.buildHistoryHierarchy { it.last() }
return@sumOf lastStepInHistoryHierarchy.foldRight(0L) { acc, n ->
acc + n
}
}
fun part2(input: List<String>): Long = input.sumOf { line ->
val firstValueInEachHistory = line.buildHistoryHierarchy { it.first() }
return@sumOf firstValueInEachHistory.foldRight(0L) { acc, n ->
acc - n
}
}
val input
get() = readInput("Day9", "aoc2023")
val testInput
get() = readInput("Day9_test", "aoc2023")
}
| 0 |
Kotlin
|
0
| 0 |
22f48b6eb02bdaa4c3d55fc67fdbd01bd395941e
| 1,453 |
Kotlin-AOC-2023
|
Apache License 2.0
|
feature/item-editing/src/main/kotlin/io/github/edwinchang24/salvage/feature/itemediting/ItemEditingNavigation.kt
|
EdwinChang24
| 653,775,661 | false | null |
package io.github.edwinchang24.salvage.feature.itemediting
import android.content.Context
import android.content.Intent
fun Context.startEditItemActivity(itemId: String) = startActivity(
Intent()
.setClass(this, ItemEditingActivity::class.java)
.putExtra(ExistingItemId, itemId)
)
fun Context.startNewItemActivity() = startActivity(
Intent().setClass(this, ItemEditingActivity::class.java)
)
| 6 |
Kotlin
|
0
| 0 |
f6ee701304c2e69618af13cde7d95fe21cbf9329
| 419 |
salvage
|
MIT License
|
app/src/main/kotlin/com/mygallery/ui/photo/PhotoPagerPresenter.kt
|
BrianLusina
| 121,283,701 | false | null |
package com.mygallery.ui.photo
import com.mygallery.ui.base.BasePresenter
interface PhotoPagerPresenter<V : PhotoPagerView> : BasePresenter<V> {
/**
* Prepares for the shared element transition
* */
fun onPrepareSharedElementTransition()
fun onRetrieveBundle()
}
| 0 |
Kotlin
|
0
| 0 |
3d4ae9363de4b8bee3cf76f8caa72dd42faa5bf0
| 289 |
mygallery
|
MIT License
|
domain/src/main/java/com/safetyheads/akademiaandroida/domain/repositories/CareerRepository.kt
|
SafetyHeads
| 590,936,924 | false | null |
package com.safetyheads.akademiaandroida.domain.repositories
import com.safetyheads.akademiaandroida.domain.entities.JobOffer
import kotlinx.coroutines.flow.Flow
interface CareerRepository {
suspend fun getJobOffersList(): Flow<List<JobOffer>>
}
| 7 |
Kotlin
|
0
| 0 |
c150bf378ff23a047bc23d19753b000f71b88511
| 254 |
Akademia-Androida-2023
|
Apache License 2.0
|
test-utils/android/src/main/java/com/instacart/testutils/android/TestViewFactory.kt
|
instacart
| 171,923,573 | false |
{"Kotlin": 565903, "Shell": 1203, "Ruby": 256}
|
package com.instacart.testutils.android
import android.view.View
import com.instacart.formula.android.FeatureView
import com.instacart.formula.android.FragmentLifecycleCallback
import com.instacart.formula.android.LayoutViewFactory
import com.instacart.formula.android.ViewInstance
class TestViewFactory<RenderModel>(
private val fragmentLifecycleCallbacks: FragmentLifecycleCallback? = null,
private val render: (View, RenderModel) -> Unit = { _, _ -> },
) : LayoutViewFactory<RenderModel>(R.layout.test_fragment_layout) {
override fun ViewInstance.create(): FeatureView<RenderModel> {
return featureView(fragmentLifecycleCallbacks) {
render(view, it)
}
}
}
| 7 |
Kotlin
|
14
| 151 |
26d544ea41b7a5ab2fa1a3b9ac6b668e69fe4dff
| 704 |
formula
|
BSD 3-Clause Clear License
|
app/src/main/java/com/axel/viewmodelpractise/activity/MainActivity.kt
|
axelasa
| 444,801,020 | false | null |
package com.axel.viewmodelpractise.activity
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.axel.viewmodelpractise.databinding.ActivityMainBinding
import com.axel.viewmodelpractise.viewmodel.IncrementViewModel
class MainActivity : AppCompatActivity() {
private lateinit var binding:ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
//instanciate the viewmodel class in your main activity
val viewModel = ViewModelProvider(this)[IncrementViewModel::class.java]
binding.numberView.text = viewModel.counter.toString()
//business logic to carryout operation
binding.increment.setOnClickListener {
viewModel.add()
binding.numberView.text = viewModel.counter.toString()
}
binding.decrement.setOnClickListener {
viewModel.subtract()
binding.numberView.text = viewModel.counter.toString()
}
}
}
| 0 |
Kotlin
|
0
| 0 |
f2a38bfb88cdbdcedf8ef1b9f0729c39e3814e83
| 1,171 |
ViewModelPractise
|
MIT License
|
app/src/main/java/com/cesarwillymc/agrostest/presentation/main/ui/dashboard/common/Conditionals.kt
|
cesarwillymc
| 392,344,387 | false | null |
package com.cesarwillymc.agrostest.presentation.main.ui.dashboard.common
fun isLastItemandInpair(size:Int,position:Int):Boolean{
return (size%2!=0) && (size-1==position)
}
| 0 |
Kotlin
|
0
| 0 |
8b8e63e33027431477462f28a2b1529decd75578
| 176 |
AgrosTest
|
Apache License 2.0
|
youtils/src/main/java/dev/prabhatpandey/youtils/views/imageview/ImageViewExt.kt
|
prabhatsdp
| 516,599,392 | false | null |
package dev.prabhatpandey.youtils.views.imageview
import android.content.res.ColorStateList
import android.widget.ImageView
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
/**
* Sets the tint color for the image of this ImageView using a color resource.
*
* This method applies a tint color to the image of the ImageView, changing its color appearance.
* The tint color is specified by the given color resource, which is resolved to an actual color value.
*
* @param colorRes The color resource ID representing the desired tint color.
* @see [ContextCompat.getColor]
*/
fun ImageView.setTint(@ColorRes colorRes: Int) {
this.imageTintList = ColorStateList.valueOf(ContextCompat.getColor(this.context, colorRes))
}
| 0 |
Kotlin
|
0
| 0 |
45ebe0f50d898e1db29eb2e6125185041bad8622
| 757 |
youtils
|
MIT License
|
src/test/kotlin/com/cognifide/gradle/aem/test/PackageComposeTest.kt
|
killakam3084
| 224,489,898 | true |
{"Kotlin": 642093, "Shell": 5281, "Java": 2130, "Batchfile": 267}
|
package com.cognifide.gradle.aem.test
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.junitpioneer.jupiter.TempDirectory
@ExtendWith(TempDirectory::class)
class PackageComposeTest : AemTest() {
@Test
fun shouldComposePackageWithBundleAndContent() {
buildTask("package-compose/bundle-and-content", ":packageCompose") {
val pkg = file("build/aem/packageCompose/example-1.0.0-SNAPSHOT.zip")
assertPackage(pkg)
assertPackageFile(pkg, "jcr_root/apps/example/.content.xml")
assertPackageFile(pkg, "jcr_root/apps/example/install/example-1.0.0-SNAPSHOT.jar")
assertPackageFile(pkg, "META-INF/vault/hooks/hook.jar")
assertPackageFile(pkg, "META-INF/vault/nodetypes.cnd")
}
}
@Test
fun shouldComposePackageAssemblyAndSingles() {
buildTasks("package-compose/assembly", "packageCompose") {
val assemblyPkg = file("build/aem/packageCompose/example-1.0.0-SNAPSHOT.zip")
assertPackage(assemblyPkg)
assertPackageFile(assemblyPkg, "jcr_root/apps/example/core/.content.xml")
assertPackageBundle(assemblyPkg, "jcr_root/apps/example/core/install/example.core-1.0.0-SNAPSHOT.jar")
assertPackageFile(assemblyPkg, "jcr_root/apps/example/common/.content.xml")
assertPackageBundle(assemblyPkg, "jcr_root/apps/example/common/install/example.common-1.0.0-SNAPSHOT.jar")
assertPackageBundle(assemblyPkg, "jcr_root/apps/example/common/install/kotlin-osgi-bundle-1.2.21.jar")
assertPackageFile(assemblyPkg, "jcr_root/etc/designs/example/.content.xml")
assertPackageFile(assemblyPkg, "META-INF/vault/hooks/hook1.jar")
assertPackageFile(assemblyPkg, "META-INF/vault/hooks/hook2.jar")
val corePkg = file("core/build/aem/packageCompose/example.core-1.0.0-SNAPSHOT.zip")
assertPackage(corePkg)
assertPackageFile(corePkg, "jcr_root/apps/example/core/.content.xml")
assertPackageBundle(corePkg, "jcr_root/apps/example/core/install/example.core-1.0.0-SNAPSHOT.jar")
val commonPkg = file("common/build/aem/packageCompose/example.common-1.0.0-SNAPSHOT.zip")
assertPackage(commonPkg)
assertPackageFile(commonPkg, "jcr_root/apps/example/common/.content.xml")
assertPackageBundle(commonPkg, "jcr_root/apps/example/common/install/example.common-1.0.0-SNAPSHOT.jar")
assertPackageFile(commonPkg, "jcr_root/apps/example/common/install/kotlin-osgi-bundle-1.2.21.jar")
val designPkg = file("design/build/aem/packageCompose/example.design-1.0.0-SNAPSHOT.zip")
assertPackage(designPkg)
assertPackageFile(designPkg, "jcr_root/etc/designs/example/.content.xml")
}
}
}
| 0 | null |
0
| 0 |
8aadf05f2e8fd5b11b4a98b22492880bfafdddf9
| 2,864 |
gradle-aem-plugin
|
Apache License 2.0
|
app/src/main/java/org/metabrainz/android/data/sources/api/ServiceModule.kt
|
metabrainz
| 166,439,000 | false | null |
package org.metabrainz.android.data.sources.api
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import org.metabrainz.android.data.sources.api.MusicBrainzServiceGenerator.createService
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class ServiceModule {
@get:Provides
@get:Singleton
val lookupService: LookupService = createService(LookupService::class.java, true)
@get:Provides
@get:Singleton
val blogService: BlogService = createService(BlogService::class.java, true)
@get:Provides
@get:Singleton
val collectionService: CollectionService = createService(CollectionService::class.java, true)
@get:Provides
@get:Singleton
val loginService: LoginService = createService(LoginService::class.java, false)
}
| 4 | null |
21
| 65 |
665e8ca4eeeae2ce507a6a522147ac750882b334
| 860 |
musicbrainz-android
|
Apache License 2.0
|
kittybot/src/main/kotlin/org/bezsahara/kittybot/telegram/classes/media/Document.kt
|
bezsahara
| 846,146,531 | false |
{"Kotlin": 752625}
|
package org.bezsahara.kittybot.telegram.classes.media
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import org.bezsahara.kittybot.telegram.classes.media.photos.PhotoSize
/**
* This object represents a general file (as opposed to photos, voice messages and audio files).
*
* *[link](https://core.telegram.org/bots/api#document)*: https://core.telegram.org/bots/api#document
*
* @param fileId Identifier for this file, which can be used to download or reuse the file
* @param fileUniqueId Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
* @param thumbnail Optional. Document thumbnail as defined by sender
* @param fileName Optional. Original filename as defined by sender
* @param mimeType Optional. MIME type of the file as defined by sender
* @param fileSize Optional. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.
*/
@Serializable
data class Document(
@SerialName("file_id") val fileId: String,
@SerialName("file_unique_id") val fileUniqueId: String,
val thumbnail: PhotoSize? = null,
@SerialName("file_name") val fileName: String? = null,
@SerialName("mime_type") val mimeType: String? = null,
@SerialName("file_size") val fileSize: Long? = null
)
| 0 |
Kotlin
|
1
| 5 |
a0b831c9f4ad00f681b2bfba5376e321766a8cfe
| 1,544 |
TelegramKitty
|
MIT License
|
03/MasterDetail/app/src/main/java/com/lfg/masterdetail/fragments/ListFragment.kt
|
leonelgomez1990
| 402,218,277 | false | null |
package com.lfg.masterdetail.fragments
import android.content.Context
import android.content.SharedPreferences
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.navigation.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lfg.masterdetail.R
import com.lfg.masterdetail.adapters.ProductAdapter
import com.lfg.masterdetail.repositories.ProductRepository
import com.lfg.masterdetail.viewmodels.ListViewModel
class ListFragment : Fragment() {
companion object {
fun newInstance() = ListFragment()
}
private lateinit var viewModelList: ListViewModel
private lateinit var v : View
private lateinit var txtHello : TextView
private lateinit var recProduct : RecyclerView
private var productRepository = ProductRepository()
private lateinit var linearLayoutManager : LinearLayoutManager
private val PREF_NAME = "mySelection"
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
v = inflater.inflate(R.layout.list_fragment, container, false)
//Binding
txtHello = v.findViewById(R.id.txtHello)
recProduct = v.findViewById(R.id.recProduct)
return v
}
override fun onStart() {
super.onStart()
setupRecycler()
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModelList = ViewModelProvider(this).get(ListViewModel::class.java)
// TODO: Use the ViewModel
}
private fun setupRecycler(){
recProduct.setHasFixedSize(true)
linearLayoutManager = LinearLayoutManager(context)
recProduct.layoutManager = linearLayoutManager
recProduct.adapter = ProductAdapter(productRepository.getList(),requireContext()) {
pos -> onItemClick(pos)
}
}
private fun onItemClick (position : Int) {
val sharedPref: SharedPreferences = requireContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
val editor = sharedPref.edit()
editor.putInt("position",position)
editor.apply()
val action = ListFragmentDirections.actionListFragmentToContainerFragment()
v.findNavController().navigate(action)
}
}
| 0 |
Kotlin
|
0
| 0 |
ce39f62befef83d53a3809411dbf60c2dcd410cc
| 2,560 |
kotlin1
|
MIT License
|
2021/src/main/kotlin/day24.kt
|
madisp
| 434,510,913 | false |
{"Kotlin": 323222}
|
import utils.Parser
import utils.Solution
import utils.cut
fun main() {
Day24Imp.run(skipTest = true)
}
object Day24Imp : Solution<List<List<Day24Imp.Insn>>>() {
override val name = "day24"
private const val DIGITS = 14
override val parser = Parser { input ->
val progStrings = input.split("inp w\n").map { it.trim() }.filter { it.isNotBlank() }
val progs = progStrings.map { it.lines().filter(String::isNotBlank).map(Insn::parse) }
// assumptions made about the input
require(progs.size == DIGITS)
progs.forEach { insns ->
// W is only input
require(insns.none { it.left == Register.W })
// X and Y are always reset before calculating
require(insns.first { it.left == Register.X } == Insn(Opcode.mul, Register.X, Literal(0)))
require(insns.first { it.left == Register.Y } == Insn(Opcode.mul, Register.Y, Literal(0)))
}
progs
}
data class Regs(var x: Int = 0, var y: Int = 0, var z: Int = 0, var w: Int = 0)
enum class Opcode { add, mul, div, mod, eql }
sealed interface Value {
operator fun get(regs: Regs): Int
}
enum class Register(val getter: (Regs) -> Int, val setter: (Regs, Int) -> Unit) : Value {
X(Regs::x, { r, v -> r.x = v }),
Y(Regs::y, { r, v -> r.y = v }),
Z(Regs::z, { r, v -> r.z = v }),
W(Regs::w, { r, v -> r.w = v });
override fun get(regs: Regs) = getter(regs)
operator fun set(regs: Regs, value: Int) = setter(regs, value)
}
data class Literal(val value: Int) : Value {
override fun get(regs: Regs) = value
}
data class Insn(val op: Opcode, val left: Register, val right: Value) {
companion object {
fun parse(str: String): Insn {
val (op, values) = str.cut(" ")
val (left, right) = values.cut(" ")
return Insn(Opcode.valueOf(op), Register.valueOf(left.uppercase()),
right.toIntOrNull()?.let { Literal(it) } ?: Register.valueOf(right.uppercase()))
}
}
}
fun exec(insn: Insn, regs: Regs) {
insn.left[regs] = when (insn.op) {
Opcode.add -> insn.left[regs] + insn.right[regs]
Opcode.mul -> insn.left[regs] * insn.right[regs]
Opcode.div -> insn.left[regs] / insn.right[regs]
Opcode.mod -> insn.left[regs] % insn.right[regs]
Opcode.eql -> if (insn.left[regs] == insn.right[regs]) 1 else 0
}
}
/**
* Return Z register for the given input
*/
fun checkDigit(insns: List<Insn>, inp: Int, z: Int): Int {
val r = Regs(z = z, w = inp)
insns.forEach { exec(it, r) }
return r.z
}
private fun solve(input: List<List<Insn>>): List<Long> {
var zRange = setOf(0)
var idx = input.size - 1
val constrained = Array<MutableMap<Int, MutableSet<Int>>>(14) { mutableMapOf() }
input.reversed().forEach { prog ->
val validZ = mutableSetOf<Int>()
for (input in 1 .. 9) {
for (z in 0 .. 1000000) {
if (checkDigit(prog, input, z) in zRange) {
val set = constrained[idx].getOrPut(input) { mutableSetOf() }
set.add(z)
validZ.add(z)
}
}
}
require(validZ.isNotEmpty()) { "No valid z for input input[$idx]?" }
idx--
zRange = validZ
}
fun findSerial(index: Int, z: Int): List<String> {
if (index == 14) return listOf("")
val opts = constrained[index].entries.filter { z in it.value }
return opts.flatMap { (digit, _) ->
val newZ = checkDigit(input[index], digit, z)
findSerial(index + 1, newZ).map {
digit.toString() + it
}
}
}
return findSerial(0, 0).map { it.toLong() }
}
override fun part1(input: List<List<Insn>>): Long? {
return solve(input).maxOrNull()
}
override fun part2(input: List<List<Insn>>): Long? {
return solve(input).minOrNull()
}
}
| 0 |
Kotlin
|
0
| 1 |
9d650f8aadc26e545cc7ab2f03c7a049c888aea8
| 3,815 |
aoc_kotlin
|
MIT License
|
skrapers/src/main/kotlin/ru/sokomishalov/skraper/Skrapers.kt
|
faridrama123
| 386,841,922 | true |
{"Kotlin": 282169, "Shell": 41, "Batchfile": 33}
|
/*
* Copyright (c) 2019-present <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("Skrapers")
@file:Suppress("unused")
package ru.sokomishalov.skraper
import ru.sokomishalov.skraper.client.HttpRequest
import ru.sokomishalov.skraper.client.SkraperClient
import ru.sokomishalov.skraper.client.jdk.DefaultBlockingSkraperClient
import ru.sokomishalov.skraper.internal.ffmpeg.FfmpegCliRunner
import ru.sokomishalov.skraper.internal.ffmpeg.FfmpegRunner
import ru.sokomishalov.skraper.internal.net.path
import ru.sokomishalov.skraper.model.*
import ru.sokomishalov.skraper.provider.facebook.FacebookSkraper
import ru.sokomishalov.skraper.provider.flickr.FlickrSkraper
import ru.sokomishalov.skraper.provider.ifunny.IFunnySkraper
import ru.sokomishalov.skraper.provider.instagram.InstagramSkraper
import ru.sokomishalov.skraper.provider.ninegag.NinegagSkraper
import ru.sokomishalov.skraper.provider.pikabu.PikabuSkraper
import ru.sokomishalov.skraper.provider.pinterest.PinterestSkraper
import ru.sokomishalov.skraper.provider.reddit.RedditSkraper
import ru.sokomishalov.skraper.provider.telegram.TelegramSkraper
import ru.sokomishalov.skraper.provider.tiktok.TikTokSkraper
import ru.sokomishalov.skraper.provider.tumblr.TumblrSkraper
import ru.sokomishalov.skraper.provider.twitch.TwitchSkraper
import ru.sokomishalov.skraper.provider.twitter.TwitterSkraper
import ru.sokomishalov.skraper.provider.vk.VkSkraper
import ru.sokomishalov.skraper.provider.youtube.YoutubeSkraper
import java.io.File
object Skrapers {
/**
* @return list of all available skrapers
*/
fun available(): List<Skraper> {
return providers.toList()
}
/**
* @param media media item
* @return skraper which supports this url or null if none of skrapers supports it
*/
fun findSuitable(media: Media): Skraper? {
return providers.find { it.supports(media) }
}
/**
* Convert provider relative media to downloadable media
* @param media item to resolve
* @return media with direct link
*/
suspend fun resolve(media: Media): Media {
return when {
// direct media url
media.url
.path
.substringAfterLast("/")
.substringAfterLast(".", "")
.isNotEmpty() -> media
// otherwise
else -> {
findSuitable(media)
?.resolve(media)
?.run {
when {
url != media.url -> resolve(media = this)
else -> when (media) {
is Image -> media.copy(url = url)
is Video -> media.copy(url = url)
is Audio -> media.copy(url = url)
is UnknownMedia -> media.copy(url = url)
}
}
}
?: media
}
}
}
/**
* Downloads media
* @param media item to download
* @param destDir destination directory for media
* @param filename custom destination file name without extension
*/
suspend fun download(
media: Media,
destDir: File,
filename: String = media.extractFileNameWithoutExtension()
): File {
val resolved = resolve(media)
val extension = resolved.extractFileExtension()
destDir.mkdirs()
val destFile = File("${destDir.absolutePath}${File.separator}${filename}.${extension}")
return when (extension) {
// m3u8 download and convert to mp4 with ffmpeg
"m3u8" -> {
val destFileMp4Path = destFile.absolutePath.replace("m3u8", "mp4")
val cmd = "-i ${resolved.url} -c copy -bsf:a aac_adtstoasc $destFileMp4Path"
ffmpegRunner.run(cmd)
File(destFileMp4Path)
}
// webm download and convert to mp4 with ffmpeg
"webm" -> {
val destFileMp4Path = destFile.absolutePath.replace("webm", "mp4")
val cmd = "-i ${resolved.url} -strict experimental $destFileMp4Path"
ffmpegRunner.run(cmd)
File(destFileMp4Path)
}
// otherwise try to download as is
else -> {
providers.random().client.download(HttpRequest(url = resolved.url), destFile = destFile)
destFile
}
}
}
/**
* Set client for all available skrapers
* @param client client to set
*/
fun setClient(client: SkraperClient) {
this.providers = implementations(client)
}
/**
* Set ffmpeg runner
* @param ffmpegRunner ffmpeg runner implementation
*/
fun setFfmpegRunner(ffmpegRunner: FfmpegRunner) {
this.ffmpegRunner = ffmpegRunner
}
private fun Media.extractFileExtension(): String {
val filename = url.path
return when (this) {
is Image -> filename.substringAfterLast(".", "png")
is Video -> filename.substringAfterLast(".", "mp4")
is Audio -> filename.substringAfterLast(".", "mp3")
is UnknownMedia -> filename.substringAfterLast(".")
}
}
private fun Media.extractFileNameWithoutExtension(): String {
return url.path.substringAfterLast("/").substringBeforeLast(".")
}
private fun implementations(client: SkraperClient): List<Skraper> = listOf(
FacebookSkraper(client),
InstagramSkraper(client),
TwitterSkraper(client),
YoutubeSkraper(client),
TikTokSkraper(client),
TelegramSkraper(client),
TwitchSkraper(client),
RedditSkraper(client),
NinegagSkraper(client),
PinterestSkraper(client),
FlickrSkraper(client),
TumblrSkraper(client),
IFunnySkraper(client),
VkSkraper(client),
PikabuSkraper(client)
)
private var providers: List<Skraper> = implementations(DefaultBlockingSkraperClient)
private var ffmpegRunner: FfmpegRunner = FfmpegCliRunner()
}
| 0 | null |
0
| 0 |
f5a77d6f2447e909ac27fc0d440d612f5af1e225
| 6,733 |
skraper
|
Apache License 2.0
|
app/src/main/kotlin/com/ivanovsky/passnotes/presentation/filepicker/factory/FilePickerCellViewModelFactory.kt
|
aivanovski
| 95,774,290 | false | null |
package com.ivanovsky.passnotes.presentation.filepicker.factory
import com.ivanovsky.passnotes.presentation.core.BaseCellViewModel
import com.ivanovsky.passnotes.presentation.core.event.EventProvider
import com.ivanovsky.passnotes.presentation.core.factory.CellViewModelFactory
import com.ivanovsky.passnotes.presentation.core.model.BaseCellModel
import com.ivanovsky.passnotes.presentation.core.model.FileCellModel
import com.ivanovsky.passnotes.presentation.core.viewmodel.FileCellViewModel
class FilePickerCellViewModelFactory : CellViewModelFactory {
override fun createCellViewModel(
model: BaseCellModel,
eventProvider: EventProvider
): BaseCellViewModel {
return when (model) {
is FileCellModel -> FileCellViewModel(
model,
eventProvider
)
else -> throwUnsupportedModelException(model)
}
}
}
| 4 | null |
1
| 7 |
dc4abdf847393919f5480129b64240ae0469b74c
| 913 |
kpassnotes
|
Apache License 2.0
|
LeetcodeKotlin/test/page010/LeetcodeTest1027.kt
|
SeptemberCold
| 840,959,904 | false |
{"Kotlin": 393641}
|
package page010
import base.BaseTest
object LeetcodeTest1027 :BaseTest<IntArray,Int>(){
@JvmStatic
fun main(args: Array<String>) {
val example = getExample()
methodTest(example){return@methodTest Leetcode1027().longestArithSeqLength(it)}
}
override fun getExample(): List<IntArray> {
val example = ArrayList<IntArray>()
example.add(intArrayOf(3,6,9,12))
example.add(intArrayOf(9,4,7,2,10))
example.add(intArrayOf(20,1,15,3,10,5,8))
example.add(intArrayOf(83,20,17,43,52,78,68,45))
return example
}
}
| 0 |
Kotlin
|
0
| 0 |
e1e1eac3f3d7894df4e06bb74b5edb5eee2d988f
| 587 |
leetcode_kotlin
|
Mulan Permissive Software License, Version 2
|
couchbase-lite/src/jvmCommonMain/kotlin/kotbase/Ordering.jvmCommon.kt
|
jeffdgr8
| 518,984,559 | false |
{"Kotlin": 2289925, "Python": 294}
|
/*
* Copyright 2022-2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotbase
import kotlin.Array
import com.couchbase.lite.Ordering as CBLOrdering
internal actual class OrderingPlatformState(
internal val actual: CBLOrdering
)
public actual sealed class Ordering
private constructor(actual: CBLOrdering) {
internal actual val platformState = OrderingPlatformState(actual)
public actual class SortOrder
internal constructor(actual: CBLOrdering.SortOrder) : Ordering(actual) {
public actual fun ascending(): Ordering {
actual.ascending()
return this
}
public actual fun descending(): Ordering {
actual.descending()
return this
}
}
override fun equals(other: Any?): Boolean =
actual == (other as? Ordering)?.actual
override fun hashCode(): Int =
actual.hashCode()
override fun toString(): String =
actual.toString()
public actual companion object {
public actual fun property(property: String): SortOrder =
SortOrder(CBLOrdering.property(property))
public actual fun expression(expression: Expression): SortOrder =
SortOrder(CBLOrdering.expression(expression.actual))
}
}
internal val Ordering.actual: CBLOrdering
get() = platformState.actual
internal val Ordering.SortOrder.actual: CBLOrdering.SortOrder
get() = platformState.actual as CBLOrdering.SortOrder
internal fun Array<out Ordering>.actuals(): Array<CBLOrdering> =
map { it.actual }.toTypedArray()
| 0 |
Kotlin
|
0
| 7 |
188723bf0c4609b649d157988de44ac140e431dd
| 2,100 |
kotbase
|
Apache License 2.0
|
zenkey-sdk/src/main/kotlin/com/xci/zenkey/sdk/RedirectUriReceiverActivity.kt
|
MyZenKey
| 212,171,855 | false | null |
/*
* Copyright 2019 XCI JV, LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.xci.zenkey.sdk
import android.app.Activity
import android.os.Bundle
import com.xci.zenkey.sdk.internal.AuthorizationRequestActivity
import com.xci.zenkey.sdk.internal.contract.Logger
/**
* This [Activity] is catching the redirect for the ZenKey SDK.
* This [Activity] have the responsibility to re-start [AuthorizationRequestActivity] and clear the activity stack.
*/
class RedirectUriReceiverActivity : Activity() {
public override fun onCreate(savedInstanceBundle: Bundle?) {
super.onCreate(savedInstanceBundle)
// while this does not appear to be achieving much, handling the redirect in this way
// ensures that we can remove the browser tab/CCID from the back stack. See the documentation
// on AuthorizationManagementActivity for more details.
val redirect = intent.data
if (redirect != null) {
Logger.get().redirect(redirect)
startActivity(AuthorizationRequestActivity.createResponseHandlingIntent(
this, intent.data!!))
} else {
Logger.get().e("RedirectUriReceiverActivity started without redirectUri")
}
finish()
}
}
| 0 |
Kotlin
|
3
| 3 |
a8c0d8f7796920cfd47f05a7bb98f211974d31a3
| 1,776 |
sp-sdk-android
|
Apache License 2.0
|
fate/src/main/kotlin/com/kotcrab/fate/PackageExtractor.kt
|
RikuNoctis
| 165,883,449 | false | null |
/*
* Copyright 2017-2018 See AUTHORS file.
*
* 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.kotcrab.fate
import com.kotcrab.fate.file.CmpFile
import com.kotcrab.fate.file.PakFile
import com.kotcrab.fate.util.Log
import kio.util.readableFileSize
import java.io.File
import java.util.*
/**
* Batch file extractor for Extra and CCC .pak/.cmp files. Use this after extracting main CPK.
* @author Kotcrab
*/
class PackageExtractor(srcDir: File, outDir: File, log: Log = Log()) {
init {
var pakFiles = 0
var pakFileEntries = 0
var duplicates = 0
var duplicatesSize = 0L
val duplicatesWithContentCollision = mutableListOf<String>()
val files = srcDir.walk().toList().filter { it.extension == "pak" || it.extension == "cmp" }
files.forEachIndexed { idx, file ->
val data = when (file.extension) {
"cmp" -> CmpFile(file).getData()
"pak" -> file.readBytes()
else -> {
return@forEachIndexed
}
}
log.info("${idx + 1}/${files.size} Process ${file.name}")
val pak = PakFile(data)
pakFiles++
pak.entries.forEachIndexed { pakIdx, entry ->
var outName = entry.path
if (entry.path == "") {
log.warn("Anonymous PAK file entry in PAK ${file.name}, ID $pakIdx")
outName = "__anonymous from ${file.name} file id $pakIdx"
}
var outFile = File(outDir, outName)
if (outFile.isDirectory) {
log.warn("PAK entry points to existing directory")
outName = "__directory from ${file.name} file id $pakIdx"
outFile = File(outDir, outName)
}
if (outFile.exists()) {
val outFileData = outFile.readBytes()
if (Arrays.equals(entry.bytes, outFileData)) {
log.warn("Duplicate PAK file entry $outName in PAK ${file.name}")
duplicates++
duplicatesSize += entry.bytes.size
} else {
duplicatesWithContentCollision.add(outName)
log.warn("Duplicate PAK file entry $outName with collision name in PAK ${file.name}")
for (i in 2..Integer.MAX_VALUE) {
outFile = File(
outFile.parentFile.path,
"${outFile.nameWithoutExtension} ($i).${outFile.extension}"
)
if (outFile.exists() == false) break
}
}
} else {
pakFileEntries++
}
entry.writeToFile(outFile)
}
}
log.info("Processed files: $pakFiles")
log.info("Unpacked files: $pakFileEntries")
log.info("Duplicate files: $duplicates")
log.info("Duplicate files size: ${readableFileSize(duplicatesSize)}")
log.info("Duplicate files with content collision: ${duplicatesWithContentCollision.size}")
if (duplicatesWithContentCollision.size != 0) {
log.info("Duplicate files with content collision list:")
log.info(duplicatesWithContentCollision.joinToString(separator = "\n"))
}
log.info("Done")
}
}
| 0 |
Kotlin
|
0
| 1 |
04d0a219269e17c97cca54f71ae11e348c9fb070
| 4,025 |
fate-explorer
|
Apache License 2.0
|
graphql-jetpack/src/main/kotlin/io/github/wickedev/graphql/kotlin/JetpackDataFetcherFactoryProvider.kt
|
wickedev
| 439,584,762 | false |
{"Kotlin": 269467, "JavaScript": 6748, "Java": 2439, "CSS": 1699}
|
package io.github.wickedev.graphql.kotlin
import com.expediagroup.graphql.generator.execution.SimpleKotlinDataFetcherFactoryProvider
import com.fasterxml.jackson.databind.ObjectMapper
import graphql.schema.DataFetcherFactory
import io.github.wickedev.graphql.JetpackFunctionDataFetcher
import io.github.wickedev.graphql.scalars.CustomScalars
import org.aopalliance.intercept.MethodInvocation
import org.springframework.context.ApplicationContext
import org.springframework.security.access.expression.SecurityExpressionHandler
import kotlin.reflect.KFunction
open class JetpackDataFetcherFactoryProvider(
private val objectMapper: ObjectMapper,
private val applicationContext: ApplicationContext,
private val securityExpressionHandler: SecurityExpressionHandler<MethodInvocation>,
private val customScalars: CustomScalars
) : SimpleKotlinDataFetcherFactoryProvider(objectMapper) {
override fun functionDataFetcherFactory(target: Any?, kFunction: KFunction<*>): DataFetcherFactory<Any?> =
DataFetcherFactory {
JetpackFunctionDataFetcher(
target,
kFunction,
objectMapper,
applicationContext,
securityExpressionHandler,
customScalars
)
}
}
| 0 |
Kotlin
|
0
| 19 |
d6913beaecf9e7ef065acdb1805794a10b07d55e
| 1,294 |
graphql-jetpack
|
The Unlicense
|
core/src/jvmMain/kotlin/com/littlekt/LwjglGraphics.kt
|
littlektframework
| 442,309,478 | false |
{"Kotlin": 2170511, "Java": 1717152, "C": 111391}
|
package com.littlekt
import com.littlekt.graphics.Cursor
import com.littlekt.graphics.HdpiMode
import com.littlekt.graphics.SystemCursor
import com.littlekt.graphics.webgpu.*
import com.littlekt.log.Logger
import com.littlekt.wgpu.*
import com.littlekt.wgpu.WGPU.*
import java.lang.foreign.Arena
import java.lang.foreign.MemorySegment
import kotlinx.atomicfu.atomic
import kotlinx.atomicfu.update
import org.lwjgl.glfw.*
import org.lwjgl.system.JNI.*
import org.lwjgl.system.macosx.ObjCRuntime.*
/**
* @author <NAME>
* @date 11/6/2021
*/
class LwjglGraphics(private val context: LwjglContext) : Graphics, Releasable {
private val systemCursors = mutableMapOf<SystemCursor, Long>()
internal var _logicalWidth: Int = 0
internal var _logicalHeight: Int = 0
internal var _backBufferWidth: Int = 0
internal var _backBufferHeight: Int = 0
override val width: Int
get() =
if (context.configuration.hdpiMode == HdpiMode.PIXELS) backBufferWidth
else _logicalWidth
override val height: Int
get() =
if (context.configuration.hdpiMode == HdpiMode.PIXELS) backBufferHeight
else _logicalHeight
override val backBufferWidth: Int
get() = _backBufferWidth
override val backBufferHeight: Int
get() = _backBufferHeight
internal var instance: Instance = Instance(WGPU_NULL)
override var surface: Surface = Surface(WGPU_NULL)
override var adapter: Adapter = Adapter(WGPU_NULL)
override var device: Device = Device(WGPU_NULL)
override val preferredFormat by lazy { surface.getPreferredFormat(adapter) }
private var hasSurfaceCapabilities = false
override val surfaceCapabilities: SurfaceCapabilities by lazy {
hasSurfaceCapabilities = true
surface.getCapabilities(adapter)
}
override fun configureSurface(
usage: TextureUsage,
format: TextureFormat,
presentMode: PresentMode,
alphaMode: AlphaMode
) {
surface.configure(
SurfaceConfiguration(device, usage, format, presentMode, alphaMode, width, height)
)
}
internal suspend fun requestAdapterAndDevice(powerPreference: PowerPreference) {
val output = atomic(WGPU_NULL)
Arena.ofConfined().use { scope ->
val options = WGPURequestAdapterOptions.allocate(scope)
val callback =
WGPURequestAdapterCallback.allocate(
{ status, adapter, message, _ ->
if (status == WGPURequestAdapterStatus_Success()) {
output.update { adapter }
} else {
logger.error {
"requestAdapter status=$status, message=${message.getUtf8String(0)}"
}
}
},
scope
)
WGPURequestAdapterOptions.powerPreference(options, powerPreference.nativeVal)
WGPURequestAdapterOptions.compatibleSurface(options, surface.segment)
WGPURequestAdapterOptions.nextInChain(options, WGPU_NULL)
wgpuInstanceRequestAdapter(instance.segment, options, callback, WGPU_NULL)
}
adapter = Adapter(output.value)
requestDevice()
}
private suspend fun requestDevice() {
device = adapter.requestDevice()
}
override fun supportsExtension(extension: String): Boolean {
return GLFW.glfwExtensionSupported(extension)
}
override fun setCursor(cursor: Cursor) {
GLFW.glfwSetCursor(context.windowHandle, cursor.cursorHandle)
}
override fun setCursor(cursor: SystemCursor) {
var handle = systemCursors[cursor]
if (handle == null) {
handle =
when (cursor) {
SystemCursor.ARROW -> GLFW.glfwCreateStandardCursor(GLFW.GLFW_ARROW_CURSOR)
SystemCursor.I_BEAM -> GLFW.glfwCreateStandardCursor(GLFW.GLFW_IBEAM_CURSOR)
SystemCursor.CROSSHAIR ->
GLFW.glfwCreateStandardCursor(GLFW.GLFW_CROSSHAIR_CURSOR)
SystemCursor.HAND -> GLFW.glfwCreateStandardCursor(GLFW.GLFW_HAND_CURSOR)
SystemCursor.HORIZONTAL_RESIZE ->
GLFW.glfwCreateStandardCursor(GLFW.GLFW_HRESIZE_CURSOR)
SystemCursor.VERTICAL_RESIZE ->
GLFW.glfwCreateStandardCursor(GLFW.GLFW_VRESIZE_CURSOR)
}
if (handle == 0L) return
systemCursors[cursor] = handle
}
GLFW.glfwSetCursor(context.windowHandle, handle)
}
internal fun createInstance(configuration: JvmConfiguration) {
instance =
Arena.ofConfined().use { scope ->
val instanceDesc = WGPUInstanceDescriptor.allocate(scope)
val extras = WGPUInstanceExtras.allocate(scope)
if (configuration.preferredBackends.isInvalid()) {
logger.warn {
"Configuration.preferredBackends is invalid and will resort to the default backend. Specify at least one backend or remove the list to get rid of this warning."
}
} else {
WGPUInstanceExtras.backends(extras, configuration.preferredBackends.flag)
}
WGPUChainedStruct.sType(
WGPUInstanceExtras.chain(extras),
WGPUSType_InstanceExtras()
)
WGPUInstanceDescriptor.nextInChain(instanceDesc, extras)
Instance(wgpuCreateInstance(instanceDesc))
}
}
internal fun configureSurfaceToWindow(windowHandle: Long) {
val isMac = System.getProperty("os.name").lowercase().contains("mac")
val isWindows = System.getProperty("os.name").lowercase().contains("windows")
val isLinux = System.getProperty("os.name").lowercase().contains("linux")
surface =
Surface(
when {
isWindows -> {
val osHandle = GLFWNativeWin32.glfwGetWin32Window(windowHandle)
Arena.ofConfined().use { scope ->
val desc = WGPUSurfaceDescriptor.allocate(scope)
val windowsDesc = WGPUSurfaceDescriptorFromWindowsHWND.allocate(scope)
WGPUSurfaceDescriptorFromWindowsHWND.hwnd(
windowsDesc,
MemorySegment.ofAddress(osHandle)
)
WGPUSurfaceDescriptorFromWindowsHWND.hinstance(windowsDesc, WGPU_NULL)
WGPUChainedStruct.sType(
WGPUSurfaceDescriptorFromWindowsHWND.chain(windowsDesc),
WGPUSType_SurfaceDescriptorFromWindowsHWND()
)
WGPUSurfaceDescriptor.label(desc, WGPU_NULL)
WGPUSurfaceDescriptor.nextInChain(desc, windowsDesc)
wgpuInstanceCreateSurface(instance.segment, desc)
}
}
isLinux -> {
val platform = GLFW.glfwGetPlatform()
when (platform) {
GLFW.GLFW_PLATFORM_X11 -> {
Arena.ofConfined().use { scope ->
val display = GLFWNativeX11.glfwGetX11Display()
val osHandle = GLFWNativeX11.glfwGetX11Window(windowHandle)
val desc = WGPUSurfaceDescriptor.allocate(scope)
val windowsDesc =
WGPUSurfaceDescriptorFromXlibWindow.allocate(scope)
WGPUSurfaceDescriptorFromXlibWindow.display(
windowsDesc,
MemorySegment.ofAddress(display)
)
WGPUSurfaceDescriptorFromXlibWindow.window(
windowsDesc,
osHandle
)
WGPUChainedStruct.sType(
WGPUSurfaceDescriptorFromXlibWindow.chain(windowsDesc),
WGPUSType_SurfaceDescriptorFromXlibWindow()
)
WGPUSurfaceDescriptor.label(desc, WGPU_NULL)
WGPUSurfaceDescriptor.nextInChain(desc, windowsDesc)
wgpuInstanceCreateSurface(instance.segment, desc)
}
}
GLFW.GLFW_PLATFORM_WAYLAND -> {
Arena.ofConfined().use { scope ->
val display = GLFWNativeWayland.glfwGetWaylandDisplay()
val osHandle =
GLFWNativeWayland.glfwGetWaylandWindow(windowHandle)
val desc = WGPUSurfaceDescriptor.allocate(scope)
val windowsDesc =
WGPUSurfaceDescriptorFromWaylandSurface.allocate(scope)
WGPUSurfaceDescriptorFromWaylandSurface.display(
windowsDesc,
MemorySegment.ofAddress(display)
)
WGPUSurfaceDescriptorFromWaylandSurface.surface(
windowsDesc,
MemorySegment.ofAddress(osHandle)
)
WGPUChainedStruct.sType(
WGPUSurfaceDescriptorFromWaylandSurface.chain(windowsDesc),
WGPUSType_SurfaceDescriptorFromWaylandSurface()
)
WGPUSurfaceDescriptor.label(desc, WGPU_NULL)
WGPUSurfaceDescriptor.nextInChain(desc, windowsDesc)
wgpuInstanceCreateSurface(instance.segment, desc)
}
}
else -> {
logger.log(Logger.Level.ERROR) {
"Linux platform not supported. Supported backends: [X11, Wayland]"
}
WGPU_NULL
}
}
}
isMac -> {
val osHandle = GLFWNativeCocoa.glfwGetCocoaWindow(windowHandle)
Arena.ofConfined().use { scope ->
val objc_msgSend = getLibrary().getFunctionAddress("objc_msgSend")
val CAMetalLayer = objc_getClass("CAMetalLayer")
val contentView =
invokePPP(osHandle, sel_getUid("contentView"), objc_msgSend)
// [ns_window.contentView setWantsLayer:YES];
invokePPV(contentView, sel_getUid("setWantsLayer:"), true, objc_msgSend)
// metal_layer = [CAMetalLayer layer];
val metal_layer =
invokePPP(CAMetalLayer, sel_registerName("layer"), objc_msgSend)
// [ns_window.contentView setLayer:metal_layer];
invokePPPP(
contentView,
sel_getUid("setLayer:"),
metal_layer,
objc_msgSend
)
val desc = WGPUSurfaceDescriptor.allocate(scope)
val metalDesc = WGPUSurfaceDescriptorFromMetalLayer.allocate(scope)
WGPUSurfaceDescriptorFromMetalLayer.layer(
metalDesc,
MemorySegment.ofAddress(metal_layer)
)
WGPUChainedStruct.sType(
WGPUSurfaceDescriptorFromMetalLayer.chain(metalDesc),
WGPUSType_SurfaceDescriptorFromMetalLayer()
)
WGPUSurfaceDescriptor.label(desc, WGPU_NULL)
WGPUSurfaceDescriptor.nextInChain(desc, metalDesc)
wgpuInstanceCreateSurface(instance.segment, desc)
}
}
else -> {
logger.log(Logger.Level.ERROR) { "Platform not supported." }
WGPU_NULL
}
}
)
}
override fun release() {
if (device.queue.segment != WGPU_NULL) {
device.queue.release()
}
if (device.segment != WGPU_NULL) {
device.release()
}
if (adapter.segment != WGPU_NULL) {
adapter.release()
}
if (surface.segment != WGPU_NULL) {
surface.release()
}
if (instance.segment != WGPU_NULL) {
wgpuInstanceRelease(instance.segment)
}
}
companion object {
private val logger = Logger<LwjglGraphics>()
}
}
| 14 |
Kotlin
|
12
| 316 |
100c37feefcfd65038a9cba4886aeb4a7d5632dc
| 14,011 |
littlekt
|
Apache License 2.0
|
app/src/androidTest/java/com/google/maps/android/compose/TestUtils.kt
|
googlemaps
| 455,343,699 | false |
{"Kotlin": 224363}
|
package com.google.maps.android.compose
import com.google.android.gms.maps.model.LatLng
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
val hasValidApiKey: Boolean =
BuildConfig.MAPS_API_KEY.isNotBlank() && BuildConfig.MAPS_API_KEY != "YOUR_API_KEY"
const val assertRoundingError: Double = 0.01
fun LatLng.assertEquals(other: LatLng) {
assertEquals(latitude, other.latitude, assertRoundingError)
assertEquals(longitude, other.longitude, assertRoundingError)
}
fun LatLng.assertNotEquals(other: LatLng) {
assertNotEquals(latitude, other.latitude, assertRoundingError)
assertNotEquals(longitude, other.longitude, assertRoundingError)
}
| 93 |
Kotlin
|
99
| 954 |
b4aaaa883751d9c342e4fbb77f86f9e5221457c7
| 687 |
android-maps-compose
|
Apache License 2.0
|
src/main/java/ru/hollowhorizon/hc/client/screens/widget/LabelWidget.kt
|
HollowHorizon
| 450,852,365 | false | null |
package ru.hollowhorizon.hc.client.screens.widget
import com.mojang.blaze3d.vertex.PoseStack
import net.minecraft.client.Minecraft
import net.minecraft.network.chat.Component
import ru.hollowhorizon.hc.client.screens.util.Anchor
import ru.hollowhorizon.hc.client.utils.drawScaled
import kotlin.math.max
private val font get() = Minecraft.getInstance().font
class LabelWidget(
text: Component,
private val hovered: Component = text,
private val anchor: Anchor = Anchor.CENTER,
private val color: Int,
private val hoveredColor: Int,
val scale: Float = 1f
): HollowWidget(0,0,
(max(font.width(text), font.width(hovered)) * scale).toInt(), (9 * scale).toInt(), text) {
override fun renderButton(stack: PoseStack, mouseX: Int, mouseY: Int, ticks: Float) {
super.renderButton(stack, mouseX, mouseY, ticks)
font.drawScaled(
stack, anchor, if(isHovered) message else hovered, x, y, if(isHovered) color else hoveredColor, scale
)
}
}
| 0 | null |
2
| 9 |
2f523cd594154cc5472a635c75bf077a18b8bf49
| 999 |
HollowCore
|
MIT License
|
bindings-chicory/src/jvmMain/kotlin/host/memory/ChicoryMemoryRawSink.kt
|
illarionov
| 848,247,126 | false |
{"Kotlin": 1343464, "ANTLR": 6038, "TypeScript": 3148, "CSS": 1042, "FreeMarker": 450, "JavaScript": 89}
|
/*
* Copyright 2024, the wasi-emscripten-host project authors and contributors. Please see the AUTHORS file
* for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
* SPDX-License-Identifier: Apache-2.0
*/
package at.released.weh.bindings.chicory.host.memory
import at.released.weh.wasm.core.IntWasmPtr
import at.released.weh.wasm.core.WasmPtr
import at.released.weh.wasm.core.memory.MemoryRawSink
import com.dylibso.chicory.runtime.Memory
import kotlinx.io.Buffer
import kotlinx.io.readByteArray
internal class ChicoryMemoryRawSink(
private val wasmMemory: Memory,
@IntWasmPtr baseAddr: WasmPtr,
@IntWasmPtr toAddrExclusive: WasmPtr,
) : MemoryRawSink(baseAddr, toAddrExclusive) {
override fun writeBytesToMemory(source: Buffer, @IntWasmPtr toAddr: WasmPtr, byteCount: Long) {
val data = source.readByteArray(byteCount.toInt())
wasmMemory.write(toAddr, data)
}
}
| 0 |
Kotlin
|
0
| 4 |
774f9d4fc1c05080636888c4fe03049fdb038a8d
| 966 |
wasi-emscripten-host
|
Apache License 2.0
|
runner/src/main/kotlin/io/engenious/sift/node/remote/plugins/blocker/LoopingTag.kt
|
engeniousio
| 262,129,936 | false | null |
package io.engenious.sift.node.remote.plugins.blocker
object LoopingTag
| 0 |
HTML
|
2
| 3 |
da5ee89d7509f66fe58468eb30e03dd05a1b89c9
| 73 |
sift-android
|
Apache License 2.0
|
app/src/main/java/com/example/gamebuddy/data/remote/model/friends/FriendsBody.kt
|
GameBuddyDevs
| 609,491,782 | false | null |
package com.example.gamebuddy.data.remote.model.friends
data class FriendsBody(
val data: FriendsData
)
| 0 |
Kotlin
|
1
| 3 |
0a767229f5505e6a68e167aece41c10abb282e1b
| 108 |
GameBuddy-Android
|
MIT License
|
kotlin-antd/antd-samples/src/main/kotlin/samples/alert/Icon.kt
|
xlj44400
| 341,311,901 | true |
{"Kotlin": 1224294, "HTML": 1503}
|
package samples.alert
import antd.alert.*
import antd.icon.*
import react.*
import react.dom.*
import styled.*
private val smileIcon = buildElement {
smileOutlined {}
}
fun RBuilder.customIcon() {
styledDiv {
css { +AlertStyles.customIcon }
div {
alert {
attrs {
icon = smileIcon
message = "showIcon = false"
type = "success"
}
}
alert {
attrs {
icon = smileIcon
message = "Success Tips"
type = "success"
showIcon = true
}
}
alert {
attrs {
icon = smileIcon
message = "Informational Notes"
type = "info"
showIcon = true
}
}
alert {
attrs {
icon = smileIcon
message = "Warning"
type = "warning"
showIcon = true
}
}
alert {
attrs {
icon = smileIcon
message = "Error"
type = "error"
showIcon = true
}
}
alert {
attrs {
icon = smileIcon
message = "Success Tips"
description = "Detailed description and advice about successful copywriting."
type = "success"
showIcon = true
}
}
alert {
attrs {
icon = smileIcon
message = "Informational Notes"
description = "Additional description and information about copywriting."
type = "info"
showIcon = true
}
}
alert {
attrs {
icon = smileIcon
message = "Warning"
description = "This is a warning notice about copywriting."
type = "warning"
showIcon = true
}
}
alert {
attrs {
icon = smileIcon
message = "Error"
description = "This is an error message about copywriting."
type = "error"
showIcon = true
}
}
}
}
}
| 0 | null |
0
| 0 |
ce8216c0332abdfefcc0a06cf5fbbbf24e669931
| 2,671 |
kotlin-js-wrappers
|
Apache License 2.0
|
expui/src/main/kotlin/io/kanro/compose/jetbrains/expui/control/Indication.kt
|
ButterCam
| 414,869,239 | false |
{"Kotlin": 411098}
|
package io.kanro.compose.jetbrains.expui.control
import androidx.compose.foundation.Indication
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.remember
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.drawOutline
import androidx.compose.ui.graphics.drawscope.ContentDrawScope
import androidx.compose.ui.graphics.isSpecified
import io.kanro.compose.jetbrains.expui.style.LocalHoverAreaColors
import io.kanro.compose.jetbrains.expui.style.LocalPressedAreaColors
class HoverOrPressedIndication(private val shape: Shape) : Indication {
private class IndicationInstance(
private val shape: Shape,
private val isHover: State<Boolean>,
private val isPressed: State<Boolean>,
private val hoverColor: Color,
private val pressedColor: Color,
) : androidx.compose.foundation.IndicationInstance {
override fun ContentDrawScope.drawIndication() {
when {
isPressed.value -> {
if (pressedColor.isSpecified) {
val outline = shape.createOutline(size, layoutDirection, this)
drawOutline(outline, pressedColor)
}
}
isHover.value -> {
if (hoverColor.isSpecified) {
val outline = shape.createOutline(size, layoutDirection, this)
drawOutline(outline, hoverColor)
}
}
}
drawContent()
}
}
@Composable
override fun rememberUpdatedInstance(interactionSource: InteractionSource): androidx.compose.foundation.IndicationInstance {
val hoverColors = LocalHoverAreaColors.current
val pressedColors = LocalPressedAreaColors.current
val isPressed = interactionSource.collectIsPressedAsState()
val isHover = interactionSource.collectIsHoveredAsState()
return remember(hoverColors, pressedColors, interactionSource) {
IndicationInstance(
shape, isHover, isPressed, hoverColors.startBackground, pressedColors.startBackground
)
}
}
}
| 1 |
Kotlin
|
8
| 186 |
8f237fd0c144ee8cc425aff5430f48ae634e914e
| 2,489 |
compose-jetbrains-theme
|
MIT License
|
src/main/kotlin/example/examplemod/data/gen/DataGenerators.kt
|
TeamVoided
| 793,062,053 | false |
{"Kotlin": 57229, "Java": 1121}
|
package example.examplemod.data.gen
import example.examplemod.NeoUranus
import example.examplemod.data.gen.prov.*
import net.minecraftforge.data.event.GatherDataEvent
import net.minecraftforge.eventbus.api.SubscribeEvent
import net.minecraftforge.fml.common.Mod
@Suppress("unused")
@Mod.EventBusSubscriber(modid = NeoUranus.ID, bus = Mod.EventBusSubscriber.Bus.MOD)
object DataGenerators {
@SubscribeEvent
fun gatherData(event: GatherDataEvent) {
val generator = event.generator
val blockTags = BlockTags(event)
generator.addProvider(event.includeServer(), blockTags)
generator.addProvider(event.includeServer(), ItemTags(event, blockTags))
// generator.addProvider(event.includeServer(), EntityTags(generator.packOutput, FarmersDelight.MODID, helper))
generator.addProvider(event.includeServer(), Recipes(event))
// generator.addProvider(event.includeServer(), Advancements(generator))
val blockStates = BlockStates(event)
generator.addProvider(event.includeClient(), blockStates)
generator.addProvider(event.includeClient(), ItemModels(event, blockStates.models().existingFileHelper))
generator.addProvider(event.includeClient(), EnglishLanguage(event))
generator.addProvider(event.includeClient(), LootTables(event))
}
}
| 0 |
Kotlin
|
0
| 0 |
61aac3187b5b83164b93fb4af0dfe2162e7ede62
| 1,335 |
NeoUranus
|
MIT License
|
hex-rules/src/main/kotlin/hex/engine/EndedHexGame.kt
|
krasnoludkolo
| 265,339,358 | false | null |
package hex.engine
import hex.*
import hex.status.GameHistory
import hex.status.GameStatus
class EndedHexGame(
private val board: Board,
private val history: GameHistory,
private val winner: HexPlayer
) : HexGame {
override fun makeMove(move: Move): MoveResult = ErrorMove.endedGame()
override fun getHistory(): GameHistory = history
override fun getStatus(): GameStatus = GameStatus.ended(board, winner, history)
}
| 0 |
Kotlin
|
0
| 0 |
97e136262f79c78aea0aabf4c7132b18da6f70bf
| 445 |
hex
|
MIT License
|
mobile/src/main/java/com/siliconlabs/bledemo/features/scan/rssi_graph/fragments/RssiGraphFragment.kt
|
SiliconLabs
| 85,345,875 | false | null |
package com.siliconlabs.bledemo.features.scan.rssi_graph.fragments
import android.app.Activity.RESULT_OK
import android.content.Context
import android.content.Intent
import android.content.Intent.ACTION_OPEN_DOCUMENT_TREE
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.*
import android.widget.Toast
import androidx.annotation.StringRes
import androidx.documentfile.provider.DocumentFile
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.siliconlabs.bledemo.home_screen.viewmodels.ScanFragmentViewModel
import com.siliconlabs.bledemo.features.scan.browser.view_states.GraphFragmentViewState
import com.siliconlabs.bledemo.R
import com.siliconlabs.bledemo.databinding.FragmentGraphBinding
import com.siliconlabs.bledemo.home_screen.base.BaseServiceDependentMainMenuFragment
import com.siliconlabs.bledemo.home_screen.fragments.ScanFragment
import com.siliconlabs.bledemo.home_screen.base.ViewPagerFragment
import com.siliconlabs.bledemo.features.scan.rssi_graph.adapters.GraphLabelAdapter
import com.siliconlabs.bledemo.features.scan.rssi_graph.utils.GraphDataExporter
import com.siliconlabs.bledemo.features.scan.rssi_graph.views.ChartView
import com.siliconlabs.bledemo.home_screen.base.BluetoothDependent
import com.siliconlabs.bledemo.home_screen.base.LocationDependent
import java.text.DateFormat
import java.util.*
import java.util.concurrent.ScheduledThreadPoolExecutor
class RssiGraphFragment : BaseServiceDependentMainMenuFragment() {
private lateinit var viewModel: ScanFragmentViewModel
private lateinit var _binding: FragmentGraphBinding
private lateinit var chartView: ChartView
private lateinit var labelAdapter: GraphLabelAdapter
private var isInitialBluetoothStateObserved = false
private var isInitialGraphStateLoaded = false // for optimization purposes when entering graph fragment
private val handler = Handler(Looper.getMainLooper())
private var executor: ScheduledThreadPoolExecutor? = null
private fun getScanFragment() = (parentFragment as ViewPagerFragment).getScanFragment()
override val bluetoothDependent = object : BluetoothDependent {
override fun onBluetoothStateChanged(isBluetoothOn: Boolean) {
toggleBluetoothBar(isBluetoothOn, _binding.bluetoothBar)
_binding.rssiGraphBtnScanning.isEnabled = isBluetoothOperationPossible()
if (isInitialBluetoothStateObserved) {
/* LiveData sends its initial value to an observer which starts scan when creating
this fragment - even if global scanning state is false. This flag prevents that. */
viewModel.setIsScanningOn(isBluetoothOperationPossible())
}
if (!isBluetoothOn) {
viewModel.reset()
chartView.reset()
}
isInitialBluetoothStateObserved = true
}
override fun onBluetoothPermissionsStateChanged(arePermissionsGranted: Boolean) {
toggleBluetoothPermissionsBar(arePermissionsGranted, _binding.bluetoothPermissionsBar)
_binding.rssiGraphBtnScanning.isEnabled = isBluetoothOperationPossible()
if (!arePermissionsGranted) {
viewModel.reset()
chartView.reset()
}
}
override fun refreshBluetoothDependentUi(isBluetoothOperationPossible: Boolean) {
_binding.rssiGraphBtnScanning.isEnabled = isBluetoothOperationPossible
}
override fun setupBluetoothPermissionsBarButtons() {
_binding.bluetoothPermissionsBar.setFragmentManager(childFragmentManager)
}
}
override val locationDependent = object : LocationDependent {
override fun onLocationStateChanged(isLocationOn: Boolean) {
toggleLocationBar(isLocationOn, _binding.locationBar)
}
override fun onLocationPermissionStateChanged(isPermissionGranted: Boolean) {
_binding.apply {
toggleLocationPermissionBar(isPermissionGranted, locationPermissionBar)
rssiGraphBtnScanning.isEnabled = isPermissionGranted
}
}
override fun setupLocationBarButtons() {
_binding.locationBar.setFragmentManager(childFragmentManager)
}
override fun setupLocationPermissionBarButtons() {
_binding.locationPermissionBar.setFragmentManager(childFragmentManager)
}
}
private val scanFragmentListener = object : ScanFragment.ScanFragmentListener {
override fun onScanningStateChanged(isOn: Boolean) {
if (isOn) chartView.updateTimestamp(viewModel.nanoTimestamp)
else showGraphArrows()
toggleRefreshGraphRunnable(isOn)
toggleScanningViews(isOn)
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
viewModel = getScanFragment().viewModel
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
setHasOptionsMenu(true)
_binding = FragmentGraphBinding.inflate(inflater)
return _binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
activity?.title = getString(R.string.fragment_scan_label)
chartView = ChartView(requireContext(), _binding.rssiChart, timeArrowHandler, viewModel.nanoTimestamp)
setupRecyclerView()
setupUiObservers()
setupViewModelObservers()
chartView.initialize()
if (viewModel.getIsScanningOn()) {
handler.postDelayed( { toggleRefreshGraphRunnable(true) }, INITIALIZATION_DELAY)
}
}
private fun setupRecyclerView() {
labelAdapter = GraphLabelAdapter(viewModel.getLabelViewsState().toMutableList(), legendClickHandler)
_binding.rssiLegendView.apply {
adapter = labelAdapter
layoutManager = LinearLayoutManager(requireContext()).apply {
orientation = RecyclerView.HORIZONTAL
}
}
}
private fun setupUiObservers() {
_binding.apply {
rssiGraphBtnScanning.setOnClickListener {
var animationDelay = 0L
if (!viewModel.getIsScanningOn()) {
viewModel.reset()
chartView.reset()
animationDelay = ANIMATION_DELAY
}
handler.postDelayed({ viewModel.toggleScanningState() }, animationDelay)
}
rssiGraphTimeArrowEnd.setOnClickListener { chartView.skipToEnd() }
rssiGraphTimeArrowStart.setOnClickListener { chartView.skipToStart() }
}
}
private fun setupViewModelObservers() {
viewModel.apply {
isAnyDeviceDiscovered.observe(viewLifecycleOwner) {
toggleLabelView(it, viewModel.getIsScanningOn())
}
labelToInsert.observe(viewLifecycleOwner) {
labelAdapter.addNewDeviceLabel(it)
}
activeFiltersDescription.observe(viewLifecycleOwner) {
toggleFilterDescriptionView(it)
}
filteredDevices.observe(viewLifecycleOwner) {
if (isInitialGraphStateLoaded) {
chartView.updateChartData(
viewModel.getGraphDevicesState(),
viewModel.highlightedLabel.value
)
labelAdapter.updateLabels(viewModel.getLabelViewsState())
}
}
highlightedLabel.observe(viewLifecycleOwner) {
if (isInitialGraphStateLoaded) {
labelAdapter.updateHighlightedDevice(it)
chartView.updateChartData(viewModel.getGraphDevicesState(), it)
}
}
}
}
override fun onResume() {
super.onResume()
getScanFragment().apply {
setScanFragmentListener(scanFragmentListener)
refreshViewState(viewModel.getGraphFragmentViewState())
}
}
private fun refreshViewState(viewState: GraphFragmentViewState) {
toggleScanningViews(viewState.isScanningOn)
labelAdapter.apply {
updateLabels(viewState.labelsInfo)
updateHighlightedDevice(viewState.highlightedLabel)
}
chartView.apply {
if (viewModel.shouldResetChart) {
reset()
viewModel.shouldResetChart = false
}
updateTimestamp(viewState.scanTimestamp)
updateChartData(viewState.graphInfo, viewState.highlightedLabel)
}
isInitialGraphStateLoaded = true
}
private fun toggleScanningViews(isScanningOn: Boolean) {
toggleLabelView(viewModel.isAnyDeviceDiscovered.value ?: false, isScanningOn)
toggleScanningButton(isScanningOn)
}
override fun onDestroy() {
super.onDestroy()
executor?.shutdown()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_rssi_graph, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.rssi_filter_icon -> {
getScanFragment().toggleFilterFragment(shouldShowFilterFragment = true)
true
}
R.id.rssi_sort_icon -> {
viewModel.sortDevices()
labelAdapter.updateLabels(viewModel.getLabelViewsState())
_binding.rssiLabelWithDevices.smoothScrollTo(0, 0)
Toast.makeText(requireContext(), getString(R.string.rssi_labels_sorted_by_descending_rssi),
Toast.LENGTH_SHORT).show()
true
}
R.id.rssi_csv_export -> {
if (viewModel.isAnyDeviceDiscovered.value == true) {
startActivityForResult(Intent(ACTION_OPEN_DOCUMENT_TREE), EXPORT_TO_CSV_CODE)
showShortToast(R.string.rssi_graph_file_location_chooser)
} else {
showShortToast(R.string.no_graph_data_to_export)
}
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK) {
when (requestCode) {
EXPORT_TO_CSV_CODE -> onExportLocationChosen(data)
}
}
}
private fun onExportLocationChosen(intent: Intent?) {
intent?.data?.let {
DocumentFile.fromTreeUri(requireContext(), it)?.let { dirLocation ->
dirLocation.createFile("text/csv", createFileName())?.let { fileLocation ->
val fileContent = GraphDataExporter().export(
viewModel.getExportDevicesState(),
viewModel.miliTimestamp,
viewModel.nanoTimestamp)
activity?.contentResolver?.openOutputStream(fileLocation.uri)?.let { stream ->
stream.write(fileContent.toByteArray())
showShortToast(R.string.gatt_configurator_toast_export_successful)
} ?: showShortToast(R.string.gatt_configurator_toast_export_unsuccessful)
} ?: showLongToast(R.string.rssi_graph_file_creation_unsuccessful)
} ?: showLongToast(R.string.toast_export_wrong_location_chosen)
} ?: showLongToast(R.string.toast_export_wrong_location_chosen)
}
private fun createFileName() : String {
val calendar = Calendar.getInstance()
val dateFormatter = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM).apply {
timeZone = calendar.timeZone
}
return "graph-data-${dateFormatter.format(calendar.time)}.csv"
}
private fun showLongToast(@StringRes message: Int) {
Toast.makeText(requireContext(), message, Toast.LENGTH_LONG).show()
}
private fun showShortToast(@StringRes message: Int) {
Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
}
private fun toggleRefreshGraphRunnable(isOn: Boolean) {
handler.let {
if (isOn) {
it.removeCallbacks(drawGraphRunnable)
it.post(drawGraphRunnable)
} else {
it.removeCallbacks(drawGraphRunnable)
}
}
}
private fun toggleLabelView(isAnyDeviceDiscovered: Boolean, isScanningOn: Boolean) {
_binding.apply {
if (isAnyDeviceDiscovered) {
rssiLabelDescription.visibility = View.GONE
rssiLabelWithDevices.visibility = View.VISIBLE
} else {
rssiLabelDescription.visibility = View.VISIBLE
rssiLabelWithDevices.visibility = View.GONE
rssiLabelDescription.text = getString(
if (isScanningOn) R.string.device_scanning_background_message
else R.string.no_devices_found_title_copy
)
}
}
}
private fun toggleFilterDescriptionView(description: String?) {
_binding.activeFiltersDescription.apply {
description?.let {
visibility = View.VISIBLE
text = it
} ?: run { visibility = View.GONE }
}
}
private val legendClickHandler = object : GraphLabelAdapter.LegendClickHandler {
override fun onLegendItemClicked(device: ScanFragmentViewModel.LabelViewState?) {
viewModel.handleOnLegendItemClick(device)
}
}
private val timeArrowHandler = object : ChartView.TimeArrowsHandler {
override fun handleVisibility(isStartArrowVisible: Boolean, isEndArrowVisible: Boolean) {
//runOnUiThread {
_binding.rssiGraphTimeArrowStart.visibility =
if (isStartArrowVisible) View.VISIBLE
else View.INVISIBLE
_binding.rssiGraphTimeArrowEnd.visibility =
if (isEndArrowVisible) View.VISIBLE
else View.INVISIBLE
//}
}
}
private fun showGraphArrows() {
_binding.apply {
rssiGraphTimeArrowStart.visibility = View.VISIBLE
rssiGraphTimeArrowEnd.visibility = View.VISIBLE
}
}
private val drawGraphRunnable = object : Runnable {
override fun run() {
chartView.updateChartData(viewModel.getGraphDevicesState(), viewModel.highlightedLabel.value)
handler.postDelayed(this, GRAPH_REFRESH_PERIOD)
}
}
private fun toggleScanningButton(isScanningOn: Boolean) {
_binding.rssiGraphBtnScanning.apply {
text = getString(
if (isScanningOn) R.string.button_stop_scanning
else R.string.button_start_scanning
)
setIsActionOn(isScanningOn)
}
}
companion object {
private const val GRAPH_REFRESH_PERIOD = 250L // ms
private const val ANIMATION_DELAY = 250L // give user a chance to see what's going on
private const val INITIALIZATION_DELAY = 750L // smooth user experience when creating fragment
private const val EXPORT_TO_CSV_CODE = 201
}
}
| 6 | null |
70
| 96 |
a4e476451c17abaa67b1ba85c81dd6146e5c5715
| 15,743 |
EFRConnect-android
|
Apache License 2.0
|
compose/src/main/java/pn/android/compose/components/calendar/CalendarPreview.kt
|
purenative
| 577,193,628 | false | null |
package pn.android.compose.components.calendar
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Divider
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.kizitonwose.calendar.compose.VerticalCalendar
import com.kizitonwose.calendar.compose.rememberCalendarState
import com.kizitonwose.calendar.core.CalendarDay
import com.kizitonwose.calendar.core.CalendarMonth
import com.kizitonwose.calendar.core.DayPosition
import com.kizitonwose.calendar.core.daysOfWeek
import pn.android.compose.components.calendar.ContinuousSelectionHelper.getSelection
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.YearMonth
private val primaryColor = Color.Black.copy(alpha = 0.9f)
@Composable
fun CalendarExample() {
val currentMonth = remember { YearMonth.now() }
val startMonth = remember { currentMonth }
val endMonth = remember { currentMonth.plusMonths(12) }
val today = remember { LocalDate.now() }
var selection by remember { mutableStateOf(DateSelection()) }
val daysOfWeek = remember { daysOfWeek() }
MaterialTheme(colors = MaterialTheme.colors.copy(primary = primaryColor)) {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.White),
) {
Column {
val state = rememberCalendarState(
startMonth = startMonth,
endMonth = endMonth,
firstVisibleMonth = currentMonth,
firstDayOfWeek = daysOfWeek.first(),
)
CalendarTop(
daysOfWeek = daysOfWeek,
selection = selection,
clearDates = { selection = DateSelection() },
)
VerticalCalendar(
state = state,
contentPadding = PaddingValues(bottom = 100.dp),
dayContent = { value ->
Day(
value,
today = today,
) { day ->
if (day.position == DayPosition.MonthDate &&
(day.date == today || day.date.isAfter(today))
) {
selection = getSelection(
clickedDate = day.date,
dateSelection = selection,
)
}
}
},
monthHeader = { month -> MonthHeader(month) },
)
}
}
}
}
@Composable
private fun Day(
day: CalendarDay,
today: LocalDate,
onClick: (CalendarDay) -> Unit,
) {
Box(
modifier = Modifier
.aspectRatio(1f)
.clickable(
enabled = day.position == DayPosition.MonthDate && day.date >= today,
showRipple = false,
onClick = { onClick(day) },
),
contentAlignment = Alignment.Center,
) {
Text(
text = day.date.dayOfMonth.toString(),
color = Color.Black,
fontSize = 16.sp,
fontWeight = FontWeight.Medium,
)
}
}
@Composable
private fun MonthHeader(calendarMonth: CalendarMonth) {
Box(
modifier = Modifier
.fillMaxWidth()
.padding(top = 12.dp, bottom = 8.dp, start = 16.dp, end = 16.dp),
) {
Text(
textAlign = TextAlign.Center,
text = calendarMonth.yearMonth.displayText(),
fontSize = 18.sp,
fontWeight = FontWeight.Bold,
)
}
}
@Composable
private fun CalendarTop(
modifier: Modifier = Modifier,
daysOfWeek: List<DayOfWeek>,
selection: DateSelection,
clearDates: () -> Unit,
) {
Column(modifier.fillMaxWidth()) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(top = 6.dp, bottom = 10.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
Row(
modifier = Modifier.height(IntrinsicSize.Max),
verticalAlignment = Alignment.CenterVertically,
) {
Spacer(modifier = Modifier.weight(1f))
Text(
modifier = Modifier
.clip(RoundedCornerShape(percent = 50))
.clickable(onClick = clearDates)
.padding(horizontal = 16.dp, vertical = 8.dp),
text = "Clear",
fontWeight = FontWeight.Medium,
textAlign = TextAlign.End,
)
}
val daysBetween = selection.daysBetween
val text = if (daysBetween == null) {
"Select dates"
} else {
"$daysBetween ${if (daysBetween == 1L) "night" else "nights"} in Munich"
}
Text(
modifier = Modifier.padding(horizontal = 14.dp),
text = text,
fontWeight = FontWeight.Bold,
fontSize = 24.sp,
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(top = 4.dp),
) {
for (dayOfWeek in daysOfWeek) {
Text(
modifier = Modifier.weight(1f),
textAlign = TextAlign.Center,
color = Color.DarkGray,
text = dayOfWeek.displayText(),
fontSize = 15.sp,
)
}
}
}
Divider()
}
}
@Preview(heightDp = 800)
@Composable
private fun CalendarPreview() {
CalendarExample()
}
| 7 | null |
0
| 9 |
97493e520eaa0c950447859477b5da136fb0adaf
| 6,519 |
pn-android
|
MIT License
|
order-api/src/main/kotlin/ru/romanow/inst/services/order/model/OrderInfoResponse.kt
|
Romanow
| 304,987,654 | false |
{"Kotlin": 117029, "JavaScript": 2720, "Dockerfile": 2127, "HCL": 1533, "Shell": 1444}
|
package ru.romanow.inst.services.order.model
import java.util.UUID
data class OrderInfoResponse(
var orderUid: UUID,
val orderDate: String,
val itemUid: UUID,
val status: PaymentStatus
)
| 5 |
Kotlin
|
4
| 3 |
fd7c37f495511382a26109c1f634e1aaf6001bb9
| 205 |
micro-services-v2
|
MIT License
|
lib/src/test/kotlin/lsp_proxy_tools/ProxyFunctionsKtTest.kt
|
MozarellaMan
| 339,113,832 | false | null |
package lsp_proxy_tools
import com.github.kittinunf.fuel.core.Client
import com.github.kittinunf.fuel.core.FuelManager
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.runBlocking
import kotlin.test.BeforeTest
import kotlin.test.Test
internal class ProxyFunctionsKtTest {
//@Test
fun getFile() {
val client = mockk<Client>()
every { client.executeRequest(any()).statusCode } returns 500
FuelManager.instance.client = client
runBlocking {
val result = getFile("test", "test")
println(result)
assert(result.startsWith("PROXY ERROR:"))
}
}
}
| 0 |
Kotlin
|
0
| 0 |
140435bbc15dcc1be15fc291018c29d9571eef36
| 653 |
Language-Server-Proxy-Tools
|
MIT License
|
src/main/kotlin/com/rkd/domain/RkdDomainModuleApplication.kt
|
madrijkaard
| 831,108,493 | false |
{"Kotlin": 8273}
|
package com.rkd.domain
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class RkdDomainModuleApplication
fun main(args: Array<String>) {
runApplication<RkdDomainModuleApplication>(*args)
}
| 0 |
Kotlin
|
0
| 0 |
c9a5e0ceb57909e53ea2aee361c8caec12880102
| 282 |
rkd-domain-module
|
MIT License
|
nextgen-middleware/src/main/java/com/nextgenbroadcast/mobile/middleware/rpc/processor/AbstractRPCProcessor.kt
|
jjustman
| 418,004,011 | false | null |
package com.nextgenbroadcast.mobile.middleware.rpc.processor
import android.util.Log
import com.fasterxml.jackson.core.JsonProcessingException
import com.github.nmuzhichin.jsonrpc.api.RpcConsumer
import com.github.nmuzhichin.jsonrpc.model.request.Request
import com.github.nmuzhichin.jsonrpc.model.response.ResponseUtils
import com.github.nmuzhichin.jsonrpc.model.response.errors.Error
import com.nextgenbroadcast.mobile.middleware.rpc.RpcError
import com.nextgenbroadcast.mobile.middleware.rpc.RpcErrorCode
internal abstract class AbstractRPCProcessor(
private val consumer: RpcConsumer
) : IRPCProcessor {
private val rpcObjectMapper = RPCObjectMapper()
override fun processRequest(payload: String): String {
var requestId: Long = -1L
return try {
val request = rpcObjectMapper.jsonToObject(payload, Request::class.java).also { request ->
requestId = request.id
}
val response = consumer.execution(request)
if(response.isError) {
Log.w(TAG, "processRequest: response.isError: requestId: $requestId, request: $payload, $response")
}
rpcObjectMapper.objectToJson(response)
} catch (e: JsonProcessingException) {
Log.e(TAG, "processRequest: exception: requestId: $requestId, request: $payload", e)
errorResponse(requestId, e)
}
}
override fun processRequest(requests: List<String>): List<String> {
return try {
val requestList = requests.map { rpcObjectMapper.jsonToObject(it, Request::class.java) }
val responseList = consumer.execution(requestList)
responseList.map { rpcObjectMapper.objectToJson(it) }
} catch (e: JsonProcessingException) {
e.printStackTrace()
ArrayList<String>(requests.size).apply {
//TODO: we should return error's with request ID's
fill("")
}
}
}
private fun errorResponse(requestId: Long, e: Exception): String {
return try {
rpcObjectMapper.objectToJson(ResponseUtils.createResponse(requestId, InternalRpcError(RpcErrorCode.PARSING_ERROR_CODE.code, e.localizedMessage)))
} catch (ex: JsonProcessingException) {
// This catch should never being executed, but it's need because objectMapper throw exception
""
}
}
internal class InternalRpcError(code: Int, message: String?) : RpcError(code, message), Error {
override fun getData(): Any? {
return null
}
}
companion object {
val TAG: String = AbstractRPCProcessor::class.java.simpleName
}
}
| 0 |
Kotlin
|
0
| 5 |
f0d91240d7c68c57c7ebfd0739148c86a38ffa58
| 2,709 |
libatsc3-middleware-sample-app
|
MIT License
|
core/src/main/kotlin/com/tea505/teaplanner/core/kinematics/Drivetrain.kt
|
Tea505
| 802,756,909 | false |
{"Kotlin": 42155}
|
package com.tea505.teaplanner.core.kinematics
import com.tea505.teaplanner.core.geometry.Pose
interface Drivetrain {
fun set(pose: Pose)
}
| 0 |
Kotlin
|
0
| 0 |
1a0e2731284d726d717aa761575de7cfb8c387ac
| 145 |
TeaLeafPlanner
|
MIT License
|
delivery/src/main/kotlin/me/rasztabiga/thesis/delivery/adapter/out/fake/FakeCalculateDeliveryFeeAdapter.kt
|
BartlomiejRasztabiga
| 604,846,079 | false | null |
package me.rasztabiga.thesis.delivery.adapter.out.fake
import me.rasztabiga.thesis.delivery.domain.command.port.CalculateDeliveryFeePort
import org.springframework.stereotype.Service
import java.math.BigDecimal
@Service
class FakeCalculateDeliveryFeeAdapter : CalculateDeliveryFeePort {
@Suppress("MagicNumber")
override fun calculateBaseFee(restaurantAddress: String, deliveryAddress: String): BigDecimal {
val a = restaurantAddress.length
val b = deliveryAddress.length
return BigDecimal.valueOf((a + b) * 0.1)
}
}
| 21 |
Kotlin
|
0
| 0 |
6e63bb2b65e3e9e2edf1dbb548ad189b021500e8
| 556 |
thesis
|
MIT License
|
src/plugin/cli/src/commonTest/kotlin/community/flock/wirespec/plugin/cli/io/MainTest.kt
|
flock-community
| 506,356,849 | false |
{"Kotlin": 611564, "Shell": 7126, "TypeScript": 5819, "Witcher Script": 4248, "Java": 2714, "Dockerfile": 625, "Makefile": 555, "JavaScript": 140}
|
package community.flock.wirespec.plugin.cli.io
import community.flock.wirespec.plugin.Format
import community.flock.wirespec.plugin.Language
import io.kotest.matchers.shouldBe
import kotlin.test.Test
class MainTest {
@Test
fun testFormat() {
Format.toString() shouldBe "OpenApiV2, OpenApiV3"
}
@Test
fun testLanguages() {
Language.toString() shouldBe "Java, Kotlin, Scala, TypeScript, Wirespec"
}
}
| 20 |
Kotlin
|
1
| 16 |
d96b9fa18a136496d10c9a30a55f30d5ab78a28a
| 443 |
wirespec
|
Apache License 2.0
|
vector/src/test/java/com/haroldadmin/vector/state/StateHolderTest.kt
|
haroldadmin
| 190,186,711 | false | null |
package com.haroldadmin.vector.state
import com.haroldadmin.vector.loggers.StringLogger
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.takeWhile
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.junit.Test
class StateHolderTest {
@Test
fun `StateHolderFactory creates correctly configured StateHolder instance`() {
val initState = CountingState()
val stateHolder = StateHolderFactory.create(
initialState = initState,
logger = StringLogger()
)
assert(stateHolder.state == initState)
}
@Test
fun `state property contains the latest state`() {
val initState = CountingState()
val stateHolder = StateHolderFactory.create(
initialState = initState,
logger = StringLogger()
)
stateHolder.updateState(CountingState(count = 42))
assert(stateHolder.state.count == 42) {
"Expected current count to be 42, got ${stateHolder.state.count}"
}
}
@Test
fun `state updates are conflated`() = runBlocking {
val initState = CountingState()
val stateHolder = StateHolderFactory.create(initState, StringLogger())
val numberOfUpdates = 10
// Fast producer
launch {
for (i in 1..10) {
val currentState = stateHolder.state
val newState = currentState.copy(count = i)
stateHolder.updateState(newState)
}
stateHolder.clearHolder()
}
var collectedUpdates = 0
// Slow consumer
stateHolder
.stateObservable
.takeWhile { it.count < numberOfUpdates }
.collect {
collectedUpdates++
delay(1)
}
assert(collectedUpdates < numberOfUpdates) {
"StateUpdates were not conflated, received as many updates as were produced"
}
}
}
| 13 |
Kotlin
|
7
| 197 |
2f52fd2b42cfc516854c6ae534cdd9f73e982579
| 2,030 |
Vector
|
Apache License 2.0
|
src/main/kotlin/no/nav/sf/pdl/kafka/poster/KafkaToSFPoster.kt
|
navikt
| 724,974,015 | false |
{"Kotlin": 81822, "HTML": 15821, "Dockerfile": 137}
|
package no.nav.sf.pdl.kafka.poster
import mu.KotlinLogging
import no.nav.sf.pdl.kafka.config_FLAG_NO_POST
import no.nav.sf.pdl.kafka.config_FLAG_RUN_ONCE
import no.nav.sf.pdl.kafka.config_FLAG_SEEK
import no.nav.sf.pdl.kafka.config_KAFKA_POLL_DURATION
import no.nav.sf.pdl.kafka.config_KAFKA_TOPIC
import no.nav.sf.pdl.kafka.config_NUMBER_OF_SAMPLES
import no.nav.sf.pdl.kafka.config_SEEK_OFFSET
import no.nav.sf.pdl.kafka.env
import no.nav.sf.pdl.kafka.envAsBoolean
import no.nav.sf.pdl.kafka.envAsInt
import no.nav.sf.pdl.kafka.envAsLong
import no.nav.sf.pdl.kafka.kafka.KafkaConsumerFactory
import no.nav.sf.pdl.kafka.metrics.WorkSessionStatistics
import no.nav.sf.pdl.kafka.salesforce.KafkaMessage
import no.nav.sf.pdl.kafka.salesforce.SalesforceClient
import no.nav.sf.pdl.kafka.salesforce.isSuccess
import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.clients.consumer.ConsumerRecords
import org.apache.kafka.clients.consumer.KafkaConsumer
import org.apache.kafka.common.TopicPartition
import java.io.File
import java.time.Duration
import java.util.Base64
/**
* KafkaToSFPoster
* This class is responsible for handling a work session, ie polling and posting to salesforce until we are up-to-date with topic
* Makes use of SalesforceClient to set up connection to salesforce
*/
class KafkaToSFPoster(
private val filter: ((ConsumerRecord<String, String?>) -> Boolean)? = null,
private val modifier: ((ConsumerRecord<String, String?>) -> String?)? = null,
private val sfClient: SalesforceClient = SalesforceClient(),
private val kafkaTopic: String = env(config_KAFKA_TOPIC),
private val kafkaConsumerFactory: KafkaConsumerFactory = KafkaConsumerFactory(),
private val kafkaPollDuration: Long = envAsLong(config_KAFKA_POLL_DURATION),
private val flagSeek: Boolean = envAsBoolean(config_FLAG_SEEK),
private val seekOffset: Long = envAsLong(config_SEEK_OFFSET),
numberOfSamples: Int = envAsInt(config_NUMBER_OF_SAMPLES),
private val flagNoPost: Boolean = envAsBoolean(config_FLAG_NO_POST),
private val flagRunOnce: Boolean = envAsBoolean(config_FLAG_RUN_ONCE)
) {
private enum class ConsumeResult { SUCCESSFULLY_CONSUMED_BATCH, NO_MORE_RECORDS, FAIL }
private val log = KotlinLogging.logger { }
private var samplesLeft = numberOfSamples
private var hasRunOnce = false
private lateinit var stats: WorkSessionStatistics
fun runWorkSession() {
if (flagRunOnce && hasRunOnce) {
log.info { "Work session skipped due to flag Run Once, and has consumed once" }
return
}
stats = WorkSessionStatistics()
// Instantiate each work session to fetch config from current state of environment (fetch injected updates of credentials)
val kafkaConsumer = setupKafkaConsumer(kafkaTopic)
hasRunOnce = true
pollAndConsume(kafkaConsumer)
}
private fun setupKafkaConsumer(kafkaTopic: String): KafkaConsumer<String, String?> {
return kafkaConsumerFactory.createConsumer().apply {
// Using assign rather than subscribe since we need the ability to seek to a particular offset
val topicPartitions = partitionsFor(kafkaTopic).map { TopicPartition(it.topic(), it.partition()) }
assign(topicPartitions)
log.info { "Starting work session on topic $kafkaTopic with ${topicPartitions.size} partitions" }
if (!hasRunOnce) {
if (flagSeek) {
topicPartitions.forEach {
seek(it, seekOffset)
}
}
}
}
}
private tailrec fun pollAndConsume(kafkaConsumer: KafkaConsumer<String, String?>) {
val records = kafkaConsumer.poll(Duration.ofMillis(kafkaPollDuration))
as ConsumerRecords<String, String?>
if (consumeRecords(records) == ConsumeResult.SUCCESSFULLY_CONSUMED_BATCH) {
kafkaConsumer.commitSync() // Will update position of kafka consumer in kafka cluster
pollAndConsume(kafkaConsumer)
}
}
private fun consumeRecords(recordsFromTopic: ConsumerRecords<String, String?>): ConsumeResult =
if (recordsFromTopic.isEmpty) {
if (!stats.hasConsumed()) {
WorkSessionStatistics.subsequentWorkSessionsWithEventsCounter.clear()
WorkSessionStatistics.workSessionsWithoutEventsCounter.inc()
log.info { "Finished work session without consuming. Number of work sessions without events during lifetime of app: ${WorkSessionStatistics.workSessionsWithoutEventsCounter.get().toInt()}" }
} else {
WorkSessionStatistics.subsequentWorkSessionsWithEventsCounter.inc()
log.info { "Finished work session with activity (subsequent ${WorkSessionStatistics.subsequentWorkSessionsWithEventsCounter.get().toInt()}). $stats" }
}
ConsumeResult.NO_MORE_RECORDS
} else {
WorkSessionStatistics.workSessionsWithoutEventsCounter.clear()
stats.updateConsumedStatistics(recordsFromTopic)
val recordsFiltered = filterRecords(recordsFromTopic)
if (samplesLeft > 0) sampleRecords(recordsFiltered)
if (recordsFiltered.count() == 0 || flagNoPost) {
if (recordsFiltered.count() > 0) updateWhatWouldBeSent(recordsFiltered)
// Either we have set a flag to not post to salesforce, or the filter ate all candidates -
// consider it a successfully consumed batch without further action
ConsumeResult.SUCCESSFULLY_CONSUMED_BATCH
} else {
if (sfClient.postRecords(recordsFiltered.toKafkaMessagesSet()).isSuccess()) {
stats.updatePostedStatistics(recordsFiltered)
ConsumeResult.SUCCESSFULLY_CONSUMED_BATCH
} else {
log.warn { "Failed when posting to SF - $stats" }
WorkSessionStatistics.failedSalesforceCallCounter.inc()
ConsumeResult.FAIL
}
}
}
// For testdata:
private var whatWouldBeSentBatch = 1
private fun updateWhatWouldBeSent(recordsFiltered: Iterable<ConsumerRecord<String, String?>>) {
File("/tmp/whatwouldbesent").appendText("BATCH ${whatWouldBeSentBatch++}\n${recordsFiltered.toKafkaMessagesSet().joinToString("\n")}\n\n")
}
private fun filterRecords(records: ConsumerRecords<String, String?>): Iterable<ConsumerRecord<String, String?>> {
val recordsPostFilter = filter?.run { records.filter { invoke(it) } } ?: records
stats.incBlockedByFilter(records.count() - recordsPostFilter.count())
return recordsPostFilter
}
private fun Iterable<ConsumerRecord<String, String?>>.toKafkaMessagesSet(): Set<KafkaMessage> {
val kafkaMessages = this.map {
KafkaMessage(
CRM_Topic__c = it.topic(),
CRM_Key__c = it.key(),
CRM_Value__c = (modifier?.run { invoke(it) } ?: it.value())?.encodeB64()
)
}
val uniqueKafkaMessages = kafkaMessages.toSet()
val uniqueValueCount = uniqueKafkaMessages.count()
if (kafkaMessages.size != uniqueValueCount) {
log.warn { "Detected ${kafkaMessages.size - uniqueValueCount} duplicates in $kafkaTopic batch" }
}
return uniqueKafkaMessages
}
private fun sampleRecords(records: Iterable<ConsumerRecord<String, String?>>) {
records.forEach {
if (samplesLeft-- > 0) {
File("/tmp/samplesFromTopic").appendText("KEY: ${it.key()}\nVALUE: ${it.value()}\n\n")
if (modifier != null) {
File("/tmp/samplesAfterModifier").appendText("KEY: ${it.key()}\nVALUE: ${modifier.invoke(it)}\n\n")
}
log.info { "Saved sample. Samples left: $samplesLeft" }
}
}
}
private fun String.encodeB64(): String = Base64.getEncoder().encodeToString(this.toByteArray())
}
| 0 |
Kotlin
|
0
| 0 |
bfd04a04f15d3107c1a3ab741514d08a8ae10658
| 8,135 |
sf-pdl-kafka
|
MIT License
|
App/app/src/main/java/com/project/tripod/data/LoginUiState.kt
|
HemangMishra1234
| 806,070,121 | false |
{"Kotlin": 77658}
|
package com.project.tripod.data
data class LoginUiState(
val email: String = "",
val password: String = ""
)
| 0 |
Kotlin
|
0
| 0 |
1ff3fe9bd4bc3f26d1036812a1cef188af603810
| 118 |
Tripod
|
MIT License
|
core/database/src/main/kotlin/com/lolo/io/onelist/core/database/model/ItemEntity.kt
|
lolo-io
| 198,519,184 | false |
{"Kotlin": 363415, "Roff": 549}
|
package com.lolo.io.onelist.core.database.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.io.Serializable
@Entity (
tableName = "item"
)
data class ItemEntity(
val title: String = "",
val comment: String = "",
val done: Boolean = false,
val commentDisplayed: Boolean = false,
@PrimaryKey(autoGenerate = true)
val id: Long = 0L,
)
| 18 |
Kotlin
|
26
| 92 |
ca7df6ec46344bde7c5e357d0784ecdfdecbb78e
| 400 |
OneList
|
MIT License
|
src/main/kotlin/io/warp10/warpscriptDSL/Macro.kt
|
aurrelhebert
| 113,035,308 | false | null |
package io.warp10.warpscriptDSL
//
// WarpScript KOTLINDSL
// @author aurrelhebert
// @license apache 2.0
//
//
// WarpScript Macro builder
//
class Macro : FunctionElement {
// Macro body elements
val bodyArray = arrayListOf<Element>()
// Macro output rendering
override fun render(builder: StringBuilder, indent: String) {
if (!bodyArray.isEmpty()) {
builder.append("$indent <% \n")
for (items in bodyArray) {
items.render(builder,indent + " ")
}
builder.append(indent + " %> \n")
}
}
//
// Function used to fill macro body code with all the child element of current Macro
//
fun applyBody(ws: WarpScript, entry: Element.() -> Unit) {
this.bodyArray.addAll(this.getChilds(ws,entry))
}
// Basic constructor
constructor() : super("") {
}
}
| 0 |
Kotlin
|
0
| 0 |
fe9debfb3a6ca01517c22f9d09fa31bd5d03776d
| 889 |
KotWarpLinDSL
|
Apache License 2.0
|
library/games/src/main/kotlin/xyz/fcampbell/rxplayservices/games/RxAchievements.kt
|
francoiscampbell
| 75,945,848 | true | null |
package xyz.fcampbell.rxplayservices.games
import android.content.Context
import android.content.Intent
import com.google.android.gms.common.api.Scope
import com.google.android.gms.games.Games
import com.google.android.gms.games.achievement.Achievements
import io.reactivex.Completable
import io.reactivex.Observable
import xyz.fcampbell.rxplayservices.base.ApiClientDescriptor
import xyz.fcampbell.rxplayservices.base.ApiDescriptor
import xyz.fcampbell.rxplayservices.base.RxPlayServicesApi
/**
* Wraps [Games.Achievements]
*/
@Suppress("unused")
class RxAchievements(
apiClientDescriptor: ApiClientDescriptor,
gamesOptions: Games.GamesOptions,
vararg scopes: Scope
) : RxPlayServicesApi<Achievements, Games.GamesOptions>(
apiClientDescriptor,
ApiDescriptor(Games.API, Games.Achievements, gamesOptions, *scopes)
) {
constructor(
context: Context,
gamesOptions: Games.GamesOptions,
vararg scopes: Scope
) : this(ApiClientDescriptor(context), gamesOptions, *scopes)
fun getAchievementsIntent(): Observable<Intent> {
return map { getAchievementsIntent(it) }
}
fun load(forceReload: Boolean): Observable<Achievements.LoadAchievementsResult> {
return fromPendingResult { load(it, forceReload) }
}
fun reveal(id: String): Completable {
return toCompletable { reveal(it, id) }
}
fun revealImmediate(id: String): Observable<Achievements.UpdateAchievementResult> {
return fromPendingResult { revealImmediate(it, id) }
}
fun unlock(id: String): Completable {
return toCompletable { unlock(it, id) }
}
fun unlockImmediate(id: String): Observable<Achievements.UpdateAchievementResult> {
return fromPendingResult { unlockImmediate(it, id) }
}
fun increment(id: String, numSteps: Int): Completable {
return toCompletable { increment(it, id, numSteps) }
}
fun incrementImmediate(id: String, numSteps: Int): Observable<Achievements.UpdateAchievementResult> {
return fromPendingResult { incrementImmediate(it, id, numSteps) }
}
fun setSteps(id: String, numSteps: Int): Completable {
return toCompletable { setSteps(it, id, numSteps) }
}
fun setStepsImmediate(id: String, numSteps: Int): Observable<Achievements.UpdateAchievementResult> {
return fromPendingResult { setStepsImmediate(it, id, numSteps) }
}
}
| 1 |
Kotlin
|
2
| 10 |
b7461e4534a81d78f7bf70a6047395b059e61c3c
| 2,448 |
RxPlayServices
|
Apache License 2.0
|
LeetCode/UglyNumber/Iteration1.kt
|
MahdiDavoodi
| 434,677,181 | false |
{"Kotlin": 57766, "JavaScript": 17002, "Java": 10647, "HTML": 696, "Python": 683}
|
class Solution {
fun isUgly(n: Int): Boolean {
if (n <= 0) return false
var number = n
while (true) {
if (number.rem(2) == 0) number /= 2
else if (number.rem(3) == 0) number /= 3
else if (number.rem(5) == 0) number /= 5
else return number == 1
}
}
}
/**
* Divide the number by 2,3,5 until it's not dividable.
* If it equals to 1, return true. However, return false.
* */
| 0 |
Kotlin
|
0
| 0 |
62a23187efc6299bf921a95c8787d02d5be51742
| 461 |
ProblemSolving
|
MIT License
|
library/src/main/java/com/liulishuo/mercury/library/model/ILogin.kt
|
lingochamp
| 92,384,104 | false |
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Java": 4, "XML": 7, "Kotlin": 11}
|
package com.liulishuo.mercury.library.model
/**
* Created by echo on 5/23/17.
*/
interface ILogin {
fun login(loginCallback: LoginCallback)
}
| 0 |
Kotlin
|
1
| 9 |
ef2c850b2c24a232dbcb8016d50f7e18e53755e0
| 148 |
Mercury
|
MIT License
|
px-checkout/src/main/java/com/mercadopago/android/px/tracking/internal/model/GenericDialogTrackData.kt
|
mercadopago
| 49,529,486 | false | null |
package com.mercadopago.android.px.tracking.internal.model
import java.util.*
sealed class GenericDialogTrackData(private val description: String, hasSecondaryAction: Boolean) : TrackingMapModel() {
val actions = if (hasSecondaryAction) 2 else 1
class Open(description: String, hasSecondaryAction: Boolean) :
GenericDialogTrackData(description, hasSecondaryAction)
class Dismiss(description: String, hasSecondaryAction: Boolean) :
GenericDialogTrackData(description, hasSecondaryAction)
class Action(
private val deepLink: String,
type: Type,
description: String,
hasSecondaryAction: Boolean) : GenericDialogTrackData(description, hasSecondaryAction) {
val type = type.name.toLowerCase(Locale.ROOT)
}
enum class Type {
MAIN_ACTION,
SECONDARY_ACTION
}
}
| 44 | null |
77
| 98 |
b715075dd4cf865f30f6448f3c00d6e9033a1c21
| 859 |
px-android
|
MIT License
|
30 Days of Code (Kotlin)/day3-conditional-statements.kt
|
swapnanildutta
| 259,629,657 | false | null |
/*
Question
In this challenge, we're getting started with conditional statements. Check out the Tutorial tab for learning materials and an instructional video!
Task
Given an integer,
, perform the following conditional actions:
If
is odd, print Weird
If
is even and in the inclusive range of to
, print Not Weird
If
is even and in the inclusive range of to
, print Weird
If
is even and greater than
, print Not Weird
Complete the stub code provided in your editor to print whether or not
is weird.
Input Format
A single line containing a positive integer,
.
Constraints
Output Format
Print Weird if the number is weird; otherwise, print Not Weird.
Sample Input 0
3
Sample Output 0
Weird
Sample Input 1
24
Sample Output 1
Not Weird
Explanation
Sample Case 0:
is odd and odd numbers are weird, so we print Weird.
Sample Case 1:
and is even, so it isn't weird. Thus, we print Not Weird.
*/
import java.util.Scanner
fun main() {
val scan = Scanner(System.`in`)
val N = scan.nextLine().trim().toInt();
if(N%2==1){
println("Weird");
}
else{
if(N>20){
println("Not Weird");
}
else
if(N>=6){
println("Weird");
}
else{
println("Not Weird");
}
}
}
| 41 | null |
202
| 65 |
01b04ee56f1e4b151ff5b98094accfeb09b55a95
| 1,308 |
Hackerrank-Codes
|
MIT License
|
app/src/main/java/club/dev/mobile/ksu/takeanumber/UI/AddHelpSessionActivity.kt
|
KSU-Mobile-Dev-Club
| 169,265,974 | false |
{"Java": 36865, "Kotlin": 5939}
|
package club.dev.mobile.ksu.takeanumber.UI
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProviders
import androidx.preference.PreferenceManager
import club.dev.mobile.ksu.takeanumber.Data.HelpSession
import club.dev.mobile.ksu.takeanumber.R
import club.dev.mobile.ksu.takeanumber.ViewModels.HelpSessionViewModel
import com.google.firebase.auth.FirebaseAuth
class AddHelpSessionActivity : AppCompatActivity() {
private lateinit var mAuth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_help_session)
mAuth = FirebaseAuth.getInstance()
val createButton = findViewById<Button>(R.id.CreateHelpSessionButton)
createButton.setOnClickListener {
// Add a new help session to the database
val mViewModel = ViewModelProviders.of(this).get(HelpSessionViewModel::class.java)
val helpSessionTitle = findViewById<EditText>(R.id.NameOfHelpSession).text.toString()
val helpSession = HelpSession(helpSessionTitle, mAuth.currentUser!!.uid)
mViewModel.addHelpSession(helpSession)
// Open the TA View to that help session
val sessionIntent = Intent(this, TaHelpSessionActivity::class.java)
intent.putExtra("sessionKey", helpSession.firebaseKey)
startActivity(sessionIntent)
}
}
override fun onStart() {
super.onStart()
if (mAuth.currentUser == null) {
// Sign in the user anonymously.
mAuth.signInAnonymously().addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign-in successful
}
else {
// If sign in fails, display a message to the user.
Toast.makeText(baseContext, "Authentication failed.",
Toast.LENGTH_SHORT).show()
}
}
}
val NameOfCreator = findViewById<EditText>(R.id.NameOfCreator)
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
if (sharedPreferences.contains("key_user_name")) {
NameOfCreator.setText(sharedPreferences.getString("key_user_name", ""))
}
}
}
| 7 |
Java
|
1
| 1 |
cf5f89021016802c2a60b4a2101d6a6d56d241d2
| 2,508 |
TakeANumberAndroid
|
MIT License
|
Teacher-App/app/src/main/java/com/example/seeds/database/LogEntity.kt
|
microsoft
| 657,158,700 | false |
{"Markdown": 6, "Text": 7, "Ignore List": 10, "JSON": 16, "HTML": 2, "CSS": 3, "robots.txt": 1, "SVG": 1, "JavaScript": 103, "Batchfile": 5, "Shell": 3, "Maven POM": 2, "Dockerfile": 3, "INI": 2, "Java": 216, "Java Properties": 4, "JAR Manifest": 1, "YAML": 2, "Gradle": 3, "Proguard": 1, "Kotlin": 67, "XML": 96}
|
package com.example.seeds.database
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "log")
class LogEntity(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
val logText: String,
val time: String,
val user: String,
val priority: Int
)
| 2 |
Java
|
0
| 13 |
4e013636615321ab105cc239b3fa59533d1ac270
| 291 |
SEEDS
|
MIT License
|
grooves-core/src/main/kotlin/com/github/rahulsom/grooves/functions/EventClassifier.kt
|
rahulsom
| 82,593,452 | false |
{"Gradle Kotlin DSL": 12, "INI": 2, "Shell": 1, "Text": 14, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "AsciiDoc": 18, "Java": 74, "Kotlin": 65, "TOML": 1, "Gradle": 4, "Groovy": 34, "XML": 7, "YAML": 3, "JSON": 2, "SVG": 13, "SCSS": 1, "HTML": 3, "CSS": 4, "Java Server Pages": 1, "SQL": 1, "Java Properties": 1}
|
package com.github.rahulsom.grooves.functions
import com.github.rahulsom.grooves.EventType
import com.github.rahulsom.grooves.logging.Trace
/**
* Classifies the type of event.
*/
interface EventClassifier<Event> {
@Trace
fun invoke(event: Event): EventType
}
| 15 |
Java
|
5
| 9 |
86c79eef6f73f3acbfa380f962c6fcc302c9c376
| 270 |
grooves
|
Apache License 2.0
|
app/src/main/java/com/naufaldi_athallah_rifqi/todo_do/data/models/local/TodoLocal.kt
|
naufaldirfq
| 327,917,012 | false |
{"Gradle": 3, "Java Properties": 2, "Markdown": 3, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "JSON": 1, "Proguard": 1, "XML": 46, "Kotlin": 36, "Java": 8}
|
package com.naufaldi_athallah_rifqi.todo_do.data.models.local
import android.os.Parcelable
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.android.parcel.Parcelize
@Entity(tableName = "TodoLocal")
@Parcelize
data class TodoLocal(@PrimaryKey(autoGenerate = true) var id : Long? = null,
@ColumnInfo(name = "todo") val todo: String,
@ColumnInfo(name = "isCompleted") val isCompleted: Boolean,
@ColumnInfo(name = "date") val date: String,
@ColumnInfo(name = "createdAt") val createdAt: String) : Parcelable
| 1 | null |
1
| 1 |
8669a0b597a61db406a129474c55f8117d3d6196
| 648 |
todo-do-sourcecode
|
MIT License
|
plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/entity/ValuedEntityContext.kt
|
ingokegel
| 72,937,917 | false | null |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.core.entity
abstract class ValuedEntityContext<E : Entity> {
protected val values = mutableMapOf<String, Any>()
@Suppress("UNCHECKED_CAST")
operator fun <V : Any> get(entity: E) =
values[entity.path] as? V
open operator fun set(entity: E, value: Any) {
values[entity.path] = value
}
}
| 1 | null |
1
| 2 |
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 534 |
intellij-community
|
Apache License 2.0
|
tmp/arrays/youTrackTests/9487.kt
|
DaniilStepanov
| 228,623,440 | false | null |
// Original bug: KT-6611
fun <T> allTypes(clazz : Class<T>) : Set<Class<Any>>
= (listOf(clazz as Class<Any>) + (listOf(clazz.getSuperclass()) + clazz.getInterfaces().toList()).filterNotNull().flatMap { allTypes(it as Class<Any>) }).toSet()
| 1 | null |
1
| 1 |
602285ec60b01eee473dcb0b08ce497b1c254983
| 251 |
bbfgradle
|
Apache License 2.0
|
src/controller/java/generated/java/matter/devicecontroller/cluster/clusters/NetworkCommissioningCluster.kt
|
project-chip
| 244,694,174 | false |
{"C++": 23580999, "Java": 6220546, "Python": 3675274, "C": 2251760, "Kotlin": 1773635, "Objective-C": 1369219, "ZAP": 815702, "Objective-C++": 757226, "Shell": 291840, "CMake": 174761, "Jinja": 132617, "Dockerfile": 70720, "Swift": 29310, "JavaScript": 2379, "Emacs Lisp": 1042, "Tcl": 311}
|
/*
*
* Copyright (c) 2023 Project CHIP Authors
*
* 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 matter.devicecontroller.cluster.clusters
import matter.controller.MatterController
import matter.devicecontroller.cluster.structs.*
class NetworkCommissioningCluster(
private val controller: MatterController,
private val endpointId: UShort
) {
class ScanNetworksResponse(
val networkingStatus: UInt,
val debugText: String?,
val wiFiScanResults: List<NetworkCommissioningClusterWiFiInterfaceScanResultStruct>?,
val threadScanResults: List<NetworkCommissioningClusterThreadInterfaceScanResultStruct>?
)
class NetworkConfigResponse(
val networkingStatus: UInt,
val debugText: String?,
val networkIndex: UByte?,
val clientIdentity: ByteArray?,
val possessionSignature: ByteArray?
)
class ConnectNetworkResponse(
val networkingStatus: UInt,
val debugText: String?,
val errorValue: Int?
)
class QueryIdentityResponse(val identity: ByteArray, val possessionSignature: ByteArray?)
class NetworksAttribute(val value: List<NetworkCommissioningClusterNetworkInfoStruct>)
class LastNetworkingStatusAttribute(val value: UInt?)
class LastNetworkIDAttribute(val value: ByteArray?)
class LastConnectErrorValueAttribute(val value: Int?)
class SupportedWiFiBandsAttribute(val value: List<UInt>?)
class GeneratedCommandListAttribute(val value: List<UInt>)
class AcceptedCommandListAttribute(val value: List<UInt>)
class EventListAttribute(val value: List<UInt>)
class AttributeListAttribute(val value: List<UInt>)
suspend fun scanNetworks(
ssid: ByteArray?,
breadcrumb: ULong?,
timedInvokeTimeoutMs: Int? = null
): ScanNetworksResponse {
val commandId = 0L
if (timedInvokeTimeoutMs != null) {
// Do the action with timedInvokeTimeoutMs
} else {
// Do the action without timedInvokeTimeoutMs
}
}
suspend fun addOrUpdateWiFiNetwork(
ssid: ByteArray,
credentials: ByteArray,
breadcrumb: ULong?,
networkIdentity: ByteArray?,
clientIdentifier: ByteArray?,
possessionNonce: ByteArray?,
timedInvokeTimeoutMs: Int? = null
): NetworkConfigResponse {
val commandId = 2L
if (timedInvokeTimeoutMs != null) {
// Do the action with timedInvokeTimeoutMs
} else {
// Do the action without timedInvokeTimeoutMs
}
}
suspend fun addOrUpdateThreadNetwork(
operationalDataset: ByteArray,
breadcrumb: ULong?,
timedInvokeTimeoutMs: Int? = null
): NetworkConfigResponse {
val commandId = 3L
if (timedInvokeTimeoutMs != null) {
// Do the action with timedInvokeTimeoutMs
} else {
// Do the action without timedInvokeTimeoutMs
}
}
suspend fun removeNetwork(
networkID: ByteArray,
breadcrumb: ULong?,
timedInvokeTimeoutMs: Int? = null
): NetworkConfigResponse {
val commandId = 4L
if (timedInvokeTimeoutMs != null) {
// Do the action with timedInvokeTimeoutMs
} else {
// Do the action without timedInvokeTimeoutMs
}
}
suspend fun connectNetwork(
networkID: ByteArray,
breadcrumb: ULong?,
timedInvokeTimeoutMs: Int? = null
): ConnectNetworkResponse {
val commandId = 6L
if (timedInvokeTimeoutMs != null) {
// Do the action with timedInvokeTimeoutMs
} else {
// Do the action without timedInvokeTimeoutMs
}
}
suspend fun reorderNetwork(
networkID: ByteArray,
networkIndex: UByte,
breadcrumb: ULong?,
timedInvokeTimeoutMs: Int? = null
): NetworkConfigResponse {
val commandId = 8L
if (timedInvokeTimeoutMs != null) {
// Do the action with timedInvokeTimeoutMs
} else {
// Do the action without timedInvokeTimeoutMs
}
}
suspend fun queryIdentity(
keyIdentifier: ByteArray,
possessionNonce: ByteArray?,
timedInvokeTimeoutMs: Int? = null
): QueryIdentityResponse {
val commandId = 9L
if (timedInvokeTimeoutMs != null) {
// Do the action with timedInvokeTimeoutMs
} else {
// Do the action without timedInvokeTimeoutMs
}
}
suspend fun readMaxNetworksAttribute(): UByte {
// Implementation needs to be added here
}
suspend fun subscribeMaxNetworksAttribute(minInterval: Int, maxInterval: Int): UByte {
// Implementation needs to be added here
}
suspend fun readNetworksAttribute(): NetworksAttribute {
// Implementation needs to be added here
}
suspend fun subscribeNetworksAttribute(minInterval: Int, maxInterval: Int): NetworksAttribute {
// Implementation needs to be added here
}
suspend fun readScanMaxTimeSecondsAttribute(): UByte {
// Implementation needs to be added here
}
suspend fun subscribeScanMaxTimeSecondsAttribute(minInterval: Int, maxInterval: Int): UByte {
// Implementation needs to be added here
}
suspend fun readConnectMaxTimeSecondsAttribute(): UByte {
// Implementation needs to be added here
}
suspend fun subscribeConnectMaxTimeSecondsAttribute(minInterval: Int, maxInterval: Int): UByte {
// Implementation needs to be added here
}
suspend fun readInterfaceEnabledAttribute(): Boolean {
// Implementation needs to be added here
}
suspend fun writeInterfaceEnabledAttribute(value: Boolean, timedWriteTimeoutMs: Int? = null) {
if (timedWriteTimeoutMs != null) {
// Do the action with timedWriteTimeoutMs
} else {
// Do the action without timedWriteTimeoutMs
}
}
suspend fun subscribeInterfaceEnabledAttribute(minInterval: Int, maxInterval: Int): Boolean {
// Implementation needs to be added here
}
suspend fun readLastNetworkingStatusAttribute(): LastNetworkingStatusAttribute {
// Implementation needs to be added here
}
suspend fun subscribeLastNetworkingStatusAttribute(
minInterval: Int,
maxInterval: Int
): LastNetworkingStatusAttribute {
// Implementation needs to be added here
}
suspend fun readLastNetworkIDAttribute(): LastNetworkIDAttribute {
// Implementation needs to be added here
}
suspend fun subscribeLastNetworkIDAttribute(
minInterval: Int,
maxInterval: Int
): LastNetworkIDAttribute {
// Implementation needs to be added here
}
suspend fun readLastConnectErrorValueAttribute(): LastConnectErrorValueAttribute {
// Implementation needs to be added here
}
suspend fun subscribeLastConnectErrorValueAttribute(
minInterval: Int,
maxInterval: Int
): LastConnectErrorValueAttribute {
// Implementation needs to be added here
}
suspend fun readSupportedWiFiBandsAttribute(): SupportedWiFiBandsAttribute {
// Implementation needs to be added here
}
suspend fun subscribeSupportedWiFiBandsAttribute(
minInterval: Int,
maxInterval: Int
): SupportedWiFiBandsAttribute {
// Implementation needs to be added here
}
suspend fun readSupportedThreadFeaturesAttribute(): UShort {
// Implementation needs to be added here
}
suspend fun subscribeSupportedThreadFeaturesAttribute(
minInterval: Int,
maxInterval: Int
): UShort {
// Implementation needs to be added here
}
suspend fun readThreadVersionAttribute(): UShort {
// Implementation needs to be added here
}
suspend fun subscribeThreadVersionAttribute(minInterval: Int, maxInterval: Int): UShort {
// Implementation needs to be added here
}
suspend fun readGeneratedCommandListAttribute(): GeneratedCommandListAttribute {
// Implementation needs to be added here
}
suspend fun subscribeGeneratedCommandListAttribute(
minInterval: Int,
maxInterval: Int
): GeneratedCommandListAttribute {
// Implementation needs to be added here
}
suspend fun readAcceptedCommandListAttribute(): AcceptedCommandListAttribute {
// Implementation needs to be added here
}
suspend fun subscribeAcceptedCommandListAttribute(
minInterval: Int,
maxInterval: Int
): AcceptedCommandListAttribute {
// Implementation needs to be added here
}
suspend fun readEventListAttribute(): EventListAttribute {
// Implementation needs to be added here
}
suspend fun subscribeEventListAttribute(minInterval: Int, maxInterval: Int): EventListAttribute {
// Implementation needs to be added here
}
suspend fun readAttributeListAttribute(): AttributeListAttribute {
// Implementation needs to be added here
}
suspend fun subscribeAttributeListAttribute(
minInterval: Int,
maxInterval: Int
): AttributeListAttribute {
// Implementation needs to be added here
}
suspend fun readFeatureMapAttribute(): UInt {
// Implementation needs to be added here
}
suspend fun subscribeFeatureMapAttribute(minInterval: Int, maxInterval: Int): UInt {
// Implementation needs to be added here
}
suspend fun readClusterRevisionAttribute(): UShort {
// Implementation needs to be added here
}
suspend fun subscribeClusterRevisionAttribute(minInterval: Int, maxInterval: Int): UShort {
// Implementation needs to be added here
}
companion object {
const val CLUSTER_ID: UInt = 49u
}
}
| 1,271 |
C++
|
1709
| 6,518 |
f06d9520d02d68076c5accbf839f168cda89c47c
| 9,682 |
connectedhomeip
|
Apache License 2.0
|
server-api/src/main/kotlin/io/github/oleksivio/tl/kbot/server/api/method/group/GetChatMember.kt
|
oleksivio
| 145,889,451 | false | null |
package io.github.oleksivio.tl.kbot.server.api.method.group
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonProperty
import io.github.oleksivio.tl.kbot.server.api.model.ApiDict
import io.github.oleksivio.tl.kbot.server.api.model.ChatMemberResponse
import io.github.oleksivio.tl.kbot.server.api.model.method.common.ChatAction
import io.github.oleksivio.tl.kbot.server.api.objects.ChatId
import io.github.oleksivio.tl.kbot.server.api.objects.std.ChatMember
/**
* @see [getChatMember](https://core.telegram.org/bots/api/#getchatmember)
*/
data class GetChatMember(
/**
* chat_id Integer or String Yes Unique identifier for the target chat or username of the target channel
*/
@JsonProperty(ApiDict.CHAT_ID_KEY)
override val chatId: ChatId,
/**
* user_id Integer Unique identifier of the target user
*/
@JsonProperty(ApiDict.USER_ID_KEY)
val userId: Long
) : ChatAction<ChatMember>() {
@JsonIgnore
override val resultWrapperClass = ChatMemberResponse::class
@JsonProperty(ApiDict.METHOD_KEY)
override val method = "getChatMember"
}
| 0 | null |
0
| 5 |
d38b5be33c5217a3f91e44394995f112fd6b0ab9
| 1,141 |
tl-kbot
|
Apache License 2.0
|
product-service/src/main/kotlin/br/com/maccommerce/productservice/infrastructure/repository/TransactionCatching.kt
|
wellingtoncosta
| 251,454,379 | false |
{"Text": 1, "Markdown": 4, "Batchfile": 3, "Shell": 3, "Maven POM": 1, "Dockerfile": 3, "Ignore List": 3, "INI": 10, "Java": 34, "SQL": 3, "Gradle Kotlin DSL": 4, "Kotlin": 77, "XML": 2}
|
package br.com.maccommerce.productservice.infrastructure.repository
import br.com.maccommerce.productservice.domain.exception.DatabaseException
import org.jetbrains.exposed.sql.transactions.transaction
fun <T> transactionCatching(block: () -> T) = transaction {
try { block() } catch (t: Throwable) { throw DatabaseException(cause = t) }
}
| 0 |
Kotlin
|
0
| 1 |
f25c2157e5ffe362e405a145e4889b4e9166897d
| 345 |
maccommerce
|
MIT License
|
app/src/main/java/com/mozhimen/study_hilt/MainApplication.kt
|
mozhimen
| 648,284,839 | false | null |
package com.mozhimen.study_hilt
import android.app.Application
import com.mozhimen.basick.elemk.application.bases.BaseApplication
import dagger.hilt.android.HiltAndroidApp
@HiltAndroidApp
class MainApplication : BaseApplication() {
}
| 0 |
Kotlin
|
0
| 0 |
452a7606823c1d9ba62230b01470f351f6b4d0f6
| 235 |
Study_Android_Hilt
|
MIT License
|
app/src/main/java/com/example/m5/util/NotificationReceiver.kt
|
jiushangli
| 690,525,542 | false |
{"Kotlin": 170353, "Java": 6139}
|
package com.example.m5.util
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.m5.MusicApplication
import com.example.m5.R
import com.example.m5.activity.PlayerActivity
import com.example.m5.activity.PlayerActivity.Companion.fIndex
import com.example.m5.data.musicListPA
import com.example.m5.data.songPosition
import com.example.m5.frag.NowPlaying
import com.example.m5.util.PlayMusic.Companion.isPlaying
import com.example.m5.util.PlayMusic.Companion.musicService
class NotificationReceiver : BroadcastReceiver() {
override fun onReceive(content: Context?, intent: Intent?) {
when (intent?.action) {
MusicApplication.PREVIOUS -> preNextSong(increment = false, context = content!!)
MusicApplication.PLAY -> if (isPlaying.value!!) pauseMusic() else playMusic()
MusicApplication.NEXT -> preNextSong(increment = true, context = content!!)
MusicApplication.EXIT -> {
exitApplication()
}
}
}
//根据通知栏里面的点击情况来控制音乐的播放和暂停,改变通知栏的图标以及播放界面的播放图标
private fun playMusic() {
isPlaying.value = true
musicService!!.mediaPlayer!!.start()
}
private fun pauseMusic() {
isPlaying.value = false
musicService!!.mediaPlayer!!.pause()
}
private fun preNextSong(increment: Boolean, context: Context) {
setSongPosition(increment = increment)
playMusic()
fIndex =
favouriteChecker( musicListPA[ songPosition].id.toString())
}
}
| 0 |
Kotlin
|
1
| 1 |
de6195527aa2aa2dff9c8e7a20539e67b446985a
| 1,663 |
Music-player
|
Apache License 2.0
|
Back-end/src/main/kotlin/br/com/imt/dao/GamesDAO.kt
|
Igor-Kubota
| 466,337,130 | true |
{"Dart": 50428, "Kotlin": 41426, "HTML": 3857, "Swift": 404, "Objective-C": 38}
|
package br.com.imt.dao
import br.com.imt.interfaces.IDaoGames
import br.com.imt.models.Games
import br.com.imt.models.Review
import br.com.imt.models.User
import java.sql.DriverManager
class GamesDAO (val connectionString: String): IDaoGames {
override fun insert(obj: Games){
val connection = DriverManager.getConnection(connectionString)
val preparedStatement = connection.prepareStatement("INSERT INTO Games (Name, Summary, Developer, Genre, Score, Img, Release, Consoles) " +
"VALUES (?,?,?,?,?,?,?,?);")
preparedStatement.setString(1, obj.name)
preparedStatement.setString(2, obj.summary)
preparedStatement.setString(3, obj.developer)
preparedStatement.setString(4, obj.genre)
preparedStatement.setInt(5, obj.score)
preparedStatement.setString(6, obj.img)
preparedStatement.setString(7, obj.release)
preparedStatement.setString(8, obj.consoles)
preparedStatement.executeUpdate()
connection.close()
}
override fun update(obj: Games) {
val connection = DriverManager.getConnection(connectionString)
val preparedStatement = connection.prepareStatement("""
UPDATE Games
SET Name = ?, Summary =?, Developer=?, Genre=?, Score=?, Img=?, Release=?, Consoles=?
WHERE Id = ?;
""".trimMargin())
preparedStatement.setString(1, obj.name)
preparedStatement.setString(2, obj.summary)
preparedStatement.setString(3, obj.developer)
preparedStatement.setString(4, obj.genre)
preparedStatement.setInt(5, obj.score)
preparedStatement.setString(6, obj.img)
preparedStatement.setString(7, obj.release)
preparedStatement.setString(8, obj.consoles)
preparedStatement.setInt(9, obj.id)
preparedStatement.executeUpdate()
connection.close()
}
override fun updateImg(filePath: String,id: Int) {
val connection = DriverManager.getConnection(connectionString)
val preparedStatement = connection.prepareStatement("""
UPDATE Games
SET Img=?
WHERE Id = ?;
""".trimMargin())
preparedStatement.setString(1, filePath)
preparedStatement.setInt(2, id)
preparedStatement.executeUpdate()
connection.close()
}
override fun delete(id: Int) {
val connection = DriverManager.getConnection(connectionString)
val preparedStatement = connection.prepareStatement("""
DELETE FROM Games
WHERE id = ?;
""".trimMargin())
preparedStatement?.setInt(1,id)
preparedStatement?.executeUpdate()
connection.close()
}
override fun get(id: Int): Games{
val connection = DriverManager.getConnection(connectionString)
val sqlStatement = connection.createStatement()
val resultSet = sqlStatement.executeQuery("SELECT * FROM Games INNER JOIN Review ON Review.GameId = Games.Id INNER JOIN User ON User.Id = Review.UserId WHERE Games.Id = ${id};")
val game = Games(
resultSet.getInt(1),
resultSet.getString(2),
resultSet.getString(3),
resultSet.getString(4),
resultSet.getString(5),
resultSet.getInt(6),
resultSet.getString(7),
resultSet.getString(8),
resultSet.getString(9)
)
var reviews= mutableListOf<Review>()
while (resultSet.next()){
val user = User(
resultSet.getInt(16),
resultSet.getString(17),
resultSet.getString(18),
resultSet.getString(19),
resultSet.getString(20),
resultSet.getString(21)
)
val review = Review(
resultSet.getInt(10),
resultSet.getInt(11),
resultSet.getInt(12),
resultSet.getString(13),
resultSet.getInt(14),
resultSet.getString(15),
null,
user
)
reviews.add(review)
}
game.reviews = reviews
return game
}
override fun getAll(): List<Games>{
val connection = DriverManager.getConnection(connectionString)
val sqlStatement = connection.createStatement()
val resultSet = sqlStatement.executeQuery("SELECT * FROM Games;")
var games = mutableListOf<Games>()
while (resultSet.next()){
var g = Games(
resultSet.getInt("Id"),
resultSet.getString("Name"),
resultSet.getString("Summary"),
resultSet.getString("Developer"),
resultSet.getString("Genre"),
resultSet.getInt("Score"),
resultSet.getString("Img"),
resultSet.getString("Release"),
resultSet.getString("Consoles"),
)
games.add(g)
}
resultSet.close()
sqlStatement.close()
connection.close()
return games
}
}
| 0 | null |
0
| 0 |
dbc3f01cc147bea7129347aafd0fc443fb65a664
| 5,154 |
reviews-games-project
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.