path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
features/collections/src/main/java/com/ramonpsatu/studyorganizer/features/collections/listeners/ToggleClickListener.kt | ramonpsatu | 678,104,957 | false | null | package com.ramonpsatu.studyorganizer.features.collections.listeners
interface ToggleClickListener {
fun updateToggle(isCompleted: Int, itemId: String, adapterPosition: Int)
} | 0 | Kotlin | 0 | 0 | b2f41b28aec9444c2970f32950fed5f2b78d79bc | 183 | Study-Organizer | MIT License |
src/test/kotlin/nl/dirkgroot/structurizr/dsl/lexer/MeaningfulLineTerminatorsTest.kt | dirkgroot | 561,786,663 | false | {"Kotlin": 75934, "Lex": 2535, "ASL": 463} | package nl.dirkgroot.structurizr.dsl.lexer
import com.intellij.psi.TokenType.WHITE_SPACE
import io.kotest.matchers.collections.shouldContainExactly
import nl.dirkgroot.structurizr.dsl.psi.SDTypes.*
import nl.dirkgroot.structurizr.dsl.support.tokenize
import org.junit.Test
class MeaningfulLineTerminatorsTest {
@Test
fun `carriage return`() {
"description text\r".tokenize() shouldContainExactly listOf(
UNQUOTED_TEXT to "description",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "text",
CRLF to "\r"
)
}
@Test
fun `line feed`() {
"description text\n".tokenize() shouldContainExactly listOf(
UNQUOTED_TEXT to "description",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "text",
CRLF to "\n"
)
}
@Test
fun `carriage return + line feed`() {
"description text\r\n".tokenize() shouldContainExactly listOf(
UNQUOTED_TEXT to "description",
WHITE_SPACE to (" "),
UNQUOTED_TEXT to "text",
CRLF to "\r\n"
)
}
}
| 11 | Kotlin | 3 | 54 | 9bcbcfab6c1e7ef8258dc7c21f049e555b119237 | 1,118 | structurizr-dsl-intellij-plugin | MIT License |
kotlin/goi/src/main/kotlin/net/paploo/goi/pipeline/core/Pipeline.kt | paploo | 526,415,165 | false | {"Kotlin": 551045, "Ruby": 153592, "Java": 50625, "ANTLR": 2824, "CSS": 1961, "PLpgSQL": 274} | package net.paploo.goi.pipeline.core
import kotlinx.coroutines.Dispatchers
import net.paploo.goi.common.extensions.flatMap
import net.paploo.goi.common.extensions.parallelMap
import net.paploo.goi.common.extensions.sequenceToResult
import net.paploo.goi.common.util.TimerLog
import org.slf4j.Logger
import org.slf4j.LoggerFactory
interface Pipeline<out T> : suspend () -> Result<T>
abstract class BasePipeline<T> : Pipeline<T> {
private val logger: Logger = LoggerFactory.getLogger(this::class.java)
abstract val importer: Importer<T>
abstract val transformers: Collection<Transformer<T>>
abstract val exporters: Collection<Exporter<T>>
override suspend fun invoke(): Result<T> =
Result.success(
Context(TimerLog("Pipeline") { logger.info(it.formatted()) })
).flatMap { context ->
context.timerLog.markAround("Execute Pipeline") {
context.timerLog.mark("# START IMPORT PHASE")
import(context).flatMap {
context.timerLog.mark("# START TRANSFORM PHASE")
transform(it, context)
}.flatMap {
context.timerLog.mark("# START EXPORT PHASE")
export(it, context)
}.map {
context.timerLog.mark("# END PIPELINE")
it
}
}.also {
logger.info(context.timerLog.formatted())
}
}
private suspend fun import(context: Context): Result<T> =
context.timerLog.markAround("Import with ${importer::class.simpleName}") {
importer(context)
}
private suspend fun transform(value: T, context: Context): Result<T> =
transformers.fold(Result.success(value)) { valueResult, transformer ->
context.timerLog.markAround("Transform with ${transformer::class.simpleName}") {
valueResult.flatMap { transformer(it, context) }
}
}
private suspend fun export(value: T, context: Context): Result<T> =
exporters.parallelMap(Dispatchers.IO) { exporter ->
context.timerLog.markAround("Export with ${exporter::class.simpleName}") {
exporter(value, context)
}
}.also {
logger.info("EXPORT: $it")
}.sequenceToResult().map { value }
}
| 3 | Kotlin | 0 | 0 | ad2bd1917379e47e5cd12347157383c9ed3d19e7 | 2,377 | goi | MIT License |
src/main/kotlin/org/jmailen/gradle/kotlinter/tasks/ConfigurableKtLintTask.kt | dinomite | 252,217,909 | true | {"Kotlin": 89594} | package org.jmailen.gradle.kotlinter.tasks
import java.io.File
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.SourceTask
import org.jmailen.gradle.kotlinter.KotlinterExtension.Companion.DEFAULT_DISABLED_RULES
import org.jmailen.gradle.kotlinter.KotlinterExtension.Companion.DEFAULT_EXPERIMENTAL_RULES
import org.jmailen.gradle.kotlinter.KotlinterExtension.Companion.DEFAULT_FILE_BATCH_SIZE
import org.jmailen.gradle.kotlinter.support.KtLintParams
abstract class ConfigurableKtLintTask : SourceTask() {
@Input
val fileBatchSize = property(default = DEFAULT_FILE_BATCH_SIZE)
@Input
@Optional
val indentSize = property<Int?>(default = null)
@Internal
@Deprecated("Scheduled to be removed in 3.0.0")
var continuationIndentSize: Int? = null
set(value) {
field = value
logger.warn("`continuationIndentSize` does not have any effect and will be removed in 3.0.0")
}
@Input
val experimentalRules = property(default = DEFAULT_EXPERIMENTAL_RULES)
@Input
val disabledRules = listProperty(default = DEFAULT_DISABLED_RULES.toList())
@Optional
@InputFile
@PathSensitive(PathSensitivity.RELATIVE)
val editorConfigPath = project.objects.fileProperty()
@Internal
protected fun getKtLintParams() = KtLintParams(
indentSize = indentSize.orNull,
experimentalRules = experimentalRules.get(),
disabledRules = disabledRules.get(),
editorConfigPath = editorConfigPath.asFile.orNull?.path
)
@Internal
protected fun getChunkedSource(): List<List<File>> =
source.chunked(fileBatchSize.get())
}
internal inline fun <reified T> DefaultTask.property(default: T? = null) =
project.objects.property(T::class.java).apply {
set(default)
}
internal inline fun <reified T> DefaultTask.listProperty(default: Iterable<T> = emptyList()) =
project.objects.listProperty(T::class.java).apply {
set(default)
}
internal inline fun <reified K, reified V> DefaultTask.mapProperty(default: Map<K, V> = emptyMap()) =
project.objects.mapProperty(K::class.java, V::class.java).apply {
set(default)
}
| 0 | Kotlin | 0 | 0 | d59f5a7f1c07169ce90192096be4410632703052 | 2,419 | kotlinter-gradle | Apache License 2.0 |
app/src/main/java/com/g/pocketmal/data/database/dao/UserDao.kt | glodanif | 847,288,195 | false | {"Kotlin": 517413, "Java": 112995} | package com.g.pocketmal.data.database.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.g.pocketmal.data.database.model.UserProfileTable
@Dao
interface UserDao {
@Query("SELECT * FROM user_profile WHERE id = :id")
suspend fun getUserById(id: Int): UserProfileTable
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(user: UserProfileTable)
}
| 0 | Kotlin | 1 | 8 | 1a7fe52c2dc59dd3bf4eaeb3d9bb64d469e10845 | 464 | Pocket_MAL | MIT License |
app/src/main/java/co/temy/android/ktx/ActivityExtensions.kt | temyco | 241,076,714 | false | null | package co.temy.android.ktx
import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.DisplayMetrics
fun Activity.getDisplayWidth(): Int {
val displayMetrics: DisplayMetrics = DisplayMetrics()
this.windowManager.defaultDisplay.getMetrics(displayMetrics)
return displayMetrics.widthPixels
}
fun Activity.enablePortraitScreenOrientationForMobile(isPortrait: Boolean) {
if (!isTabletConfig()) {
if (isPortrait) requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
else requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR
}
}
fun Activity.lockScreenOrientationChanges(lock: Boolean) {
requestedOrientation = if (lock) ActivityInfo.SCREEN_ORIENTATION_LOCKED else ActivityInfo.SCREEN_ORIENTATION_SENSOR
}
fun Activity.openEmailClient(emailTo: String, subject: String) {
val uriString = "mailto:$emailTo?subject=$subject"
val emailIntent = Intent(Intent.ACTION_SENDTO)
emailIntent.data = Uri.parse(uriString)
if (emailIntent.resolveActivity(packageManager) != null) {
startActivity(emailIntent)
} else {
startActivity(Intent.createChooser(emailIntent, null))
}
}
fun Activity.openNotificationSettings() {
val intent = Intent()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
intent.action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
intent.putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
intent.action = Settings.ACTION_APP_NOTIFICATION_SETTINGS
intent.putExtra("app_package", packageName)
intent.putExtra("app_uid", applicationInfo.uid)
} else {
intent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
intent.addCategory(Intent.CATEGORY_DEFAULT)
intent.data = Uri.parse("package:$packageName")
}
startActivity(intent)
}
/**
* Starting from appcompat v.1.1.0 system overrides baseContext after [attachBaseContext]
* causing resetting locale settings. To prevent this we must call [applyOverrideConfiguration]
* with modified [overrideConfiguration] object.
*
* That's a workaround until this behaviour will be fixed in future appcompat releases.
*/
fun Activity.setupOverrideConfiguration(overrideConfiguration: Configuration?): Configuration? {
if (overrideConfiguration != null) {
val uiMode = overrideConfiguration.uiMode
overrideConfiguration.setTo(baseContext.resources.configuration)
overrideConfiguration.uiMode = uiMode
}
return overrideConfiguration
}
/**
* Navigates to the current Google user's account
* subscriptions in Google Play app.
*/
fun Activity.openGooglePlaySubscriptions() {
val uriString = "https://play.google.com/store/account/subscriptions"
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uriString))
startActivity(intent)
} | 5 | Kotlin | 0 | 4 | 30723fe0b814134a2f4d08d85e601f57f1579d05 | 3,065 | android-ktx | Apache License 2.0 |
app/src/main/java/guideme/volunteers/ui/fragments/volunteer/details/project/ProjectDetailsPresenter.kt | mniami | 79,149,480 | false | {"Kotlin": 138804, "Java": 16817, "Shell": 349} | package guideme.volunteers.ui.fragments.volunteer.details.project
import guideme.volunteers.domain.Project
import guideme.volunteers.ui.fragments.base.BasicPresenter
class ProjectDetailsPresenter(val fragment: IProjectDetailsFragment) : BasicPresenter() {
var project: Project? = null
} | 0 | Kotlin | 0 | 1 | ec79ba258d26206d8cd2ee7eb8ebcdc94696be5f | 292 | volunteers | Apache License 2.0 |
codebase/android/core-database/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/core/database/usecase/DeleteTransactionAndRevertOtherDataUseCase.kt | Abhimanyu14 | 429,663,688 | false | null | package com.makeappssimple.abhimanyu.financemanager.android.core.database.usecase
import com.makeappssimple.abhimanyu.financemanager.android.core.database.source.model.Source
import com.makeappssimple.abhimanyu.financemanager.android.core.database.source.model.updateBalanceAmount
import com.makeappssimple.abhimanyu.financemanager.android.core.database.transaction.usecase.DeleteTransactionUseCase
import com.makeappssimple.abhimanyu.financemanager.android.core.database.transaction.usecase.GetTransactionDataUseCase
import com.makeappssimple.abhimanyu.financemanager.android.core.datastore.MyDataStore
interface DeleteTransactionAndRevertOtherDataUseCase {
suspend operator fun invoke(
id: Int,
)
}
class DeleteTransactionAndRevertOtherDataUseCaseImpl(
private val dataStore: MyDataStore,
private val deleteTransactionUseCase: DeleteTransactionUseCase,
private val getTransactionDataUseCase: GetTransactionDataUseCase,
) : DeleteTransactionAndRevertOtherDataUseCase {
override suspend operator fun invoke(
id: Int,
) {
dataStore.updateLastDataChangeTimestamp()
val transactionData = getTransactionDataUseCase(
id = id,
) ?: return
val updatesSources = mutableListOf<Source>()
transactionData.sourceFrom?.let {
updatesSources.add(
it.updateBalanceAmount(
updatedBalanceAmount = it.balanceAmount.value + transactionData.transaction.amount.value,
)
)
}
transactionData.sourceTo?.let {
updatesSources.add(
it.updateBalanceAmount(
updatedBalanceAmount = it.balanceAmount.value - transactionData.transaction.amount.value,
)
)
}
deleteTransactionUseCase(
id = id,
sources = updatesSources.toTypedArray(),
)
}
}
| 0 | Kotlin | 0 | 0 | 29afaec0cf4e95ba4d6c0dcc32cba3fea6a088cb | 1,925 | finance-manager | Apache License 2.0 |
core/src/test/java/com/alibaba/fastjson2/issues_1900/Issue2069.kt | alibaba | 482,425,877 | false | null | package com.alibaba.fastjson2.issues_1900
import com.alibaba.fastjson2.JSON
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
class Issue2069 {
data class User(
val id: Long?,
val username: String?,
val isTrue: String?,
val isMain: Int?,
val isBoolean: Boolean?
) {
var isNormal: String? = null
override fun toString(): String {
return "User(id=$id, username=$username, isTrue=$isTrue, isMain=$isMain, isBoolean=$isBoolean, isNormal=$isNormal)"
}
}
@Test
fun test() {
val user = User(1, "lili", "是", 1, true)
user.isNormal = "否"
var jsonStr = JSON.toJSONString(user)
jsonStr = "{\"id\":1,\"username\":\"lili\",\"isTrue\":\"是\",\"isMain\":1,\"isBoolean\": true,\"isNormal\":\"否\"}"
val parseObject = JSON.parseObject(jsonStr, User::class.java)
assertEquals(parseObject.id, parseObject.id);
assertEquals(parseObject.username, parseObject.username);
assertEquals(parseObject.isMain, parseObject.isMain);
assertEquals(parseObject.isBoolean, parseObject.isBoolean);
assertEquals(parseObject.isTrue, parseObject.isTrue);
assertEquals(parseObject.isNormal, parseObject.isNormal);
}
}
| 458 | null | 485 | 3,746 | 2b0efeee501f9fc6ab215910a51491edfe43784e | 1,306 | fastjson2 | Apache License 2.0 |
aTalk/src/main/java/org/atalk/hmos/gui/util/XhtmlImageParser.kt | cmeng-git | 704,328,019 | false | {"Kotlin": 14462775, "Java": 2824517, "C": 275021, "Shell": 49203, "Makefile": 28273, "C++": 13642, "HTML": 7793, "CSS": 3127, "JavaScript": 2758, "AIDL": 375} | /*
* aTalk, android VoIP and Instant Messaging client
* Copyright 2014 <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 org.atalk.hmos.gui.util
import android.graphics.drawable.Drawable
import android.os.AsyncTask
import android.text.Html
import android.text.Html.ImageGetter
import android.text.method.LinkMovementMethod
import android.widget.*
import java.io.IOException
import java.net.URL
/**
* Utility class that implements `Html.ImageGetter` interface and can be used
* to display url images in `TextView` through the HTML syntax.
*
* @author <NAME>
*/
class XhtmlImageParser
/**
* Construct the XhtmlImageParser which will execute AsyncTask and refresh the TextView
* Usage: htmlTextView.setText(Html.fromHtml(HtmlString, new XhtmlImageParser(htmlTextView, HtmlString), null));
*
* @param tv the textView to be populated with return result
* @param str the xhtml string
*/
(private val mTextView: TextView, private val XhtmlString: String) : ImageGetter {
/**
* {@inheritDoc}
*/
override fun getDrawable(source: String): Drawable? {
val httpGetDrawableTask = HttpGetDrawableTask()
httpGetDrawableTask.execute(source)
return null
}
/**
* Execute fetch url image as async task: else 'android.os.NetworkOnMainThreadException'
*/
inner class HttpGetDrawableTask : AsyncTask<String?, Void?, Drawable?>() {
override fun doInBackground(vararg params: String?): Drawable? {
val source = params[0]!!
return getDrawable(source)
}
override fun onPostExecute(result: Drawable?) {
if (result != null) {
mTextView.text = Html.fromHtml(XhtmlString, { source: String? -> result }, null)
} else {
mTextView.text = Html.fromHtml(XhtmlString, null, null)
}
mTextView.movementMethod = LinkMovementMethod.getInstance()
}
/***
* Get the Drawable from the given URL (change to secure https if necessary)
* aTalk/android supports only secure https connection
*
* @param urlString url string
* @return drawable
*/
fun getDrawable(urlString: String): Drawable? {
var urlString = urlString
return try {
// urlString = "https://cmeng-git.github.io/atalk/img/09.atalk_avatar.png";
urlString = urlString.replace("http:", "https:")
val sourceURL = URL(urlString)
val urlConnection = sourceURL.openConnection()
urlConnection.connect()
val inputStream = urlConnection.getInputStream()
val drawable = Drawable.createFromStream(inputStream, "src")
drawable?.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
drawable
} catch (e: IOException) {
null
}
}
}
} | 0 | Kotlin | 0 | 0 | 393d94a8b14913b718800238838801ce6cdf5a1f | 3,477 | atalk-hmos_kotlin | Apache License 2.0 |
app/src/main/java/mse/mobop/mymoviesbucketlists/ui/recyclerview/adapters/MoviesPaginationAdapter.kt | RaedAbr | 221,748,823 | false | {"Kotlin": 130757} | package mse.mobop.mymoviesbucketlists.ui.recyclerview.adapters
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade
import com.bumptech.glide.request.RequestListener
import kotlinx.android.synthetic.main.dialog_movie_poster.view.*
import kotlinx.android.synthetic.main.item_list_movie.view.*
import mse.mobop.mymoviesbucketlists.R
import mse.mobop.mymoviesbucketlists.model.Movie
import mse.mobop.mymoviesbucketlists.utils.BASE_URL_IMG
import mse.mobop.mymoviesbucketlists.utils.BASE_URL_IMG_POSTER
import mse.mobop.mymoviesbucketlists.utils.getAttributeDrawable
@SuppressLint("DefaultLocale", "InflateParams", "SetTextI18n")
class MoviesPaginationAdapter(
private val context: Context
) : ListAdapter<Movie, RecyclerView.ViewHolder>(DIFF_CALLBACK) {
companion object {
private const val ITEM = 0
private const val LOADING = 1
private val DIFF_CALLBACK = object: DiffUtil.ItemCallback<Movie>() {
override fun areItemsTheSame(oldItem: Movie, newItem: Movie): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Movie, newItem: Movie): Boolean {
return oldItem == newItem
}
}
}
private var lastClickedMoviePosition: Int = -1
private var itemListener: ItemListener? = null
fun setOnItemLongClickListener(itemListener: ItemListener) {
this.itemListener = itemListener
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): RecyclerView.ViewHolder {
val viewHolder: RecyclerView.ViewHolder
val inflater = LayoutInflater.from(parent.context)
viewHolder = when (viewType) {
ITEM -> MovieVH(inflater.inflate(R.layout.item_list_movie, parent, false))
// else it's a loading bar
else -> LoadingVH(inflater.inflate(R.layout.item_progress, parent, false))
}
return viewHolder
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val movie: Movie = getItem(position)
when (getItemViewType(position)) {
ITEM -> {
val movieVH = holder as MovieVH
movieVH.bind(movie)
}
LOADING -> { }
}
}
override fun getItemViewType(position: Int): Int {
return if (getItem(position).isLoadingItem)
LOADING
else
ITEM
}
/**
* Main list's content ViewHolder
*/
private inner class MovieVH(private val movieItemView: View): RecyclerView.ViewHolder(movieItemView) {
private val mMovieTitle: TextView = movieItemView.movie_title
private val mMovieDesc: TextView = movieItemView.movie_desc
private val mYear: TextView = movieItemView.movie_year // displays "year | language"
internal val mPosterImg: ImageView = movieItemView.movie_poster
internal val mProgress: ProgressBar = movieItemView.movie_progress
internal val mNoPoster: TextView = movieItemView.movie_no_poster
fun bind(movie: Movie) {
mMovieTitle.text = movie.title
mYear.text = movie.originalLanguage!!.toUpperCase() + " | " + movie.releaseDate
mMovieDesc.text = movie.overview!!
movieItemView.movie_selected_checkbox.isChecked = movie.isSelected
if (movie.isSelected) {
movieItemView.background = context.getDrawable(R.drawable.background_movie_selected)
} else {
movieItemView.background = getAttributeDrawable(context, R.attr.colorCardBackground)
}
if (movie.isExpanded) {
mMovieDesc.ellipsize = null
mMovieDesc.maxLines = Int.MAX_VALUE
mMovieTitle.ellipsize = null
mMovieTitle.maxLines = Int.MAX_VALUE
} else {
mMovieDesc.maxLines = 3
mMovieDesc.ellipsize = TextUtils.TruncateAt.END
mMovieTitle.maxLines = 1
mMovieTitle.ellipsize = TextUtils.TruncateAt.END
}
Glide
.with(movieItemView.context)
.load(BASE_URL_IMG + movie.posterPath)
.listener(object : RequestListener<Drawable> {
override fun onResourceReady(
resource: Drawable?,
model: Any?,
target: com.bumptech.glide.request.target.Target<Drawable>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean { // image ready, hide progress now
mProgress.visibility = View.GONE
mPosterImg.setOnClickListener(showDialogPoster(movie))
Log.e("onResourceReady", model.toString())
return false // return false if you want Glide to handle everything else.
}
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: com.bumptech.glide.request.target.Target<Drawable>?,
isFirstResource: Boolean
): Boolean {
mProgress.visibility = View.GONE
mNoPoster.visibility = View.VISIBLE
mPosterImg.setOnClickListener(null)
Log.e("onLoadFailed", model.toString())
Log.e("onLoadFailed", "id: ${movie.id}\ttitle: ${movie.title}")
return false
}
})
.diskCacheStrategy(DiskCacheStrategy.ALL) // cache both original & resized image
.centerCrop()
.transition(withCrossFade())
.into(mPosterImg)
movieItemView.movie_linear_layout.setOnClickListener {
if (lastClickedMoviePosition != -1 &&
lastClickedMoviePosition != adapterPosition &&
getItem(lastClickedMoviePosition).isExpanded) {
getItem(lastClickedMoviePosition).isExpanded = false
}
getItem(adapterPosition).isExpanded = !getItem(adapterPosition).isExpanded
lastClickedMoviePosition = adapterPosition
notifyDataSetChanged()
}
if (itemListener != null) {
movieItemView.movie_linear_layout.setOnLongClickListener {
itemListener!!.onItemLongClick(adapterPosition)
true
}
// Show trailer Dialog
mPosterImg.setOnLongClickListener {
itemListener!!.onPosterLongClick(movie.id!!)
true
}
}
}
private fun showDialogPoster(movie: Movie): View.OnClickListener? {
return View.OnClickListener {
val builder = AlertDialog.Builder(context)
val inflater: LayoutInflater = (context as AppCompatActivity).layoutInflater
val dialogLayout: View = inflater.inflate(R.layout.dialog_movie_poster, null)
val dialog = builder.create()
dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dialog.setView(dialogLayout)
dialog.setOnShowListener {
Glide
.with(context)
.load(BASE_URL_IMG_POSTER + movie.posterPath)
.listener(object : RequestListener<Drawable> {
override fun onResourceReady(
resource: Drawable?,
model: Any?,
target: com.bumptech.glide.request.target.Target<Drawable>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean { // image ready, hide progress now
dialogLayout.poster_progress.visibility = View.GONE
return false // return false if you want Glide to handle everything else.
}
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: com.bumptech.glide.request.target.Target<Drawable>?,
isFirstResource: Boolean
): Boolean {
Log.e("onLoadFailedddd", model.toString())
Log.e("onLoadFailedddd", "id: ${movie.id}\ttitle: ${movie.title}")
return false
}
})
.diskCacheStrategy(DiskCacheStrategy.ALL) // cache both original & resized image
.fitCenter()
.transition(withCrossFade())
.into(dialogLayout.movie_poster_image)
}
dialogLayout.setOnClickListener {
dialog.dismiss()
}
dialog.show()
}
}
}
private inner class LoadingVH(itemView: View?) :
RecyclerView.ViewHolder(itemView!!)
interface ItemListener {
fun onItemLongClick(position: Int)
fun onPosterLongClick(movieId: Int)
}
} | 0 | Kotlin | 0 | 0 | b3bfcfef5163d2b94f465893737ae8fd7b701de4 | 10,547 | my-movies-bucket-lists | MIT License |
demo-kotlin/src/main/java/me/yokeyword/sample/zhihu/ui/fragment/third/child/child/ContentFragment.kt | qdsfdhvh | 166,903,972 | true | {"Gradle": 10, "Markdown": 7, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 7, "Batchfile": 1, "YAML": 1, "Proguard": 5, "XML": 77, "Kotlin": 86, "INI": 4, "Java": 52} | package me.yokeyword.sample.zhihu.ui.fragment.third.child.child
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import me.yokeyword.fragmentation.SupportFragment
import me.yokeyword.fragmentation.anim.FragmentAnimator
import me.yokeyword.fragmentation.parentStart
import me.yokeyword.sample.R
import me.yokeyword.sample.zhihu.ui.fragment.CycleFragment
/**
* Created by YoKeyword on 16/2/9.
*/
class ContentFragment : SupportFragment() {
private var mTvContent: TextView? = null
private var mBtnNext: Button? = null
private var mMenu: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val args = arguments
if (args != null) {
mMenu = args.getString(ARG_MENU)
}
}
override fun onCreateFragmentAnimator(): FragmentAnimator {
return FragmentAnimator.noAnimator()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_content, container, false)
initView(view)
return view
}
@SuppressLint("SetTextI18n")
private fun initView(view: View) {
mTvContent = view.findViewById<View>(R.id.tv_content) as TextView
mBtnNext = view.findViewById<View>(R.id.btn_next) as Button
mTvContent!!.text = "Content:\n" + mMenu!!
mBtnNext!!.setOnClickListener {
// 和MsgFragment同级别的跳转 交给MsgFragment处理
parentStart(CycleFragment.newInstance(1))
}
}
override fun onBackPressedSupport(): Boolean {
// ContentFragment是ShopFragment的栈顶子Fragment,可以在此处理返回按键事件
return super.onBackPressedSupport()
}
companion object {
private val ARG_MENU = "arg_menu"
fun newInstance(menu: String): ContentFragment {
val args = Bundle()
args.putString(ARG_MENU, menu)
val fragment = ContentFragment()
fragment.arguments = args
return fragment
}
}
}
| 0 | Java | 0 | 0 | 3ddb2fe6ee7f8519e78ef0a5806bd217329ed023 | 2,243 | Fragmentation | Apache License 2.0 |
bundle/base/apps/demo/server/services/samples/kotlin/query-interaction.kts | netuno-org | 392,833,670 | false | {"JavaScript": 44861543, "Java": 4776673, "HTML": 2778101, "CSS": 1516576, "SCSS": 780640, "TypeScript": 342186, "Less": 329678, "CoffeeScript": 162930, "Sass": 148557, "PHP": 51440, "Handlebars": 47094, "Kotlin": 28079, "Python": 25431, "Groovy": 22872, "Ruby": 22085, "ActionScript": 16386, "Shell": 15503, "PowerShell": 13617, "Twig": 3998, "Batchfile": 2368, "Dockerfile": 2322, "EJS": 820, "Makefile": 285, "Harbour": 168, "Mustache": 90} |
/**
*
* EN: EXECUTE A QUERY WITH PARAMETER AND INTERACTION TO RESULT AS JSON
*
* PT: EXECUTA UMA QUERY COM PARÂMETROS E INTERAGE PARA RESULTAR COMO JSON
*
*/
var tableName = "worker"
var columnName = "name"
if (_db.config().getString("name") == "demo_pt") {
tableName = "trabalhador"
columnName = "nome"
}
val rows = _db.query(
"""SELECT *
FROM $tableName
WHERE id > ?::int AND active = true
ORDER BY $columnName""",
_req.getInt("id")
)
val list = _val.list()
rows.forEach {
list.add(
_val.map()
.set("id", it.getInt("id"))
.set("name", it.getString(columnName))
)
}
_out.json(list)
| 4 | JavaScript | 3 | 26 | d4b2bc61fd2d08c3537ae1c992e9e41c43b050c5 | 632 | platform | Apache License 2.0 |
app/src/main/java/com/umairadil/androidjetpack/ui/movies/dialog/MovieFilterDialog.kt | umair13adil | 139,688,287 | false | null | package com.umairadil.androidjetpack.ui.movies.dialog
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.app.AlertDialog
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import com.michaelflisar.rxbus2.RxBus
import com.umairadil.androidjetpack.R
import com.umairadil.androidjetpack.data.local.MovieGenre
import com.umairadil.androidjetpack.data.local.RealmHelper
import com.umairadil.androidjetpack.models.rxbus.FilterOptions
import com.umairadil.androidjetpack.utils.Constants
import com.umairadil.androidjetpack.utils.Preferences
import com.umairadil.androidjetpack.utils.Utils
import dagger.android.support.AndroidSupportInjection
import io.realm.Realm
import kotlinx.android.synthetic.main.dialog_movie_filter.view.*
import java.util.*
import javax.inject.Inject
class MovieFilterDialog : DialogFragment() {
@Inject
lateinit var db: RealmHelper
//Filter Items
var year: Int = 0
var sortBy: String = ""
var genre: Int = 18
override fun onAttach(context: Context) {
super.onAttach(context)
//Dagger
AndroidSupportInjection.inject(this)
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(activity!!).setCancelable(false)
val view = activity?.layoutInflater?.inflate(R.layout.dialog_movie_filter, null)
//Set year options
setYearsSpinner(view)
//Set sortBy options
setSortSpinner(view)
//Set genre options
setGenreSpinner(view)
view?.btn_apply?.setOnClickListener {
//Save Filter Options
Preferences.getInstance().save(activity!!, Constants.PREF_GENRE, genre)
Preferences.getInstance().save(activity!!, Constants.PREF_YEAR, year)
RxBus.get().withSendToDefaultBus().send(FilterOptions(year, sortBy, genre))
dismiss()
}
builder.setView(view)
return builder.create()
}
private fun setYearsSpinner(view: View?) {
val list = ArrayList<Int>()
val thisYear = Calendar.getInstance().get(Calendar.YEAR)
for (i in 1950..thisYear) {
list.add(i)
}
val adapter = ArrayAdapter<Int>(activity, android.R.layout.simple_spinner_item, list)
view?.spinner_year?.adapter = adapter
//Get Saved filter value
val saved = Preferences.getInstance().getInt(activity!!, Constants.PREF_YEAR, thisYear)
val index = list.binarySearch(saved)
view?.spinner_year?.setSelection(index)
view?.spinner_year?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(p0: AdapterView<*>?) {
year = saved
}
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
year = list.get(p2)
}
}
}
private fun setSortSpinner(view: View?) {
val list = resources.getStringArray(R.array.array_sort_by)
val sortByList = arrayListOf<String>()
val seperatedList = arrayListOf<String>()
for (item in list) {
val separated = Utils.getInstance().getSeparatedValues(item, ":")
sortByList.add(separated.get(0)) //Sort By Name
seperatedList.add(separated.get(0)) //Sort By Key
}
//Get Saved filter value
val saved = Preferences.getInstance().getString(activity!!, Constants.PREF_SORT)
val index = seperatedList.binarySearch { String.CASE_INSENSITIVE_ORDER.compare(it, saved) }
val adapter = ArrayAdapter<String>(activity, android.R.layout.simple_spinner_item, sortByList)
view?.spinner_sort_by?.adapter = adapter
view?.spinner_sort_by?.setSelection(index)
view?.spinner_sort_by?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(p0: AdapterView<*>?) {
val separated = Utils.getInstance().getSeparatedValues(list.first(), ":")
Preferences.getInstance().save(activity!!, Constants.PREF_SORT, separated.get(0))
sortBy = separated.get(1)
}
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
val separated = Utils.getInstance().getSeparatedValues(list.get(p2), ":")
Preferences.getInstance().save(activity!!, Constants.PREF_SORT, separated.get(0))
sortBy = separated.get(1)
}
}
}
private fun setGenreSpinner(view: View?) {
val list = Realm.getDefaultInstance().copyFromRealm(db.findAll(MovieGenre().javaClass)).sortedBy { it.id }
if (list.isEmpty())
return
val names = ArrayList<String>()
for (genre in list) {
names.add(genre.name!!)
}
//Get Saved filter value
val saved = Preferences.getInstance().getInt(activity!!, Constants.PREF_GENRE, genre)
val index = list.binarySearch { String.CASE_INSENSITIVE_ORDER.compare(it.id.toString(), saved.toString()) }
val adapter = ArrayAdapter<String>(activity, android.R.layout.simple_spinner_item, names)
view?.spinner_genre?.adapter = adapter
view?.spinner_genre?.setSelection(index)
view?.spinner_genre?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(p0: AdapterView<*>?) {
genre = saved
}
override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
genre = list.get(p2).id!!
}
}
}
} | 0 | Kotlin | 4 | 11 | 2cf74f50df7329c33cda543a84540c97860c4452 | 5,846 | AndroidJetpackTemplate | The Unlicense |
app/src/main/java/com/fakhir/mobile/fooddelivery/screen/LoginScreen.kt | fakhirsh | 579,318,697 | false | null | package com.fakhir.mobile.fooddelivery
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.fakhir.mobile.fooddelivery.model.AppViewModel
import com.fakhir.mobile.fooddelivery.model.User
import com.fakhir.mobile.fooddelivery.ui.theme.FoodDeliveryComposeTheme
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
@Composable
fun LoginScreen(navController: NavController?=null, viewModel: AppViewModel?=null) {
var email by remember { mutableStateOf("") }
var password by remember { mutableStateOf("") }
val state by viewModel?.appState!!.collectAsState()
FoodDeliveryComposeTheme{
Column(
modifier = Modifier.fillMaxSize(),
) {
Image(
painter = painterResource(R.drawable.chinese_food_banner),
contentDescription = null,
modifier = Modifier
.fillMaxWidth()
.height(150.dp),
contentScale = ContentScale.Crop
)
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Image(
painter = painterResource(R.drawable.panda),
contentDescription = null,
modifier = Modifier
.wrapContentSize(align = Alignment.Center)
.height(150.dp)
)
Spacer(modifier = Modifier.height(35.dp))
OutlinedTextField(
value = email,
onValueChange = {
email = it
},
label = { Text(text = "Email") },
)
OutlinedTextField(
value = password,
onValueChange = {
password = it
},
label = { Text("Password") },
visualTransformation = PasswordVisualTransformation()
)
Button(
onClick = {
Log.d("TAG", "Login Button Clicked")
var auth = Firebase.auth
val currentUser = auth.currentUser
Log.d("TAG", "Current User: ${currentUser}")
auth?.signInWithEmailAndPassword(email, password)
?.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d("TAG", "Login Successful")
var user:User = User()
user.name = currentUser!!.displayName.toString()
user.email = currentUser!!.email.toString()
viewModel?.setUser(user)
navController?.navigate("home")
} else {
Log.d("TAG", "Login Failed" + task.exception)
}
}
},
modifier = Modifier.padding(16.dp)
) {
Text(text = "Log in")
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 47f1c0f90741e73d6de364dd5f59b218595352fb | 4,024 | FoodDeliveryCompose | MIT License |
android/app/src/main/kotlin/com/oguzkaba/flutter_firebase_crud/MainActivity.kt | oguzkaba | 456,688,990 | false | {"Dart": 25751, "HTML": 3954, "Swift": 404, "Kotlin": 139, "Objective-C": 38} | package com.oguzkaba.flutter_firebase_crud
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | Dart | 0 | 0 | 961f4a21af38776a33328492a8060634ba72c420 | 139 | flutter_firebase_crud | Apache License 2.0 |
app/src/main/java/com/routinely/routinely/data/auth/model/RegisterRequest.kt | RoutinelyOrganization | 609,263,361 | false | {"Kotlin": 276295} | package com.routinely.routinely.data.auth.model
import kotlinx.serialization.Serializable
@Serializable
data class RegisterRequest(
val name: String,
val email: String,
val password: String,
val acceptedTerms: Boolean,
)
| 26 | Kotlin | 3 | 3 | e5520e68d574c3d6a58ed626b652dc902801192b | 239 | routinely-mobile | MIT License |
oauth/src/main/java/jp/co/soramitsu/oauth/base/sdk/ContractData.kt | sora-xor | 610,919,196 | false | {"Kotlin": 321971} | package jp.co.soramitsu.oauth.base.sdk
import android.os.Parcelable
import com.paywings.oauth.android.sdk.data.enums.EnvironmentType
import jp.co.soramitsu.oauth.common.model.KycStatus
import kotlinx.parcelize.Parcelize
@Parcelize
data class SoraCardKycCredentials(
val endpointUrl: String,
val username: String,
val password: String
) : Parcelable
@Parcelize
enum class SoraCardEnvironmentType : Parcelable {
NOT_DEFINED,
TEST,
PRODUCTION
}
@Parcelize
data class SoraCardInfo(
val accessToken: String,
val accessTokenExpirationTime: Long,
val refreshToken: String
) : Parcelable
fun SoraCardEnvironmentType.toPayWingsType(): EnvironmentType =
when (this) {
SoraCardEnvironmentType.NOT_DEFINED -> EnvironmentType.NOT_DEFINED
SoraCardEnvironmentType.TEST -> EnvironmentType.TEST
SoraCardEnvironmentType.PRODUCTION -> EnvironmentType.PRODUCTION
}
| 12 | Kotlin | 1 | 3 | f07bbcd675088bbbc74d6f32487b92768dba5ff2 | 918 | sora-card-android | Apache License 2.0 |
klinelib/src/main/java/cn/laplacetech/klinelib/chart/CustomCombinedChart.kt | limxing | 143,873,938 | false | null | package cn.laplacetech.klinelib.chart
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.util.Log
import com.github.mikephil.charting.charts.CombinedChart
import com.github.mikephil.charting.components.IMarker
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.CombinedData
import com.github.mikephil.charting.data.DataSet
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.highlight.Highlight
import com.github.mikephil.charting.interfaces.datasets.IDataSet
import com.github.mikephil.charting.utils.MPPointF
/**
* Created by <EMAIL> on 2018/8/6.
*
*/
class CustomCombinedChart @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : CombinedChart(context, attrs, defStyle) {
private var mXMarker: IMarker? = null
private var mYMarker: IMarker? = null
private var mYCenter: Float = 0.toFloat()
override fun init() {
super.init()
mRenderer = CustomCombinedChartRenderer(this, mAnimator, mViewPortHandler)
isLogEnabled = false
}
fun setYMarker(marker: IMarker) {
mYMarker = marker
}
fun setXMarker(marker: IMarker) {
mXMarker = marker
}
override fun setData(data: CombinedData) {
try {
super.setData(data)
} catch (e: ClassCastException) {
// ignore
}
(mRenderer as CustomCombinedChartRenderer).createRenderers()
mRenderer.initBuffers()
}
override fun drawMarkers(canvas: Canvas) {
super.drawMarkers(canvas)
if (mXMarker == null || !isDrawMarkersEnabled || !valuesToHighlight())
return
for (i in mIndicesToHighlight.indices) {
val highlight = mIndicesToHighlight[i]
val set = mData.getDataSetByIndex(highlight.dataSetIndex)
val e = mData.getEntryForHighlight(mIndicesToHighlight[i])
// 有疑问,修改前是:
// val entryIndex = set.getEntryIndex(e)
// val entryIndex = set.getEntryIndex(e.x, e.y, DataSet.Rounding.CLOSEST)
// make sure entry not null
if (e == null || set.getEntryIndex(e.x, e.y, DataSet.Rounding.CLOSEST) > set.entryCount * mAnimator.phaseX)
continue
val pos = getMarkerPosition(highlight)
// check bounds
if (!mViewPortHandler.isInBounds(pos[0], pos[1]))
continue
// callbacks to update the content
// mMarker.refreshContent(e, highlight)
mXMarker?.refreshContent(e, highlight)
mYMarker?.refreshContent(e, highlight)
// draw the marker
// if (mMarker instanceof LineChartYMarkerView) {
// val yMarker = mMarker as LineChartYMarkerView
val xMarker = mXMarker as LineChartXMarkerView?
val yMarker = mYMarker as LineChartYMarkerView?
// val width = yMarker.measuredWidth
// mMarker.draw(canvas, measuredWidth - width * 1.05f, pos[1] - yMarker.measuredHeight / 2)
mXMarker?.draw(canvas, pos[0] - xMarker!!.measuredWidth / 2, measuredHeight.toFloat() - xMarker.measuredHeight)
yMarker?.draw(canvas, 0f, pos[1] - yMarker.measuredHeight / 2)
// } else {
// mMarker.draw(canvas, pos[0], pos[1]);
// }
}
}
override fun drawDescription(c: Canvas) {
// check if description should be drawn
if (mDescription != null && mDescription.isEnabled) {
val position = mDescription.position
mDescPaint.typeface = mDescription.typeface
mDescPaint.textSize = mDescription.textSize
mDescPaint.color = mDescription.textColor
mDescPaint.textAlign = mDescription.textAlign
val x: Float
val y: Float
// if no position specified, draw on default position
if (position == null) {
x = width.toFloat() - mViewPortHandler.offsetRight() - mDescription.xOffset
y = mDescription.textSize + mViewPortHandler.offsetTop() + mDescription.yOffset
} else {
x = position.x
y = position.y
}
c.drawText(mDescription.text, x, y, mDescPaint)
}
}
/**
* 重写这两个方法,为了让开盘价和涨跌幅剧中显示
* Performs auto scaling of the axis by recalculating the minimum and maximum y-values based on the entries currently in view.
*/
override fun autoScale() {
val fromX = lowestVisibleX
val toX = highestVisibleX
mData.calcMinMaxY(fromX, toX)
mXAxis.calculate(mData.xMin, mData.xMax)
// calculate axis range (min / max) according to provided data
if (mAxisLeft.isEnabled) {
if (mYCenter == 0f) {
mAxisLeft.calculate(mData.getYMin(YAxis.AxisDependency.LEFT),
mData.getYMax(YAxis.AxisDependency.LEFT))
} else {
var yMin = mData.getYMin(YAxis.AxisDependency.LEFT)
var yMax = mData.getYMax(YAxis.AxisDependency.LEFT)
val interval = Math.max(Math.abs(mYCenter - yMax), Math.abs(mYCenter - yMin))
yMax = Math.max(yMax, mYCenter + interval)
yMin = Math.min(yMin, mYCenter - interval)
mAxisLeft.calculate(yMin, yMax)
}
}
if (mAxisRight.isEnabled) {
if (mYCenter == 0f) {
mAxisRight.calculate(mData.getYMin(YAxis.AxisDependency.RIGHT),
mData.getYMax(YAxis.AxisDependency.RIGHT))
} else {
var yMin = mData.getYMin(YAxis.AxisDependency.RIGHT)
var yMax = mData.getYMax(YAxis.AxisDependency.RIGHT)
val interval = Math.max(Math.abs(mYCenter - yMax), Math.abs(mYCenter - yMin))
yMax = Math.max(yMax, mYCenter + interval)
yMin = Math.min(yMin, mYCenter - interval)
mAxisRight.calculate(yMin, yMax)
}
}
calculateOffsets()
}
/**
* 重写这两个方法,为了让开盘价和涨跌幅剧中显示
*/
override fun calcMinMax() {
mXAxis.calculate(mData.xMin, mData.xMax)
if (mYCenter == 0f) {
// calculate axis range (min / max) according to provided data
mAxisLeft.calculate(mData.getYMin(YAxis.AxisDependency.LEFT), mData.getYMax(YAxis.AxisDependency.LEFT))
mAxisRight.calculate(mData.getYMin(YAxis.AxisDependency.RIGHT), mData.getYMax(YAxis.AxisDependency
.RIGHT))
} else {
var yLMin = mData.getYMin(YAxis.AxisDependency.LEFT)
var yLMax = mData.getYMax(YAxis.AxisDependency.LEFT)
val interval = Math.max(Math.abs(mYCenter - yLMax), Math.abs(mYCenter - yLMin))
yLMax = Math.max(yLMax, mYCenter + interval)
yLMin = Math.min(yLMin, mYCenter - interval)
mAxisLeft.calculate(yLMin, yLMax)
var yRMin = mData.getYMin(YAxis.AxisDependency.RIGHT)
var yRMax = mData.getYMax(YAxis.AxisDependency.RIGHT)
val rinterval = Math.max(Math.abs(mYCenter - yRMax), Math.abs(mYCenter - yRMin))
yRMax = Math.max(yRMax, mYCenter + rinterval)
yRMin = Math.min(yRMin, mYCenter - rinterval)
mAxisRight.calculate(yRMin, yRMax)
}
}
/**
* 设置图表中Y居中的值
*/
fun setYCenter(YCenter: Float) {
mYCenter = YCenter
}
fun getYMarkView(): IMarker? {
return mYMarker
}
fun getXMarkView(): IMarker? {
return mXMarker
}
}
| 1 | null | 16 | 192 | e53763eb3b8abd699b52f1295fe5788bd282be3d | 7,772 | LaplaceKLine | MIT License |
app/src/main/java/com/purplepotato/kajianku/core/util/AlarmReceiver.kt | openumma | 337,439,221 | true | {"Kotlin": 125281} | package com.purplepotato.kajianku.core.util
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
class AlarmReceiver : BroadcastReceiver() {
companion object {
private const val EXTRA_ID = "extra_id"
private const val EXTRA_MESSAGE = "extra_message"
}
override fun onReceive(context: Context?, intent: Intent?) {
intent?.let {
val id = intent.getLongExtra(EXTRA_ID, 0)
val message = intent.getStringExtra(EXTRA_MESSAGE)
Notifier.postReminderNotification(
context as Context,
id,
message as String
)
}
}
fun setOneTimeAlarm(
context: Context,
requestCode: Long,
id: Long,
message: String,
triggerAtMillis: Long
) {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, AlarmReceiver::class.java)
intent.putExtra(EXTRA_ID, id)
intent.putExtra(EXTRA_MESSAGE, message)
val pendingIntent = PendingIntent.getBroadcast(context, requestCode.toInt(), intent, 0)
alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent)
}
fun cancelAlarm(context: Context, requestCode: Long) {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, AlarmReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(context, requestCode.toInt(), intent, 0)
pendingIntent.cancel()
alarmManager.cancel(pendingIntent)
}
} | 0 | null | 0 | 0 | 7b56424b1d65ff42b1668ac337a39c31e607150e | 1,750 | kajianku | Apache License 2.0 |
client/PathFinder/app/src/main/java/com/dijkstra/pathfinder/domain/repository/MainRepository.kt | PathFinder-SSAFY | 643,691,193 | false | null | package com.dijkstra.pathfinder.domain.repository
import android.util.Log
import com.dijkstra.pathfinder.data.dto.CurrentLocationResponse
import com.dijkstra.pathfinder.data.dto.Point
import com.dijkstra.pathfinder.data.dto.SearchResponse
import com.dijkstra.pathfinder.data.dto.SearchValidResponse
import com.dijkstra.pathfinder.di.AppModule
import com.dijkstra.pathfinder.domain.api.MainApi
import com.google.gson.JsonObject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import retrofit2.Response
import javax.inject.Inject
private const val TAG = "MainRepository_싸피"
class MainRepository @Inject constructor(
@AppModule.OkHttpInterceptorApi private val mainApi: MainApi
) {
suspend fun postFacilityDynamic(searchData: String): Flow<Response<SearchResponse>> =
flow {
val json = JsonObject().apply {
addProperty("filteringSearch", searchData)
}
emit(mainApi.postFacilityDynamic(json))
}.flowOn(Dispatchers.IO) // End of postFacilityDynamic2
suspend fun postFindHelp(help: Int, point: Point): Flow<Response<Point>> =
flow {
val start = JsonObject().apply {
addProperty("x", point.x)
addProperty("y", point.y)
addProperty("z", point.z)
}
val json = JsonObject().apply {
addProperty("help", help)
add("start", start)
}
emit(mainApi.postFindHelp(json))
}.flowOn(Dispatchers.IO) // End of postFindHelp
suspend fun postCurrentLocation(point: Point): Flow<Response<CurrentLocationResponse>> =
flow {
val json = JsonObject().apply {
addProperty("x", point.x)
addProperty("y", point.y)
addProperty("z", point.z)
}
emit(mainApi.postCurrnetLocation(json))
}.flowOn(Dispatchers.IO) // End of postCurrentLocation
suspend fun patchCurrentLocation(
id: String,
currentLocation: String,
point: Point
): Flow<Response<CurrentLocationResponse>> =
flow {
val json = JsonObject().apply {
addProperty("facilityName", currentLocation)
addProperty("x", point.x)
addProperty("y", point.y)
addProperty("z", point.z)
}
emit(mainApi.patchCurrentLocation(id, json))
}.flowOn(Dispatchers.IO) // End of patchCurrentLocation
suspend fun postFacilityValid(destination: String): Flow<Response<SearchValidResponse>> =
flow {
val json = JsonObject().apply {
addProperty("filteringSearch", destination)
}
emit(mainApi.postFacilityValid(json))
}.flowOn(Dispatchers.IO) // End of postFacilityValid
} // End of MainRepository class
| 1 | Kotlin | 3 | 1 | 481f5c8f967f96293c25274ec1ef851ecc49d6bd | 2,966 | PathFinder | Apache License 2.0 |
src/dev/ky3he4ik/battleship_server/Game.kt | Ky3He4iK | 264,867,305 | false | null | package dev.ky3he4ik.battleship_server
import kotlin.random.Random
class Game(var p1: Client, var p2: Client) {
val id = Random.nextLong()
fun finish() {
if (p1.connection.isOpen)
p1.connection.send(
Action(
actionType = Action.ActionType.DISCONNECT,
playerId = 0,
name = p1.clientInfo.name,
gameId = id,
uuid = p1.clientInfo.uuid
).toJson()
)
if (p2.connection.isOpen)
p2.connection.send(
Action(
actionType = Action.ActionType.DISCONNECT,
playerId = 1,
name = p2.clientInfo.name,
gameId = id,
uuid = p2.clientInfo.uuid
).toJson()
)
}
} | 0 | Kotlin | 0 | 0 | e151eb35812d52bc5d4162a7b40c696bbf7857b5 | 880 | battleship_server | The Unlicense |
build-logic/convention/src/main/kotlin/com/abiao/convention/Compose.kt | yudengwei | 818,541,459 | false | {"Kotlin": 310654} | package com.abiao.convention
import com.android.build.api.dsl.CommonExtension
import org.gradle.api.Project
import org.gradle.api.artifacts.VersionCatalogsExtension
import org.gradle.kotlin.dsl.getByType
import org.gradle.kotlin.dsl.withType
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
internal fun Project.configureCompose(commonExtension: CommonExtension<*, *, *, *, *, *>) {
val libs = extensions.getByType<VersionCatalogsExtension>().named("libs")
commonExtension.apply {
buildFeatures {
compose = true
}
composeOptions {
kotlinCompilerExtensionVersion =
libs.findVersion("androidx-compose-compiler").get().toString()
}
}
tasks.withType<KotlinCompile>().configureEach {
kotlinOptions {
freeCompilerArgs += setOf(
"-opt-in=androidx.compose.foundation.ExperimentalFoundationApi",
"-opt-in=androidx.compose.foundation.layout.ExperimentalLayoutApi",
"-opt-in=androidx.compose.foundation.layout.ExperimentalLayoutApi",
"-opt-in=com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi",
"-opt-in=androidx.compose.material3.windowsizeclass.ExperimentalMaterial3WindowSizeClassApi",
"-opt-in=androidx.compose.animation.ExperimentalAnimationApi",
"-opt-in=androidx.compose.material.ExperimentalMaterialApi",
)
}
}
} | 0 | Kotlin | 0 | 0 | 283dedc4b1005c72730c63efb8218730a6348535 | 1,478 | composedemo | Apache License 2.0 |
src/main/kotlin/com/github/subat0m1c/hatecheaters/commands/impl/ImportantItemsCommand.kt | SubAt0m1c | 854,316,644 | false | {"Kotlin": 143911, "Java": 7021} | package com.github.subat0m1c.hatecheaters.commands.impl
import com.github.subat0m1c.hatecheaters.commands.commodore
import com.github.stivais.commodore.utils.GreedyString
import com.github.subat0m1c.hatecheaters.modules.BetterPartyFinder.importantItems
import com.github.subat0m1c.hatecheaters.utils.ChatUtils.capitalizeWords
import com.github.subat0m1c.hatecheaters.utils.ChatUtils.modMessage
import me.odinmain.config.Config
val ItemCommand = commodore("hcitems") {
literal("add").runs { item: GreedyString ->
val name = item.string.lowercase().replace("_", " ").capitalizeWords()
if (name in importantItems) return@runs modMessage("$name is already in the list!")
importantItems.add(name)
modMessage("$name has been added to the list!")
Config.save()
}
literal("remove").runs { item: GreedyString ->
val name = item.string.lowercase().replace("_", " ").capitalizeWords()
if (importantItems.remove(name)) modMessage("$name has been removed from the list!")
else modMessage("$name is not in the list!")
Config.save()
}
literal("list").runs {
if (importantItems.isEmpty()) modMessage("Item list is empty!")
else modMessage("items:\n${importantItems.joinToString("\n")}")
}
literal("clear").runs {
importantItems.clear()
Config.save()
modMessage("Cleared the items list!")
}
} | 0 | Kotlin | 0 | 1 | 88d4abe49b886d4ca79bcdc845b7559105164c5c | 1,424 | HateCheaters | MIT License |
app/src/main/java/by/godevelopment/kingcalculator/domain/partiesdomain/usecases/ValidatePartyNameUseCase.kt | aleh-god | 458,515,512 | false | {"Kotlin": 256219, "Java": 6183} | package by.godevelopment.kingcalculator.domain.partiesdomain.usecases
import by.godevelopment.kingcalculator.R
import by.godevelopment.kingcalculator.domain.commons.models.ValidationResult
import javax.inject.Inject
class ValidatePartyNameUseCase @Inject constructor() {
private val MIN_PARTY_NAME_LENGTH = 3
private val MAX_PARTY_NAME_LENGTH = 20
fun execute(partyName: String): ValidationResult {
if (partyName.length < MIN_PARTY_NAME_LENGTH) {
return ValidationResult(
successful = false,
errorMessage = R.string.message_error_validate_party_name_length
)
}
if (partyName.length > MAX_PARTY_NAME_LENGTH) {
return ValidationResult(
successful = false,
errorMessage = R.string.message_error_validate_party_name_high_length
)
}
return ValidationResult(successful = true)
}
}
| 2 | Kotlin | 0 | 2 | 295cfb7970e2a488612f3b2ec65984eb5046a460 | 947 | calculator-king | MIT License |
legal/dtos/src/commonMain/kotlin/identifier/CorporateType.kt | aSoft-Ltd | 699,234,925 | false | {"Kotlin": 71264} | @file:JsExport
package identifier
import kotlinx.serialization.Serializable
import kotlinx.JsExport
@Serializable
enum class CorporateType(val label: String) {
NGO("NGO"),
COMPANY("Company"),
GOVERNMENT_INSTITUTION("Government Institution")
} | 0 | Kotlin | 0 | 0 | d1222239619cf48d225c8516f179dc4f36384051 | 257 | identifier-api | MIT License |
app/src/main/java/ru/resodostudios/flick/core/database/DaosModule.kt | f33lnothin9 | 565,400,839 | false | null | package ru.resodostudios.flick.core.database
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import ru.resodostudios.flick.core.database.dao.MovieDao
@Module
@InstallIn(SingletonComponent::class)
object DaosModule {
@Provides
fun providesTransactionsDao(
database: FlickDatabase,
): MovieDao = database.movieDao()
} | 0 | Kotlin | 2 | 15 | a9875c075298ad915ad4f4f052c27cfc59818d53 | 412 | Flick | Apache License 2.0 |
android/src/main/kotlin/net/amond/flutter_mixpanel/MixpanelType.kt | amondnet | 185,914,587 | false | {"Dart": 12576, "Swift": 12267, "Kotlin": 9559, "Ruby": 2065, "Objective-C": 403, "Shell": 63} | package net.amond.flutter_mixpanel
import org.json.JSONObject
fun Map<String, Any>.toMixpanelProperties(): JSONObject {
val jsonObject = JSONObject()
for ((k, v) in this) {
if (v == "true") {
jsonObject.put(k, true)
} else if (v == "false") {
jsonObject.put(k, false)
}
jsonObject.put(k, v)
}
return jsonObject
}
data class Track(val event: String, val properties: Map<String, Any>? = null)
data class Time(val event: String)
data class Append(val name: String, val value: Any)
| 1 | Dart | 1 | 1 | 661c4f7c537ae1ebeb9fd03286098e8b0198e320 | 522 | flutter_mixpanel | Apache License 2.0 |
feature-about/src/main/java/de/niklasbednarczyk/nbweather/feature/about/navigation/AboutDestinations.kt | NiklasBednarczyk | 529,683,941 | false | null | package de.niklasbednarczyk.nbweather.feature.about.navigation
import de.niklasbednarczyk.nbweather.core.ui.navigation.NBNavigationDestination
object AboutDestinations {
object Overview : NBNavigationDestination.Overview {
override val route: String
get() = "about_overview"
}
} | 15 | Kotlin | 0 | 0 | e6af34b6b65007853acc6cf2bf4c3f9b5ff26359 | 310 | NBWeather | MIT License |
src/main/kotlin/com/cout970/reactive/core/Renderer.kt | cout970 | 121,807,275 | false | null | package com.cout970.reactive.core
import org.liquidengine.legui.component.Component
object Renderer {
const val METADATA_KEY = "key"
const val METADATA_COMPONENTS = "ReactiveRComponents"
const val METADATA_NODE_TREE = "ReactiveNodeTree"
const val METADATA_POST_MOUNT = "ReactivePostMount"
// This lock can be used to avoid critical races between threads
val updateLock = Any()
fun render(mountPoint: Component, func: RBuilder.() -> Unit): RContext {
return render(mountPoint, buildNode(func))
}
fun render(mountPoint: Component, app: RNode): RContext {
val ctx = RContext(mountPoint, app)
updateSubTree(ctx, mountPoint, app)
return ctx
}
fun rerender(ctx: RContext) {
updateSubTree(ctx, ctx.mountPoint, ctx.app)
}
internal fun <S, P> scheduleUpdate(comp: RComponent<P, S>, updateFunc: S.() -> S, setter: (S) -> Unit)
where S : RState, P : RProps {
if (!comp.mounted) {
throw IllegalStateException("Trying to update a unmounted component!")
}
AsyncManager.runLater {
val newState = updateFunc(comp.state)
if (comp.shouldComponentUpdate(comp.props, newState)) {
setter(newState)
val ctx = comp.ctx
val mount = comp.mountPoint
comp.componentWillUpdate()
updateSubTree(ctx, mount, mount.metadata[METADATA_NODE_TREE] as RNode)
} else {
setter(newState)
}
}
}
private fun updateSubTree(ctx: RContext, mount: Component, node: RNode) {
synchronized(updateLock) {
preUpdate(ctx)
unmountAllRComponents(ctx, mount)
ReconciliationManager.traverse(ctx, mount, node)
postUpdate(ctx)
callPostMount(mount)
ctx.updateListeners.forEach { it(mount to node) }
}
}
@Suppress("UNCHECKED_CAST")
private fun callPostMount(comp: Component) {
comp.metadata[Renderer.METADATA_POST_MOUNT]?.let { func ->
(func as? ((Component) -> Unit))?.invoke(comp)
}
comp.childComponents.forEach {
callPostMount(it)
}
}
private fun preUpdate(ctx: RContext) {
ctx.mountedComponents.clear()
ctx.unmountedComponents.clear()
}
private fun postUpdate(ctx: RContext) {
ctx.mountedComponents.filter { it !in ctx.unmountedComponents }.forEach {
it.componentWillMount()
it.componentDidMount()
}
ctx.unmountedComponents.filter { it !in ctx.mountedComponents }.forEach {
it.componentWillUnmount()
}
}
private fun unmountAllRComponents(ctx: RContext, comp: Component) {
comp.unmountComponents(ctx)
comp.childComponents.forEach { unmountAllRComponents(ctx, it) }
}
@Suppress("UNCHECKED_CAST")
private fun Component.unmountComponents(ctx: RContext) {
if (METADATA_COMPONENTS in metadata) {
val list = metadata[METADATA_COMPONENTS] as MutableList<RComponent<*, *>>
list.filter { it.mounted }.forEach {
ctx.unmountedComponents.add(it); it.mounted = false
}
}
}
} | 0 | Kotlin | 0 | 2 | 40cc6b38c57ca249c50aa7359a7afe0da041fa36 | 3,284 | Reactive | MIT License |
kmp/compose/foundation/uikit/src/commonMain/kotlin/com/egoriku/grodnoroads/foundation/uikit/listitem/SimpleListItem.kt | BehindWheel | 485,026,420 | false | {"Kotlin": 1176402, "Ruby": 5951, "Swift": 2927, "Shell": 830} | package com.egoriku.grodnoroads.foundation.uikit.listitem
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.heightIn
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
import com.egoriku.grodnoroads.foundation.icons.GrodnoRoads
import com.egoriku.grodnoroads.foundation.icons.outlined.Play
import com.egoriku.grodnoroads.foundation.preview.GrodnoRoadsM3ThemePreview
@Composable
fun SimpleListItem(
text: String,
modifier: Modifier = Modifier,
imageVector: ImageVector? = null,
onClick: () -> Unit
) {
BasicListItem(
touchModifier = modifier
.heightIn(min = 48.dp)
.clickable(onClick = onClick),
imageVector = imageVector,
text = text,
textStyle = MaterialTheme.typography.bodyMedium
)
}
@Composable
private fun SimpleListItemPreview() = GrodnoRoadsM3ThemePreview {
SimpleListItem(
imageVector = GrodnoRoads.Outlined.Play,
text = "Test test test",
onClick = {}
)
}
| 16 | Kotlin | 1 | 18 | f33ed73eb6d83670f7bb096c4a1995117d80aa2f | 1,182 | BehindWheelKMP | Apache License 2.0 |
app/src/test/java/com/yupfeg/sample/RxJavaUnitTest.kt | yuPFeG1819 | 448,007,290 | false | {"Kotlin": 640855, "Java": 11404, "AIDL": 411} | package com.yupfeg.sample
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.*
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.functions.Function
import io.reactivex.rxjava3.schedulers.Schedulers
import io.reactivex.rxjava3.subjects.BehaviorSubject
import io.reactivex.rxjava3.subjects.PublishSubject
import org.junit.Test
import java.util.concurrent.TimeUnit
/**
* RxJava相关单元测试
* @author yuPFeG
* @date
*/
class RxJavaUnitTest {
fun testObservable(){
Observable.create<String> { emitter->
val array = arrayOf("first","second","third")
array.forEach {
emitter.onNext(it)
}
emitter.onComplete()
}
.subscribe{
}
}
@Test
fun testFlatMap(){
var isComplete = false
val startTime = System.currentTimeMillis()
Observable.create<String> { emitter->
val array = arrayOf("first","second","third")
array.forEach {
// if (it == "second") throw NullPointerException("test")
emitter.onNext(it)
}
emitter.onComplete()
}
.delay(50,TimeUnit.MILLISECONDS)
.flatMap {text->
println("run flat map : $text ${System.currentTimeMillis()-startTime}ms")
Observable.create<List<String>> {
val list = mutableListOf<String>()
list.add("$text __1")
list.add("$text __2")
list.add("$text __3")
it.onNext(list)
}
}
.subscribeOn(Schedulers.io())
.subscribe(object : Observer<List<String>>{
override fun onSubscribe(d: Disposable) {
}
override fun onNext(t: List<String>) {
println("onNext : $t ${System.currentTimeMillis()-startTime}ms")
}
override fun onError(e: Throwable) {
}
override fun onComplete() {
isComplete = true
}
})
}
@Test
fun testZip(){
val observable1 = Observable.create<String> { emitter->
val array = arrayOf("first","second","third")
array.forEach {
if (it == "second") throw NullPointerException("test")
emitter.onNext(it)
}
}.delay(50,TimeUnit.MILLISECONDS)
val observable2 = Observable.create<Int> { emitter->
val array = arrayOf(1,3,5)
array.forEach { emitter.onNext(it) }
}.delay(100,TimeUnit.MILLISECONDS)
.toFlowable(BackpressureStrategy.LATEST)
.publish()
observable1
.doOnSubscribe {
println("run do on subscribe 1")
}
.startWithItem("11")
.switchIfEmpty {
it.onNext("empty value")
it.onComplete()
}
.onErrorReturnItem("error return item")
.retryWhen (ObservableRetryWithDelay(3,100,TimeUnit.MILLISECONDS))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Observer<String>{
override fun onSubscribe(d: Disposable) {
}
override fun onNext(t: String) {
println("on Next $t")
}
override fun onError(e: Throwable) {
println("on Error $e")
}
override fun onComplete() {
println("on Complete")
}
})
//
Thread.sleep(1000)
// Observable.zip(observable1,observable2, { t1, t2 ->
// "$t1 + $t2"
// })
// .subscribe {
// println("on Next $it")
// }
// Thread.sleep(1000)
}
/**
* [Observable]的延迟重试执行方法对象
* @param maxRetryCount 最大重试次数
* @param delay 重试延迟的时间
* @param unit 延迟时间的单位
* */
private class ObservableRetryWithDelay(
private val maxRetryCount : Int = 1,
private val delay: Long = 1,
private val unit : TimeUnit = TimeUnit.SECONDS
)
: Function<Observable<Throwable>, ObservableSource<*>> {
/**当前重试次数*/
private var retryCount : Int = 0
override fun apply(errorObservable : Observable<Throwable>): ObservableSource<*> {
//这里不能直接发起新的订阅,否则无效
//在Function函数中,必须对输入的 Observable<Any>进行处理,
// 此处使用flatMap操作符接收上游的数据
return errorObservable.flatMap {throwable->
if (++retryCount <= maxRetryCount){
//必须使用Observable来创建,这里要求返回为ObservableSource的子类
return@flatMap Observable.timer(delay,unit)
}
//超出最大重试次数
return@flatMap Observable.error<Exception>(throwable)
}
}
}
@Test
fun testSubjects(){
val publishSubject = PublishSubject.create<String>()
publishSubject.onNext("1")
publishSubject.toFlowable(BackpressureStrategy.LATEST)
val behaviorSubject = BehaviorSubject.createDefault("1")
val result = behaviorSubject.value
}
} | 0 | Kotlin | 0 | 0 | 1112f3158aba4aa1449ce7c94edc37ce5529bc23 | 5,406 | FastBuildLibrary | Apache License 2.0 |
tgbotapi.core/src/commonMain/kotlin/dev/inmo/tgbotapi/utils/serializers/CustomizableSerializationStrategy.kt | InsanusMokrassar | 163,152,024 | false | {"Kotlin": 3243076, "Shell": 373} | package dev.inmo.tgbotapi.utils.serializers
import dev.inmo.tgbotapi.types.update.RawUpdate
import dev.inmo.tgbotapi.types.update.abstracts.Update
import dev.inmo.tgbotapi.types.update.abstracts.UpdateDeserializationStrategy.deserialize
import kotlinx.serialization.SerializationStrategy
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlinx.serialization.json.JsonElement
interface CustomizableSerializationStrategy<T> : SerializationStrategy<T> {
fun interface CustomSerializerStrategy<T> {
fun optionallySerialize(encoder: Encoder, value: T): Boolean
}
/**
* Contains [CustomSerializerStrategy] which will be used in [Serialize] method when standard
* [RawUpdate] serializer will be unable to create [RawUpdate] (and [Update] as well)
*/
val customSerializationStrategies: Set<CustomSerializerStrategy<T>>
/**
* Adding [deserializationStrategy] into [customSerializationStrategies] for using in case of unknown update
*/
fun addUpdateSerializationStrategy(
deserializationStrategy: CustomSerializerStrategy<T>
): Boolean
/**
* Removing [deserializationStrategy] from [customSerializationStrategies]
*/
fun removeUpdateSerializationStrategy(
deserializationStrategy: CustomSerializerStrategy<T>
): Boolean
}
/**
* @param defaultSerializeCallback Default way of serialization
* @param fallbackSerialization Fallback way which will be used in case when [defaultSerializeCallback] and [customSerializationStrategies]
* were unable to serialize data
*/
open class CallbackCustomizableSerializationStrategy<T>(
override val descriptor: SerialDescriptor,
private val defaultSerializeCallback: (encoder: Encoder, value: T) -> Unit,
private val fallbackSerialization: (initialException: Throwable, encoder: Encoder, value: T) -> T = { initialException, _, _ -> throw initialException }
) : CustomizableSerializationStrategy<T> {
protected val _customSerializationStrategies = LinkedHashSet<CustomizableSerializationStrategy.CustomSerializerStrategy<T>>()
/**
* Contains [JsonSerializerStrategy] which will be used in [deserialize] method when standard
* [RawUpdate] serializer will be unable to create [RawUpdate] (and [Update] as well)
*/
override val customSerializationStrategies: Set<CustomizableSerializationStrategy.CustomSerializerStrategy<T>>
get() = _customSerializationStrategies.toSet()
/**
* Trying to serialize data by [defaultSerializeCallback]. If [defaultSerializeCallback] it will try to use each
* strategy from [customSerializationStrategies] until one of them will return true (means, serialized). If there
* are no any strategy success serialization and [defaultSerializeCallback] thrown exception will be used
* [fallbackSerialization] callback
*/
override fun serialize(encoder: Encoder, value: T) {
runCatching {
defaultSerializeCallback(encoder, value)
}.getOrElse {
customSerializationStrategies.forEach {
if (it.optionallySerialize(encoder, value)) {
return@getOrElse
}
}
// next line will be called onle in case all
fallbackSerialization(it, encoder, value)
}
}
/**
* Adding [deserializationStrategy] into [customSerializationStrategies] for using in case of unknown update
*/
override fun addUpdateSerializationStrategy(
deserializationStrategy: CustomizableSerializationStrategy.CustomSerializerStrategy<T>
): Boolean = _customSerializationStrategies.add(deserializationStrategy)
/**
* Removing [deserializationStrategy] from [customSerializationStrategies]
*/
override fun removeUpdateSerializationStrategy(
deserializationStrategy: CustomizableSerializationStrategy.CustomSerializerStrategy<T>
): Boolean = _customSerializationStrategies.remove(deserializationStrategy)
}
| 13 | Kotlin | 29 | 358 | 482c375327b7087699a4cb8bb06cb09869f07630 | 4,101 | ktgbotapi | Apache License 2.0 |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/synthetics/CfnCanaryS3EncryptionPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 63959868} | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.synthetics
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.services.synthetics.CfnCanary
/**
* A structure that contains the configuration of the encryption-at-rest settings for artifacts that
* the canary uploads to Amazon S3 .
*
* Artifact encryption functionality is available only for canaries that use Synthetics runtime
* version syn-nodejs-puppeteer-3.3 or later. For more information, see
* [Encrypting canary artifacts](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_artifact_encryption.html)
* .
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.synthetics.*;
* S3EncryptionProperty s3EncryptionProperty = S3EncryptionProperty.builder()
* .encryptionMode("encryptionMode")
* .kmsKeyArn("kmsKeyArn")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-synthetics-canary-s3encryption.html)
*/
@CdkDslMarker
public class CfnCanaryS3EncryptionPropertyDsl {
private val cdkBuilder: CfnCanary.S3EncryptionProperty.Builder =
CfnCanary.S3EncryptionProperty.builder()
/**
* @param encryptionMode The encryption method to use for artifacts created by this canary.
* Specify `SSE_S3` to use server-side encryption (SSE) with an Amazon S3-managed key. Specify
* `SSE-KMS` to use server-side encryption with a customer-managed AWS KMS key.
*
* If you omit this parameter, an AWS -managed AWS KMS key is used.
*/
public fun encryptionMode(encryptionMode: String) {
cdkBuilder.encryptionMode(encryptionMode)
}
/**
* @param kmsKeyArn The ARN of the customer-managed AWS KMS key to use, if you specify `SSE-KMS`
* for `EncryptionMode`.
*/
public fun kmsKeyArn(kmsKeyArn: String) {
cdkBuilder.kmsKeyArn(kmsKeyArn)
}
public fun build(): CfnCanary.S3EncryptionProperty = cdkBuilder.build()
}
| 4 | Kotlin | 0 | 3 | c59c6292cf08f0fc3280d61e7f8cff813a608a62 | 2,367 | awscdk-dsl-kotlin | Apache License 2.0 |
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/batch/Share.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 149148378} | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.batch
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.common.CdkObject
import io.cloudshiftdev.awscdk.common.CdkObjectWrappers
import kotlin.Number
import kotlin.String
import kotlin.Unit
/**
* Represents a group of Job Definitions.
*
* All Job Definitions that
* declare a share identifier will be considered members of the Share
* defined by that share identifier.
*
* The Scheduler divides the maximum available vCPUs of the ComputeEnvironment
* among Jobs in the Queue based on their shareIdentifier and the weightFactor
* associated with that shareIdentifier.
*
* Example:
*
* ```
* FairshareSchedulingPolicy fairsharePolicy = new FairshareSchedulingPolicy(this,
* "myFairsharePolicy");
* fairsharePolicy.addShare(Share.builder()
* .shareIdentifier("A")
* .weightFactor(1)
* .build());
* fairsharePolicy.addShare(Share.builder()
* .shareIdentifier("B")
* .weightFactor(1)
* .build());
* JobQueue.Builder.create(this, "JobQueue")
* .schedulingPolicy(fairsharePolicy)
* .build();
* ```
*/
public interface Share {
/**
* The identifier of this Share.
*
* All jobs that specify this share identifier
* when submitted to the queue will be considered as part of this Share.
*/
public fun shareIdentifier(): String
/**
* The weight factor given to this Share.
*
* The Scheduler decides which jobs to put in the Compute Environment
* such that the following ratio is equal for each job:
*
* `sharevCpu / weightFactor`,
*
* where `sharevCpu` is the total amount of vCPU given to that particular share; that is,
* the sum of the vCPU of each job currently in the Compute Environment for that share.
*
* See the readme of this module for a detailed example that shows how these are used,
* how it relates to `computeReservation`, and how `shareDecay` affects these calculations.
*/
public fun weightFactor(): Number
/**
* A builder for [Share]
*/
@CdkDslMarker
public interface Builder {
/**
* @param shareIdentifier The identifier of this Share.
* All jobs that specify this share identifier
* when submitted to the queue will be considered as part of this Share.
*/
public fun shareIdentifier(shareIdentifier: String)
/**
* @param weightFactor The weight factor given to this Share.
* The Scheduler decides which jobs to put in the Compute Environment
* such that the following ratio is equal for each job:
*
* `sharevCpu / weightFactor`,
*
* where `sharevCpu` is the total amount of vCPU given to that particular share; that is,
* the sum of the vCPU of each job currently in the Compute Environment for that share.
*
* See the readme of this module for a detailed example that shows how these are used,
* how it relates to `computeReservation`, and how `shareDecay` affects these calculations.
*/
public fun weightFactor(weightFactor: Number)
}
private class BuilderImpl : Builder {
private val cdkBuilder: software.amazon.awscdk.services.batch.Share.Builder =
software.amazon.awscdk.services.batch.Share.builder()
/**
* @param shareIdentifier The identifier of this Share.
* All jobs that specify this share identifier
* when submitted to the queue will be considered as part of this Share.
*/
override fun shareIdentifier(shareIdentifier: String) {
cdkBuilder.shareIdentifier(shareIdentifier)
}
/**
* @param weightFactor The weight factor given to this Share.
* The Scheduler decides which jobs to put in the Compute Environment
* such that the following ratio is equal for each job:
*
* `sharevCpu / weightFactor`,
*
* where `sharevCpu` is the total amount of vCPU given to that particular share; that is,
* the sum of the vCPU of each job currently in the Compute Environment for that share.
*
* See the readme of this module for a detailed example that shows how these are used,
* how it relates to `computeReservation`, and how `shareDecay` affects these calculations.
*/
override fun weightFactor(weightFactor: Number) {
cdkBuilder.weightFactor(weightFactor)
}
public fun build(): software.amazon.awscdk.services.batch.Share = cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.batch.Share,
) : CdkObject(cdkObject), Share {
/**
* The identifier of this Share.
*
* All jobs that specify this share identifier
* when submitted to the queue will be considered as part of this Share.
*/
override fun shareIdentifier(): String = unwrap(this).getShareIdentifier()
/**
* The weight factor given to this Share.
*
* The Scheduler decides which jobs to put in the Compute Environment
* such that the following ratio is equal for each job:
*
* `sharevCpu / weightFactor`,
*
* where `sharevCpu` is the total amount of vCPU given to that particular share; that is,
* the sum of the vCPU of each job currently in the Compute Environment for that share.
*
* See the readme of this module for a detailed example that shows how these are used,
* how it relates to `computeReservation`, and how `shareDecay` affects these calculations.
*/
override fun weightFactor(): Number = unwrap(this).getWeightFactor()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): Share {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal fun wrap(cdkObject: software.amazon.awscdk.services.batch.Share): Share =
CdkObjectWrappers.wrap(cdkObject) as? Share ?: Wrapper(cdkObject)
internal fun unwrap(wrapped: Share): software.amazon.awscdk.services.batch.Share = (wrapped as
CdkObject).cdkObject as software.amazon.awscdk.services.batch.Share
}
}
| 4 | Kotlin | 0 | 4 | 9a242bcc59b2c1cf505be2f9d838f1cd8008fe12 | 6,197 | kotlin-cdk-wrapper | Apache License 2.0 |
fontawesome/src/de/msrd0/fontawesome/icons/FA_LANDMARK_FLAG.kt | msrd0 | 363,665,023 | false | {"Kotlin": 3912511, "Jinja": 2214} | /* @generated
*
* This file is part of the FontAwesome Kotlin library.
* https://github.com/msrd0/fontawesome-kt
*
* This library is not affiliated with FontAwesome.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.msrd0.fontawesome.icons
import de.msrd0.fontawesome.Icon
import de.msrd0.fontawesome.Style
import de.msrd0.fontawesome.Style.SOLID
/** Landmark Flag */
object FA_LANDMARK_FLAG: Icon {
override val name get() = "Landmark Flag"
override val unicode get() = "e51c"
override val styles get() = setOf(SOLID)
override fun svg(style: Style) = when(style) {
SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M352 0C360.8 0 368 7.164 368 16V80C368 88.84 360.8 96 352 96H272V128H464C481.7 128 496 142.3 496 160C496 177.7 481.7 192 464 192H47.1C30.33 192 15.1 177.7 15.1 160C15.1 142.3 30.33 128 47.1 128H239.1V16C239.1 7.164 247.2 0 255.1 0H352zM63.1 224H127.1V416H167.1V224H231.1V416H280V224H344V416H384V224H448V420.3C448.6 420.6 449.2 420.1 449.8 421.4L497.8 453.4C509.5 461.2 514.7 475.8 510.6 489.3C506.5 502.8 494.1 512 480 512H31.1C17.9 512 5.458 502.8 1.372 489.3C-2.715 475.8 2.515 461.2 14.25 453.4L62.25 421.4C62.82 420.1 63.4 420.6 63.1 420.3V224z"/></svg>"""
else -> null
}
}
| 0 | Kotlin | 0 | 0 | ee6a62d201fd5df2555859271cb0c6a7ee887e7a | 1,778 | fontawesome-kt | Apache License 2.0 |
study/Study14/app/src/main/java/org/techtown/movie/OnMovieFavoriteListItemClickListener.kt | mike-jung | 281,814,310 | false | null | package org.techtown.movie
import android.view.View
interface OnMovieFavoriteListItemClickListener {
fun onItemClick(holder: MovieFavoriteListAdapter.ViewHolder?, view: View?, position: Int)
} | 0 | null | 17 | 13 | f7b6f1df6d5445bee3b02c63527c997da22157f1 | 200 | kotlin-android | Apache License 2.0 |
app/src/main/java/com/vadmax/timetosleep/ui/screens/phonetimer/ui/Moon.kt | VadimZhuk0v | 403,318,456 | false | {"Kotlin": 214064, "Ruby": 928} | package com.vadmax.timetosleep.ui.screens.phonetimer.ui
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCancellationBehavior
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.LottieConstants
import com.airbnb.lottie.compose.animateLottieCompositionAsState
import com.airbnb.lottie.compose.rememberLottieComposition
import com.vadmax.timetosleep.R
import com.vadmax.timetosleep.coreui.extensions.clickableNoRipple
@Composable
fun Moon(
isTimerEnable: Boolean,
onCheckedChange: (value: Boolean) -> Unit,
) {
val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.lt_moon))
val lottieState = animateLottieCompositionAsState(
composition = composition,
isPlaying = isTimerEnable,
iterations = LottieConstants.IterateForever,
cancellationBehavior = LottieCancellationBehavior.OnIterationFinish,
)
LottieAnimation(
composition = composition,
progress = { lottieState.progress },
modifier = Modifier
.fillMaxSize()
.clickableNoRipple {
onCheckedChange(isTimerEnable.not())
},
)
}
| 0 | Kotlin | 1 | 1 | 927e28d6b0dc422cb0d4a70be067566be13f40bb | 1,388 | TimeToSleep | MIT License |
app/src/main/java/com/example/recipeapp/data/adapters/ViewPagerAdapter.kt | Someboty | 747,740,247 | false | {"Kotlin": 109244} | package com.example.recipeapp.data.adapters
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
/**
* Adapter class for managing fragments in a ViewPager2 within a FragmentActivity.
*
* @param fragmentActivity The FragmentActivity hosting the ViewPager2.
* @param fragments List of fragments to be displayed in the ViewPager2.
* @param titles List of titles corresponding to each fragment.
*/
class ViewPagerAdapter(
fragmentActivity: FragmentActivity,
private val fragments: List<Fragment>,
private val titles: List<String>
) : FragmentStateAdapter(fragmentActivity) {
/**
* Returns the total number of fragments managed by the adapter.
*
* @return The total number of fragments.
*/
override fun getItemCount() = fragments.size
/**
* Creates a new fragment for the given position.
*
* @param position The position of the fragment in the ViewPager2.
* @return The newly created fragment.
*/
override fun createFragment(position: Int): Fragment = fragments[position]
/**
* Returns the title of the fragment at the specified position.
*
* @param position The position of the fragment.
* @return The title of the fragment.
*/
fun getPageTitle(position: Int): CharSequence = titles[position]
}
| 0 | Kotlin | 0 | 0 | 15d50588b5ecde3440cc101cb69bfbf4e7c9b541 | 1,391 | Recipe_App | MIT License |
app/src/main/java/io/github/eh/eh/TermsActivity.kt | Singlerr | 367,322,450 | false | null | package io.github.eh.eh
import android.os.Bundle
import android.transition.Slide
import android.view.Gravity
import android.view.Window
import androidx.appcompat.app.AppCompatActivity
class TermsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
with(window) {
requestWindowFeature(Window.FEATURE_CONTENT_TRANSITIONS)
exitTransition = Slide(Gravity.RIGHT)
}
setContentView(R.layout.activity_terms)
}
} | 0 | Kotlin | 0 | 0 | c59f9c4236481abcd5b0dd3ad4e2806a439f35e5 | 537 | EscapeHonbab | Creative Commons Zero v1.0 Universal |
renderer/src/main/java/com/gabrielittner/renderer/RendererComposable.kt | gabrielittner | 208,638,130 | false | {"Kotlin": 18155} | package com.gabrielittner.renderer
import android.view.LayoutInflater
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView
@Composable
fun <State : Any, Action : Any> Renderer(
factory: ViewRenderer.Factory<*, out ViewRenderer<State, Action>>,
state: State,
sendAction: (Action) -> Unit,
modifier: Modifier = Modifier,
) {
val rendererState = remember { mutableStateOf<ViewRenderer<State, Action>?>(null) }
LaunchedEffect(rendererState.value) {
rendererState.value?.actions?.collect { sendAction(it) }
}
AndroidView(
modifier = modifier,
factory = {
val newRenderer = factory.inflate(LayoutInflater.from(it), null)
rendererState.value = newRenderer
newRenderer.rootView
},
) {
rendererState.value!!.render(state)
}
}
| 2 | Kotlin | 1 | 8 | cf80b7b4b57c989b6319c23d39d18e73fe00ebf0 | 1,049 | renderer | Apache License 2.0 |
app/src/main/java/com/lyc/gank/utils/ClipExt.kt | SirLYC | 93,046,345 | false | null | package com.lyc.gank.utils
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Context.CLIPBOARD_SERVICE
/**
* Created by <NAME> on 2018/2/23.
*/
fun Context.textCopy(content: CharSequence) {
val clipBoardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
clipBoardManager.primaryClip = ClipData.newPlainText(null, content)
}
fun Context.textPaste(): CharSequence? {
val clipBoardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
return if (clipBoardManager.hasPrimaryClip())
clipBoardManager.primaryClip.getItemAt(0).text
else null
} | 1 | Kotlin | 0 | 6 | f72e0079a84871da510012e8f4b8cb330f80d1a1 | 672 | Android-Gank-Share | Apache License 2.0 |
intellij-plugin/src/main/kotlin/com/squareup/idea/dagger/DaggerProjectComponent.kt | AlecKazakova | 148,797,966 | true | {"Kotlin": 2657} | package com.squareup.idea.dagger
import com.intellij.openapi.components.ProjectComponent
class DaggerProjectComponent : ProjectComponent {
override fun projectOpened() {
println("Hello World!")
}
} | 0 | Kotlin | 0 | 0 | 86ec808f9757a99c46e774f8b9d653d7aaf2484d | 207 | dagger-intellij-plugin | Apache License 2.0 |
core/data/src/main/java/de/cleema/android/core/data/network/routes/RegionsRoute.kt | sandstorm | 840,235,083 | false | {"Kotlin": 955115, "Ruby": 1773} | package de.cleema.android.core.data.network.routes
import de.cleema.android.core.data.network.responses.ApiResponse
import de.cleema.android.core.data.network.responses.RegionResponse
import retrofit2.http.GET
import retrofit2.http.Query
import java.util.*
internal interface RegionsRoute {
@GET("api/regions")
suspend fun getRegions(@Query("filters[uuid][\$eq]") id: UUID? = null): Result<ApiResponse<List<RegionResponse>>>
}
| 0 | Kotlin | 0 | 1 | ddcb7ddedbbefb8045e7299e14a2ad47329fc53e | 437 | cleema-android | MIT License |
src/test/kotlin/leetcode/LC_98_ValidateBinarySearchTreeTest.kt | so3500 | 110,426,646 | false | {"Java": 733632, "Kotlin": 67130, "Python": 10364, "Shell": 893} | package leetcode
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
class LC_98_ValidateBinarySearchTreeTest {
private val lcn = LC_98_ValidateBinarySearchTree()
@ParameterizedTest
@MethodSource
fun test(input: TreeNode, expected: Boolean) {
assertThat(lcn.isValidBST(input)).isEqualTo(expected)
}
companion object {
@JvmStatic
private fun test() = listOf(
Arguments.of(TreeNode(2, TreeNode(1), TreeNode(3)), true),
Arguments.of(TreeNode(2, TreeNode(1), TreeNode(3)), true),
Arguments.of(TreeNode(1, TreeNode(1), TreeNode(1)), false),
Arguments.of(TreeNode(2147483647), true)
)
}
} | 1 | Java | 1 | 1 | 1e2a25431b419d0e8d60f5ca88dde8c08d870786 | 767 | problem-solving | MIT License |
app/src/main/java/com/jhc/volumetile/VolumeTileService.kt | j-hc | 608,155,571 | false | null | package com.jhc.volumetile
import android.media.AudioManager
import android.service.quicksettings.TileService
class VolumeTileService : TileService() {
private lateinit var am: AudioManager
override fun onStartListening() {
am = getSystemService(AUDIO_SERVICE) as AudioManager
}
override fun onClick() {
am.adjustStreamVolume(
AudioManager.STREAM_MUSIC, AudioManager.ADJUST_SAME, AudioManager.FLAG_SHOW_UI
)
}
} | 0 | Kotlin | 0 | 2 | 282da234c9e9321486d86a3238a9a5868d97ee20 | 471 | VolumeTile | MIT License |
core/src/commonMain/kotlin/com/symbiosis/sdk/contract/ContractAddress.kt | symbiosis-finance | 473,611,783 | false | {"Kotlin": 563820, "Swift": 5851, "Ruby": 1700} | package com.symbiosis.sdk.contract
import dev.icerock.moko.web3.EthereumAddress
fun List<EthereumAddress>.sortedAddresses() = sortedBy(EthereumAddress::withoutPrefix)
| 0 | Kotlin | 2 | 4 | e8b1c424c62a847a5339039864223e65fdb2cbae | 169 | mobile-sdk | Apache License 2.0 |
zebra/core/data/src/main/java/com/maksimowiczm/zebra/core/data/repository/UserPreferencesRepository.kt | maksimowiczm | 854,647,759 | false | {"Kotlin": 244293} | package com.maksimowiczm.zebra.core.data.repository
import com.maksimowiczm.zebra.core.datastore.UserPreferencesDataSource
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class UserPreferencesRepository @Inject constructor(
private val userPreferencesDataSource: UserPreferencesDataSource,
) {
fun observeBiometricIdentifier(): Flow<ByteArray> {
return userPreferencesDataSource.observeBiometricIdentifier()
}
suspend fun getBiometricIdentifier(): ByteArray {
return userPreferencesDataSource.getBiometricIdentifier()
}
suspend fun setBiometricIdentifier(identifier: ByteArray) {
return userPreferencesDataSource.updateBiometricIdentifier(identifier)
}
} | 0 | Kotlin | 0 | 0 | 21f20c7f83a542b704928171371d10e6a14c6ce5 | 725 | zebra-android | Apache License 2.0 |
core/domain/src/main/java/org/the_chance/honeymart/domain/usecase/usecaseManager/user/UserCouponsManagerUseCase.kt | TheChance101 | 647,400,117 | false | {"Kotlin": 1218713} | package org.the_chance.honeymart.domain.usecase.usecaseManager.user
import org.the_chance.honeymart.domain.usecase.ClipCouponUseCase
import org.the_chance.honeymart.domain.usecase.GetClippedUserCouponsUseCase
import org.the_chance.honeymart.domain.usecase.GetCouponsUseCase
import javax.inject.Inject
data class UserCouponsManagerUseCase @Inject constructor(
val clipCouponUseCase: ClipCouponUseCase,
val getAllCouponsUseCase: GetCouponsUseCase,
val getClippedUserCouponsUseCase: GetClippedUserCouponsUseCase,
)
| 3 | Kotlin | 7 | 21 | 50200e0ec0802cdadc282b09074a19c96df3220c | 526 | Honey-Mart-Android-Client | Apache License 2.0 |
kotlin/PlanesAndroid/app/src/main/java/com/planes/android/customviews/ViewWithText.kt | xxxcucus | 141,627,030 | false | {"Kotlin": 568895, "C++": 491550, "Java": 230638, "TeX": 105835, "C": 77099, "QML": 33687, "CMake": 24483, "HTML": 18531, "JavaScript": 5615, "Assembly": 4220, "Ruby": 909, "Shell": 631} | package com.planes.android.customviews
interface ViewWithText {
fun getOptimalTextSize(maxTextSize: Int, viewWidth: Int, viewHeight: Int): Int
fun setTextSize(textSize: Int)
} | 13 | Kotlin | 9 | 35 | 68d5e14566ea2bfe06df933ab80eb0182df5dad0 | 184 | planes | MIT License |
app/src/main/java/com/yangdai/opennote/ui/component/NoteCard.kt | YangDai2003 | 774,993,540 | false | {"Kotlin": 218210} | package com.yangdai.opennote.ui.component
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.basicMarquee
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.sizeIn
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.yangdai.opennote.data.local.entity.NoteEntity
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun NoteCard(
note: NoteEntity,
isEnabled: Boolean,
isSelected: Boolean,
onNoteClick: (NoteEntity) -> Unit,
onEnableChange: (Boolean) -> Unit
) =
ElevatedCard(modifier = Modifier
.sizeIn(minHeight = 80.dp, maxHeight = 360.dp)
.combinedClickable(
onLongClick = {
onEnableChange(true)
},
onClick = { onNoteClick(note) }
)
) {
Box(modifier = Modifier.fillMaxWidth()) {
if (isEnabled)
Checkbox(
checked = isSelected, onCheckedChange = null, modifier = Modifier
.padding(10.dp)
.align(Alignment.TopEnd)
)
Column(
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp, horizontal = 10.dp)
) {
Text(
modifier = Modifier
.basicMarquee()
.padding(bottom = 12.dp),
text = note.title,
style = MaterialTheme.typography.titleMedium,
maxLines = 1
)
Text(
text = note.content,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
overflow = TextOverflow.Ellipsis
)
}
}
}
| 0 | Kotlin | 0 | 0 | 7e727f427cd812759a517db20420357005bafd92 | 2,451 | OpenNote-Compose | Apache License 2.0 |
lib-blast-types/examples/printing-help/src/main/kotlin/example/main.kt | VEuPathDB | 303,794,401 | false | {"Kotlin": 1601655, "Java": 404589, "RAML": 120840, "Dockerfile": 3585, "Shell": 2218, "SQL": 2160} | package example
import org.veupathdb.lib.blast.Blast
import org.veupathdb.lib.blast.common.fields.HelpLong
import java.io.InputStream
import java.io.OutputStream
fun main() {
val command = Blast.blastn().apply {
longHelp = HelpLong(true)
}
println("Executing command: ${command.toCliString()}")
println()
println("=== Command Output: =============================================")
println()
with(ProcessBuilder(*command.toCliArray()).start()) {
inputStream.transferTo(System.out)
errorStream.transferTo(System.err)
require(waitFor() == 0)
}
}
//
// transferTo (available in JDK 9+)
//
private const val BUFFER_SIZE = 8192
private fun InputStream.transferTo(out: OutputStream) {
val buffer = ByteArray(BUFFER_SIZE)
var read: Int
while (this.read(buffer, 0, BUFFER_SIZE).also { read = it } >= 0) {
out.write(buffer, 0, read)
}
} | 20 | Kotlin | 0 | 0 | e0639a45d45fce3e393ab1eff1176c5c75375738 | 877 | service-multi-blast | Apache License 2.0 |
lib-blast-types/examples/printing-help/src/main/kotlin/example/main.kt | VEuPathDB | 303,794,401 | false | {"Kotlin": 1601655, "Java": 404589, "RAML": 120840, "Dockerfile": 3585, "Shell": 2218, "SQL": 2160} | package example
import org.veupathdb.lib.blast.Blast
import org.veupathdb.lib.blast.common.fields.HelpLong
import java.io.InputStream
import java.io.OutputStream
fun main() {
val command = Blast.blastn().apply {
longHelp = HelpLong(true)
}
println("Executing command: ${command.toCliString()}")
println()
println("=== Command Output: =============================================")
println()
with(ProcessBuilder(*command.toCliArray()).start()) {
inputStream.transferTo(System.out)
errorStream.transferTo(System.err)
require(waitFor() == 0)
}
}
//
// transferTo (available in JDK 9+)
//
private const val BUFFER_SIZE = 8192
private fun InputStream.transferTo(out: OutputStream) {
val buffer = ByteArray(BUFFER_SIZE)
var read: Int
while (this.read(buffer, 0, BUFFER_SIZE).also { read = it } >= 0) {
out.write(buffer, 0, read)
}
} | 20 | Kotlin | 0 | 0 | e0639a45d45fce3e393ab1eff1176c5c75375738 | 877 | service-multi-blast | Apache License 2.0 |
app/src/main/kotlin/dev/aaa1115910/bv/component/pgc/Carousel.kt | aaa1115910 | 571,702,700 | false | {"Kotlin": 1683327} | package dev.aaa1115910.bv.component.pgc
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.tv.material3.Carousel
import androidx.tv.material3.ExperimentalTvMaterial3Api
import androidx.tv.material3.MaterialTheme
import coil.compose.AsyncImage
import dev.aaa1115910.biliapi.entity.pgc.PgcCarouselData
import dev.aaa1115910.bv.activities.video.SeasonInfoActivity
import dev.aaa1115910.bv.entity.proxy.ProxyArea
import dev.aaa1115910.bv.util.focusedBorder
@OptIn(ExperimentalTvMaterial3Api::class)
@Composable
fun PgcCarousel(
modifier: Modifier = Modifier,
data: List<PgcCarouselData.CarouselItem>
) {
val context = LocalContext.current
Carousel(
itemCount = data.size,
modifier = modifier
//.fillMaxWidth()
.height(240.dp)
.clip(MaterialTheme.shapes.large)
.focusedBorder(),
contentTransformEndToStart =
fadeIn(tween(1000)).togetherWith(fadeOut(tween(1000))),
contentTransformStartToEnd =
fadeIn(tween(1000)).togetherWith(fadeOut(tween(1000)))
) { itemIndex ->
PgcCarouselCard(
data = data[itemIndex],
onClick = {
SeasonInfoActivity.actionStart(
context = context,
epId = data[itemIndex].episodeId,
seasonId = data[itemIndex].seasonId,
proxyArea = ProxyArea.checkProxyArea(data[itemIndex].title)
)
}
)
}
}
@Composable
fun PgcCarouselCard(
modifier: Modifier = Modifier,
data: PgcCarouselData.CarouselItem,
onClick: () -> Unit = {}
) {
AsyncImage(
modifier = modifier
.fillMaxWidth()
.clip(MaterialTheme.shapes.large)
.clickable { onClick() },
model = data.cover,
contentDescription = null,
contentScale = ContentScale.Crop,
alignment = Alignment.TopCenter
)
} | 22 | Kotlin | 161 | 1,429 | ac8c6ca424a99840e4073d7aa8fe71ea8a898388 | 2,516 | bv | MIT License |
app/src/main/kotlin/dev/aaa1115910/bv/component/pgc/Carousel.kt | aaa1115910 | 571,702,700 | false | {"Kotlin": 1683327} | package dev.aaa1115910.bv.component.pgc
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.tv.material3.Carousel
import androidx.tv.material3.ExperimentalTvMaterial3Api
import androidx.tv.material3.MaterialTheme
import coil.compose.AsyncImage
import dev.aaa1115910.biliapi.entity.pgc.PgcCarouselData
import dev.aaa1115910.bv.activities.video.SeasonInfoActivity
import dev.aaa1115910.bv.entity.proxy.ProxyArea
import dev.aaa1115910.bv.util.focusedBorder
@OptIn(ExperimentalTvMaterial3Api::class)
@Composable
fun PgcCarousel(
modifier: Modifier = Modifier,
data: List<PgcCarouselData.CarouselItem>
) {
val context = LocalContext.current
Carousel(
itemCount = data.size,
modifier = modifier
//.fillMaxWidth()
.height(240.dp)
.clip(MaterialTheme.shapes.large)
.focusedBorder(),
contentTransformEndToStart =
fadeIn(tween(1000)).togetherWith(fadeOut(tween(1000))),
contentTransformStartToEnd =
fadeIn(tween(1000)).togetherWith(fadeOut(tween(1000)))
) { itemIndex ->
PgcCarouselCard(
data = data[itemIndex],
onClick = {
SeasonInfoActivity.actionStart(
context = context,
epId = data[itemIndex].episodeId,
seasonId = data[itemIndex].seasonId,
proxyArea = ProxyArea.checkProxyArea(data[itemIndex].title)
)
}
)
}
}
@Composable
fun PgcCarouselCard(
modifier: Modifier = Modifier,
data: PgcCarouselData.CarouselItem,
onClick: () -> Unit = {}
) {
AsyncImage(
modifier = modifier
.fillMaxWidth()
.clip(MaterialTheme.shapes.large)
.clickable { onClick() },
model = data.cover,
contentDescription = null,
contentScale = ContentScale.Crop,
alignment = Alignment.TopCenter
)
} | 22 | Kotlin | 161 | 1,429 | ac8c6ca424a99840e4073d7aa8fe71ea8a898388 | 2,516 | bv | MIT License |
src/main/java/ru/hollowhorizon/hc/client/imgui/ImGuiExample.kt | HollowHorizon | 450,852,365 | false | {"Kotlin": 534641, "Java": 118373, "GLSL": 8074} | package ru.hollowhorizon.hc.client.imgui
import imgui.extension.texteditor.TextEditor
import imgui.extension.texteditor.TextEditorLanguageDefinition
import imgui.flag.ImGuiTreeNodeFlags
import imgui.flag.ImGuiWindowFlags
import imgui.type.ImInt
import imgui.type.ImString
import net.minecraft.client.Minecraft
import java.io.File
val text = ImString("Капец, какой ужас, что за убогий интерфейс... \uD83D\uDE00")
val item = ImInt()
private val EDITOR = TextEditor().apply {
setLanguageDefinition(TextEditorLanguageDefinition.c().apply {
setIdentifiers(
mapOf(
"npc" to "Возможные функции:\nmoveTo { ... }\nlookAt { ... }\nmoveAlwaysTo { ... }\nlookAlwaysAt { ... }",
"moveTo" to "Персонаж пойдёт к указанной цели, например: pos(0, 0, 0), team или entity.",
)
)
})
}
fun test() = object : Renderable {
override fun render() {
val window = Minecraft.getInstance().window
begin(
"Редактор кода", ImGuiWindowFlags.NoCollapse or
ImGuiWindowFlags.NoResize or
ImGuiWindowFlags.NoMove or
ImGuiWindowFlags.HorizontalScrollbar
) {
setWindowPos(window.width / 2f, 0f)
setWindowSize(window.width / 2f, window.height.toFloat())
EDITOR.render("Редактор кода")
}
begin(
"ОКНО", ImGuiWindowFlags.NoCollapse or
ImGuiWindowFlags.NoResize or
ImGuiWindowFlags.NoMove or
ImGuiWindowFlags.NoTitleBar or
ImGuiWindowFlags.HorizontalScrollbar
) {
setWindowPos(0f, 0f)
setWindowSize(window.width.toFloat(), window.height.toFloat())
setWindowSize(window.width / 2f, window.height.toFloat())
drawTree(File("C:\\Users\\Artem\\AppData\\Roaming\\.minecraft\\hollowengine"))
}
}
fun drawTree(file: File) {
val params =
if (file.isDirectory) 0 else ImGuiTreeNodeFlags.NoTreePushOnOpen or ImGuiTreeNodeFlags.Leaf or ImGuiTreeNodeFlags.SpanFullWidth
treeNode(file.name, params) {
file.listFiles()?.sortedBy { if (it.isDirectory) 0 else 1 }?.forEach {
drawTree(it)
}
}
}
override fun getTheme() = object : Theme {
override fun preRender() {
}
override fun postRender() {
}
}
} | 0 | Kotlin | 2 | 14 | 0ebb1ce35d4c6e286a73902ed5dac60a8a206421 | 2,468 | HollowCore | MIT License |
src/main/kotlin/il/co/sysbind/intellij/moodledev/util/MoodleFileTemplateGroupFactory.kt | SysBind | 296,470,214 | false | {"Kotlin": 27404, "HTML": 3130, "PHP": 389} | package il.co.sysbind.intellij.moodledev.util
import com.intellij.ide.fileTemplates.FileTemplateGroupDescriptor
import com.intellij.ide.fileTemplates.FileTemplateGroupDescriptorFactory
class MoodleFileTemplateGroupFactory : FileTemplateGroupDescriptorFactory {
override fun getFileTemplatesDescriptor(): FileTemplateGroupDescriptor {
TODO("Not yet implemented")
}
}
| 3 | Kotlin | 0 | 3 | 51bec41f2a25c699750491b8e8124f0efa09053f | 384 | moodle-dev | Apache License 2.0 |
app/src/main/java/com/kotlin/cloud/kotlinUtil/toast.kt | zhuasen | 270,330,684 | false | {"Kotlin": 101932, "Java": 16475} | package com.kotlin.cloud.kotlinUtil
import android.widget.Toast
import com.kotlin.cloud.oss.OssApplication
/**
* Toast工具类
* 用法:
* 某个String类型.toastShort即可,也可使用长时toast
*
* */
fun String.toastShort(){
Toast.makeText(getContext(),this,Toast.LENGTH_SHORT).show();
}
fun String.toastLong(){
Toast.makeText(getContext(),this,Toast.LENGTH_LONG).show();
} | 0 | null | 0 | 0 | 6e0362d41fffddad8a8ef264ee080cd9a6f4772e | 362 | Cloud_Kotlin | Apache License 2.0 |
android/features/history/src/main/java/nl/entreco/giddyapp/history/models/HeaderViewHolder.kt | Entreco | 164,009,012 | false | null | package nl.entreco.giddyapp.history.models
import nl.entreco.giddyapp.history.databinding.ListMatchNameBinding
class HeaderViewHolder(private val binding: ListMatchNameBinding) :
BaseViewHolder<BaseModel.HeaderModel>(binding.root) {
override fun bind(model: BaseModel.HeaderModel?, position: Int) {
binding.model = model
binding.executePendingBindings()
}
} | 23 | null | 1 | 1 | 59960640ecd182c502df2d52fa17ed619d415c91 | 387 | GiddyApp | Apache License 2.0 |
modules/services/core/src/commonMain/kotlin/com/makeevrserg/empireprojekt/mobile/services/core/LinkBrowser.kt | makeevrserg | 655,032,944 | false | {"Kotlin": 309198, "Swift": 16767, "Ruby": 1737} | package com.makeevrserg.empireprojekt.mobile.services.core
interface LinkBrowser {
fun openInBrowser(url: String)
}
| 1 | Kotlin | 0 | 3 | 0b2201d03b5b464f362e0d2e8bb4e59ed6d0950a | 121 | EmpireProjekt-Mobile | RSA Message-Digest License |
dashkit/src/main/kotlin/io/definenulls/dashkit/messages/TransactionLockMessage.kt | toEther | 677,363,684 | false | null | package io.definenulls.dashkit.messages
import io.definenulls.bitcoincore.extensions.toReversedHex
import io.definenulls.bitcoincore.io.BitcoinInputMarkable
import io.definenulls.bitcoincore.network.messages.IMessage
import io.definenulls.bitcoincore.network.messages.IMessageParser
import io.definenulls.bitcoincore.serializers.TransactionSerializer
import io.definenulls.bitcoincore.storage.FullTransaction
class TransactionLockMessage(var transaction: FullTransaction) : IMessage {
override fun toString(): String {
return "TransactionLockMessage(${transaction.header.hash.toReversedHex()})"
}
}
class TransactionLockMessageParser : IMessageParser {
override val command: String = "ix"
override fun parseMessage(input: BitcoinInputMarkable): IMessage {
val transaction = TransactionSerializer.deserialize(input)
return TransactionLockMessage(transaction)
}
}
| 0 | Kotlin | 0 | 0 | bbd7c809a027dd33c1fd393f6a53684d84dcbe14 | 910 | bitcoin-kit-android_s | MIT License |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/BracketCurlyRight.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Bold.BracketCurlyRight: ImageVector
get() {
if (_bracketCurlyRight != null) {
return _bracketCurlyRight!!
}
_bracketCurlyRight = Builder(name = "BracketCurlyRight", defaultWidth = 512.0.dp,
defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(17.56f, 13.06f)
lineToRelative(-1.83f, 1.83f)
curveToRelative(-0.47f, 0.47f, -0.73f, 1.11f, -0.73f, 1.77f)
verticalLineToRelative(1.84f)
curveToRelative(0.0f, 3.03f, -2.47f, 5.5f, -5.5f, 5.5f)
curveToRelative(-0.83f, 0.0f, -1.5f, -0.67f, -1.5f, -1.5f)
reflectiveCurveToRelative(0.67f, -1.5f, 1.5f, -1.5f)
curveToRelative(1.38f, 0.0f, 2.5f, -1.12f, 2.5f, -2.5f)
verticalLineToRelative(-1.84f)
curveToRelative(0.0f, -1.47f, 0.57f, -2.85f, 1.61f, -3.89f)
lineToRelative(0.77f, -0.77f)
lineToRelative(-0.77f, -0.77f)
curveToRelative(-1.04f, -1.04f, -1.61f, -2.42f, -1.61f, -3.89f)
verticalLineToRelative(-1.84f)
curveToRelative(0.0f, -1.38f, -1.12f, -2.5f, -2.5f, -2.5f)
curveToRelative(-0.83f, 0.0f, -1.5f, -0.67f, -1.5f, -1.5f)
reflectiveCurveToRelative(0.67f, -1.5f, 1.5f, -1.5f)
curveToRelative(3.03f, 0.0f, 5.5f, 2.47f, 5.5f, 5.5f)
verticalLineToRelative(1.84f)
curveToRelative(0.0f, 0.66f, 0.27f, 1.3f, 0.73f, 1.77f)
lineToRelative(1.83f, 1.83f)
curveToRelative(0.59f, 0.59f, 0.59f, 1.54f, 0.0f, 2.12f)
close()
}
}
.build()
return _bracketCurlyRight!!
}
private var _bracketCurlyRight: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 2,655 | icons | MIT License |
engine/src/main/java/com/google/android/fhir/sync/remote/GzipUploadInterceptor.kt | google | 247,977,633 | false | {"Kotlin": 3601315, "Shell": 6510, "Java": 454} | /*
* Copyright 2023 Google 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.google.android.fhir.sync.remote
import okhttp3.Interceptor
import okhttp3.MediaType
import okhttp3.RequestBody
import okhttp3.Response
import okio.Buffer
import okio.BufferedSink
import okio.GzipSink
import okio.buffer
const val CONTENT_ENCODING_HEADER_NAME = "Content-Encoding"
/** Compresses upload requests with gzip. */
object GzipUploadInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val uncompressedRequest = chain.request()
if (uncompressedRequest.body == null) {
return chain.proceed(uncompressedRequest)
}
val encodingHeader =
if (uncompressedRequest.header(CONTENT_ENCODING_HEADER_NAME) != null) {
"${uncompressedRequest.header(CONTENT_ENCODING_HEADER_NAME)}, gzip"
} else {
"gzip"
}
val compressedRequest =
uncompressedRequest
.newBuilder()
.header(CONTENT_ENCODING_HEADER_NAME, encodingHeader)
.method(uncompressedRequest.method, addContentLength(gzip(uncompressedRequest.body!!)))
.build()
return chain.proceed(compressedRequest)
}
private fun gzip(body: RequestBody): RequestBody =
object : RequestBody() {
override fun contentType(): MediaType? = body.contentType()
override fun writeTo(sink: BufferedSink) {
val gzipBufferedSink: BufferedSink = GzipSink(sink).buffer()
body.writeTo(gzipBufferedSink)
gzipBufferedSink.close()
}
}
private fun addContentLength(requestBody: RequestBody): RequestBody {
val buffer = Buffer()
requestBody.writeTo(buffer)
return object : RequestBody() {
override fun contentType(): MediaType? = requestBody.contentType()
override fun contentLength(): Long = buffer.size
override fun writeTo(sink: BufferedSink) {
sink.write(buffer.snapshot())
}
}
}
}
| 330 | Kotlin | 288 | 485 | d417dde6c08d0a21b620754400b37e0fe131e679 | 2,465 | android-fhir | Apache License 2.0 |
TripKitData/src/main/java/com/skedgo/tripkit/data/database/locations/bikepods/BikePodRepository.kt | skedgo | 38,415,407 | false | {"Java": 815763, "Kotlin": 434506} | package com.skedgo.tripkit.data.database.locations.bikepods
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.Single
import com.skedgo.tripkit.location.GeoPoint
interface BikePodRepository {
fun saveBikePods(key: String, bikePods: List<BikePodLocationEntity>): Completable
fun getBikePods(cellIds: List<String>): Observable<List<BikePodLocationEntity>>
fun getBikePod(id: String): Single<BikePodLocationEntity>
fun getBikePodsWithinBounds(cellIds: List<String>, southwest: GeoPoint, northEast: GeoPoint): Observable<List<BikePodLocationEntity>>
} | 2 | Java | 3 | 4 | 55fd2ddc7692ccf183499c387bdab32476732bdc | 589 | tripkit-android | Apache License 2.0 |
src/commonMain/kotlin/tile/CornerPipe.kt | glubo | 745,395,684 | false | {"Kotlin": 27463, "Smarty": 1812, "Dockerfile": 377, "Shell": 127} | package tile
import Assets
import Direction
import korlibs.korge.view.SContainer
import korlibs.korge.view.Sprite
import korlibs.korge.view.centered
import korlibs.korge.view.image
import korlibs.korge.view.position
import korlibs.korge.view.rotation
import korlibs.korge.view.size
import korlibs.korge.view.sprite
import korlibs.math.geom.Rectangle
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds
class CornerPipe(
val length: Duration,
val direction: Direction,
) : Tile() {
var elapsed = 0.seconds
var liquidDirection: Direction? = null
var filled = false
lateinit var liquidView: Sprite
lateinit var assets: Assets
lateinit var sContainer: SContainer
lateinit var target: Rectangle
override fun bindView(
target: Rectangle,
assets: Assets,
sContainer: SContainer,
) {
release()
views.add(
sContainer.image(
assets.empty,
) {
position(target.centerX, target.centerY)
centered
size(target.size)
},
)
views.add(
sContainer.image(
assets.corner,
) {
position(target.centerX, target.centerY)
centered
size(target.size)
rotation(angle())
},
)
liquidView = if (direction == liquidDirection) {
sContainer.sprite(
assets.cornerFluidFlipped,
) {
position(target.centerX, target.centerY)
centered
size(target.size)
setFrame(0)
rotation(angle())
}
} else {
sContainer.sprite(
assets.cornerFluid,
) {
position(target.centerX, target.centerY)
centered
size(target.size)
setFrame(0)
rotation(angle())
}
}
views.add(
liquidView,
)
this.assets = assets
this.sContainer = sContainer
this.target = target
}
private fun angle() = direction.angle()
override fun onUpdate(dt: Duration): TileEvent? {
if (liquidDirection != null) {
if (!filled) {
elapsed += dt
}
val elapsedRatio = (elapsed / length).coerceAtMost(0.9999)
val frame = ((liquidView.totalFrames - 1) * elapsedRatio).toInt()
liquidView.setFrame(1 + frame)
if (!filled && liquidDirection != null && elapsed > length) {
filled = true
val outputDirection = validDirections().first { it != liquidDirection }
return Overflow(
elapsed - length,
outputDirection,
1000
)
}
}
return null
}
override fun takeLiquid(
direction: Direction,
dt: Duration,
) = when {
liquidDirection != null -> false
direction.opposite() in validDirections() -> {
liquidDirection = direction.opposite()
bindView(
target, assets, sContainer
)
true
}
else -> false
}
private fun validDirections() = listOf(direction, direction.nextClockwise())
override fun isEditable() = liquidDirection == null
override fun toString(): String {
return "CornerPipe(direction=$direction, elapsed=$elapsed, liquidDirection=$liquidDirection)"
}
}
| 0 | Kotlin | 0 | 0 | acc7a2756a7ecff5126697f66adb7dc151ef8156 | 3,693 | plumbeteer | MIT License |
src/main/kotlin/xveon/roadmap/core/RoadmapMain.kt | XVNexus | 633,999,690 | false | null | package xveon.roadmap.core
import net.fabricmc.api.ModInitializer
import org.slf4j.LoggerFactory
object RoadmapMain : ModInitializer {
val logger = LoggerFactory.getLogger("roadmap")
override fun onInitialize() {
// This code runs as soon as Minecraft is in a mod-load-ready state.
// However, some things (like resources) may still be uninitialized.
// Proceed with mild caution.
logger.info("Initializing roadmap main...")
}
}
| 0 | Kotlin | 0 | 0 | 7edbb7712314f0bd17698ff54209539a8255d809 | 476 | roadmap | Apache License 2.0 |
geary-core/src/commonMain/kotlin/com/mineinabyss/geary/engine/PipelineImpl.kt | MineInAbyss | 306,093,350 | false | {"Kotlin": 324047} | package com.mineinabyss.geary.engine
import com.mineinabyss.geary.addons.GearyPhase
import com.mineinabyss.geary.helpers.fastForEach
import com.mineinabyss.geary.modules.geary
import com.mineinabyss.geary.systems.System
import com.mineinabyss.geary.systems.TrackedSystem
import com.mineinabyss.geary.systems.query.Query
class PipelineImpl : Pipeline {
private val queryManager get() = geary.queryManager
private val onSystemAdd = mutableListOf<(System<*>) -> Unit>()
private val repeatingSystems: MutableSet<TrackedSystem<*>> = mutableSetOf()
private val scheduled = Array(GearyPhase.entries.size) { mutableListOf<() -> Unit>() }
private var currentPhase = GearyPhase.entries.first()
override fun runOnOrAfter(phase: GearyPhase, block: () -> Unit) {
if (currentPhase > phase) block()
else scheduled[phase.ordinal].add(block)
}
override fun onSystemAdd(run: (System<*>) -> Unit) {
onSystemAdd.add(run)
}
override fun runStartupTasks() {
scheduled.fastForEach { actions ->
actions.fastForEach { it() }
}
}
override fun <T : Query> addSystem(system: System<T>): TrackedSystem<*> {
onSystemAdd.fastForEach { it(system) }
val runner = queryManager.trackQuery(system.query)
val tracked = TrackedSystem(system, runner)
if (system.interval != null) {
repeatingSystems.add(tracked)
}
return TrackedSystem(system, runner)
}
override fun addSystems(vararg systems: System<*>) {
systems.fastForEach { addSystem(it) }
}
override fun getRepeatingInExecutionOrder(): Iterable<TrackedSystem<*>> {
return repeatingSystems
}
}
| 12 | Kotlin | 11 | 49 | ef3ecae844043d2650e1f7f4b54f74c4ff99b99b | 1,715 | geary | MIT License |
app/src/main/java/com/breezefieldsalesprolific/features/addshop/model/AddShopResponse.kt | DebashisINT | 858,666,785 | false | {"Kotlin": 15933758, "Java": 1028328} | package com.breezefieldsalesprolific.features.addshop.model
import com.breezefieldsalesprolific.base.BaseResponse
/**
* Created by Pratishruti on 22-11-2017.
*/
class AddShopResponse:BaseResponse() {
val data:AddShopResponseData?=null
} | 0 | Kotlin | 0 | 0 | 5f087f70f683b3c661531f4740db1a223a07b5ff | 244 | PROLIFIC | Apache License 2.0 |
shared/src/commonMain/kotlin/com/kodatos/shared/domain/common/BookPriority.kt | Kodatos | 382,815,535 | false | null | package com.kodatos.shared.domain.common
enum class BookPriority {
HIGH,
MEDIUM,
LOW
} | 0 | Kotlin | 0 | 0 | 375662bdb40888891ce34e3aa40c60fe2db5bd43 | 99 | bookmark | Apache License 2.0 |
url/src/commonTest/kotlin/pw/binom/url/UrlEncoderTest.kt | caffeine-mgn | 773,488,588 | false | {"Kotlin": 33664} | package pw.binom.url
import kotlin.test.Test
import kotlin.test.assertEquals
class UrlEncoderTest {
@Test
fun testEncode() {
assertEquals(
"http%3A%2F%2Fexample.com%2Ftest%3Fff%3Dffff",
UrlEncoder.encode("http://example.com/test?ff=ffff")
)
}
} | 0 | Kotlin | 0 | 0 | ce8a958d2bb6f8fc76844351b7054906b1def2f4 | 299 | kpathes | Apache License 2.0 |
kotlin-mui-icons/src/main/generated/mui/icons/material/NorthWestSharp.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/NorthWestSharp")
package mui.icons.material
@JsName("default")
external val NorthWestSharp: SvgIconComponent
| 10 | null | 5 | 983 | 7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35 | 192 | kotlin-wrappers | Apache License 2.0 |
example/android/app/src/main/kotlin/scientifichackers/com/example/MainActivity.kt | devxpy | 213,067,155 | false | {"Dart": 10314, "Ruby": 2571, "Swift": 404, "Kotlin": 134, "Objective-C": 37} | package scientifichackers.com.example
import io.flutter.embedding.android.FlutterActivity
class MainActivity : FlutterActivity() {}
| 0 | Dart | 1 | 4 | 602019faf6843b884b0876f9898c126545ac405c | 134 | flutter-shared-value | MIT License |
versionPlugin/src/main/java/com/hi/dhl/plugin/DependencyManager.kt | Borninthesun | 272,635,434 | true | {"Kotlin": 6891, "Java": 408} | package com.hi.dhl.plugin
/**
* <pre>
* author: dhl
* date : 2020/6/15
* desc : 如果数量少的话,放在一个类里面就可以,如果数量多的话,可以拆分为多个类
* </pre>
*/
object Versions {
val retrofit = "2.3.0"
val appcompat = "1.1.0"
val coreKtx = "1.3.0"
val constraintlayout = "1.1.3"
val kotlin = "1.3.72"
val koin = "2.1.5"
val junit = "4.12"
val junitExt = "1.1.1"
val espressoCore = "3.2.0"
}
object AndroidX {
val appcompat = "androidx.appcompat:appcompat:${Versions.appcompat}"
val coreKtx = "androidx.core:core-ktx:${Versions.coreKtx}"
val constraintlayout =
"androidx.constraintlayout:constraintlayout:${Versions.constraintlayout}"
}
object kotlinLib {
val stdlibJdk7 = "org.jetbrains.kotlin:kotlin-stdlib-jdk7:${Versions.kotlin}"
val stdlibJdk8 = "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${Versions.kotlin}"
val test = "org.jetbrains.kotlin:kotlin-test-junit:${Versions.kotlin}"
val plugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.kotlin}"
}
object Koin {
val core = "org.koin:koin-core:${Versions.koin}"
val viewmodel = "org.koin:koin-androidx-viewmodel:${Versions.koin}"
}
object Depend {
val retrofit = "com.squareup.retrofit2:retrofit:${Versions.retrofit}"
val junit = "junit:junit:${Versions.junit}"
val androidTestJunit = "androidx.test.ext:junit:${Versions.junitExt}"
val espressoCore = "androidx.test.espresso:espresso-core:${Versions.espressoCore}"
}
| 0 | null | 0 | 0 | a69ae0d896fb5688c3e7d567b3129ce13bb07cc6 | 1,470 | ComposingBuilds-vs-buildSrc | Apache License 2.0 |
libraries/tools/kotlin-gradle-plugin/src/common/kotlin/org/jetbrains/kotlin/gradle/plugin/sources/android/configurator/MultiplatformLayoutV2DependsOnConfigurator.kt | prashant71 | 245,955,054 | false | null | /*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.gradle.plugin.sources.android.configurator
import com.android.build.gradle.api.AndroidSourceSet
import com.android.build.gradle.api.BaseVariant
import org.jetbrains.kotlin.gradle.dsl.kotlinExtension
import org.jetbrains.kotlin.gradle.dsl.multiplatformExtensionOrNull
import org.jetbrains.kotlin.gradle.plugin.KotlinPluginLifecycle
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
import org.jetbrains.kotlin.gradle.plugin.KotlinTargetHierarchy
import org.jetbrains.kotlin.gradle.plugin.launchInStage
import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinAndroidTarget
import org.jetbrains.kotlin.gradle.plugin.mpp.targetHierarchy.orNull
import org.jetbrains.kotlin.gradle.plugin.sources.android.AndroidBaseSourceSetName
import org.jetbrains.kotlin.gradle.plugin.sources.android.AndroidVariantType
import org.jetbrains.kotlin.gradle.plugin.sources.android.type
import org.jetbrains.kotlin.gradle.plugin.sources.android.variantType
import org.jetbrains.kotlin.gradle.utils.lowerCamelCaseName
internal object MultiplatformLayoutV2DependsOnConfigurator : KotlinAndroidSourceSetConfigurator {
override fun configure(target: KotlinAndroidTarget, kotlinSourceSet: KotlinSourceSet, androidSourceSet: AndroidSourceSet) {
val androidBaseSourceSetName = AndroidBaseSourceSetName.byName(androidSourceSet.name) ?: return
setDefaultDependsOn(target, kotlinSourceSet, androidBaseSourceSetName.variantType)
}
override fun configureWithVariant(target: KotlinAndroidTarget, kotlinSourceSet: KotlinSourceSet, variant: BaseVariant) {
setDefaultDependsOn(target, kotlinSourceSet, variant.type)
}
private fun setDefaultDependsOn(target: KotlinAndroidTarget, kotlinSourceSet: KotlinSourceSet, variantType: AndroidVariantType) {
target.project.launchInStage(KotlinPluginLifecycle.Stage.FinaliseRefinesEdges) {
/* Only setup default if not KotlinTargetHierarchy was applied */
if (target.project.multiplatformExtensionOrNull?.internalKotlinTargetHierarchy?.appliedDescriptors.orEmpty().isNotEmpty()) {
return@launchInStage
}
val module = KotlinTargetHierarchy.ModuleName.orNull(target, variantType) ?: return@launchInStage
val commonSourceSetName = lowerCamelCaseName("common", module.name)
val commonSourceSet = target.project.kotlinExtension.sourceSets.findByName(commonSourceSetName) ?: return@launchInStage
kotlinSourceSet.dependsOn(commonSourceSet)
}
}
}
| 1 | null | 1 | 1 | 37bbf447a353fb68e37ff65398f680e2bb8aae77 | 2,750 | kotlin | Apache License 2.0 |
src/main/kotlin/Game.kt | marcelogdomingues | 317,385,314 | false | {"Kotlin": 18719, "Assembly": 38} |
import kotlin.system.exitProcess
fun startGame(){
players()
game()
}
fun game(){
board()
}
//É nesta função que é mostrado o tabuleiro e é onde pede constantemente para cada jogador colocar as coordenadas de partida e de origem.
// Também é aqui que dá a opção de retornar ao menu principal, clicando na tecla “m”.
// É de notar que os argumentos whitePlayer e blackPlayer são os nomes dados pelos utilizador, em que o whitePlayer é o nome do 1o jogador e o blackPlayer é o nome do 2o jogador.
fun startNewGame (whitePlayer: String, blackPlayer: String, pieces : Array<Pair<String, String>?>, totalPiecesAndTurn : Array<Int?>,numColumns: Int,numLines: Int, showLegend: Boolean, showPieces: Boolean){
buildBoard(numColumns = numColumns + 1, numLines = numLines + 1, showLegend = showLegend, showPieces = showPieces, pieces = arrayOfNulls(5))
println("\n" + "Menu-> m;" + "\n")
val userInput = readLine()
if(userInput.toString() == "m" || userInput.toString() == "M"){
menu()
}else if(userInput.toString() == "2"){
exitProcess(1)
}else{
buildBoard(numColumns = numColumns + 1, numLines = numLines + 1, showLegend = showLegend, showPieces = showPieces, pieces = arrayOfNulls(5))
}
}
//Valida se as coordenadas escolhidas estão dentro do tabuleiro.
fun isCoordinateInsideChess (coord: Pair<Int, Int>,numColumns: Int,numLines: Int):Boolean{
return false
}
//A partir de uma string (por exemplo “2a”), esta função converte as coordenadas em números (por exemplo return Pair(2,2) com a string de entrada de “2a”).
// Se as coordenadas forem inválidas, deve retornar null. A String passada deve ser case insensitive, ou seja, aceitar “2a” ou “2A”.
fun getCoordinates (readText: String?): Pair<Int, Int>?{
return null
}
//A partir do tipo de peça e da côr, devolve o Unicode respetivo. Caso a peça e/ou a côr sejam inválidos, deve retornar uma String com um espaço (“ “). Verão que este espaço vai facilitar o desenho do tabuleiro.
fun convertStringToUnicode(piece: String, color: String): String{
return "0"
} | 0 | Kotlin | 0 | 0 | 43c92dfd18ccd5d957d38a75b0de299d4e95c3c3 | 2,101 | fp-chess | MIT License |
app/src/test/java/com/pr656d/cattlenotes/ui/timeline/TimelineViewModelTest.kt | pr656d | 217,208,430 | false | {"Kotlin": 916289} | /*
* Copyright 2020 Cattle Notes. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pr656d.cattlenotes.ui.timeline
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.times
import com.nhaarman.mockito_kotlin.verify
import com.pr656d.androidtest.util.LiveDataTestUtil
import com.pr656d.cattlenotes.test.fakes.data.breeding.FakeBreedingRepository
import com.pr656d.model.Breeding
import com.pr656d.model.BreedingWithCattle
import com.pr656d.shared.data.breeding.BreedingRepository
import com.pr656d.shared.domain.breeding.addedit.UpdateBreedingUseCase
import com.pr656d.shared.domain.timeline.LoadTimelineUseCase
import com.pr656d.test.MainCoroutineRule
import com.pr656d.test.TestData
import com.pr656d.test.runBlockingTest
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Assert.assertNotNull
import org.junit.Rule
import org.junit.Test
import org.hamcrest.Matchers.equalTo as isEqualTo
/**
* Unit tests for [TimelineViewModel].
*/
@ExperimentalCoroutinesApi
class TimelineViewModelTest {
// Executes tasks in the Architecture Components in the same thread
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
// Overrides Dispatchers.Main used in Coroutines
@get:Rule
var coroutineRule = MainCoroutineRule()
private fun createTimelineViewModel(
breedingRepository: BreedingRepository = object : FakeBreedingRepository() {
override fun getAllBreedingWithCattle(): Flow<List<BreedingWithCattle>> =
flowOf(TestData.breedingWithCattleList)
}
): TimelineViewModel {
val coroutineDispatcher = coroutineRule.testDispatcher
return TimelineViewModel(
loadTimelineUseCase = LoadTimelineUseCase(breedingRepository, coroutineDispatcher),
updateBreedingUseCase = UpdateBreedingUseCase(breedingRepository, coroutineDispatcher)
)
}
@Test
fun validateTimelineList() = coroutineRule.runBlockingTest {
val viewModel = createTimelineViewModel()
val breedingWithCattleList = LiveDataTestUtil.getValue(viewModel.timelineList)
assertThat(TestData.validTimelineList, isEqualTo(breedingWithCattleList))
}
@Test
fun saveBreedingCalled_verifySaved() = coroutineRule.runBlockingTest {
val newBreeding = TestData.breedingRHNegativePregnancyCheckNone
val mockBreedingRepository = mock<BreedingRepository> {}
val viewModel = createTimelineViewModel(mockBreedingRepository)
val selectedData = TimelineActionListener.ItemTimelineData(
BreedingWithCattle(
TestData.breedingWithCattle1.cattle,
newBreeding
),
false
)
// Call on option selected.
viewModel.saveBreeding(selectedData)
// Verify update is called.
verify(mockBreedingRepository, times(1)).updateBreeding(newBreeding)
}
@Test
fun saveBreedingCalled_showMessageOnError() = coroutineRule.runBlockingTest {
val newBreeding = TestData.breedingRHNegativePregnancyCheckNone
val viewModel = createTimelineViewModel(
object : FakeBreedingRepository() {
override fun getAllBreedingWithCattle(): Flow<List<BreedingWithCattle>> =
flowOf(TestData.breedingWithCattleList)
override suspend fun updateBreeding(breeding: Breeding) {
throw Exception("Error!")
}
}
)
val selectedData = TimelineActionListener.ItemTimelineData(
BreedingWithCattle(
TestData.breedingWithCattle1.cattle,
newBreeding
),
false
)
// Save called
viewModel.saveBreeding(selectedData)
val showMessage = LiveDataTestUtil.getValue(viewModel.showMessage)
assertNotNull(showMessage?.getContentIfNotHandled())
}
@Test
fun saveBreedingCalledWithAddNewCattle_launchAddNewCattleOnSuccess() =
coroutineRule.runBlockingTest {
val viewModel = createTimelineViewModel()
val cattle = TestData.breedingWithCattle1.cattle
val newBreeding = TestData.breedingRepeatHeatNegative
val selectedData = TimelineActionListener.ItemTimelineData(
BreedingWithCattle(
cattle,
newBreeding
),
false
)
// Save called
viewModel.saveBreeding(itemTimelineData = selectedData, addNewCattle = true)
val launchAddNewCattle = LiveDataTestUtil.getValue(viewModel.launchAddNewCattleScreen)
assertThat(cattle, isEqualTo(launchAddNewCattle?.getContentIfNotHandled()))
}
}
| 0 | Kotlin | 0 | 0 | e375ab87cd75fedec5d457f07b730eee25723f4f | 5,530 | CattleNotes | Apache License 2.0 |
plugins/kotlin/idea/tests/testData/findUsages/kotlin/findClassUsages/kotlinInterfaceDerivedAnonymousObjects.0.kt | ingokegel | 72,937,917 | true | null | // PSI_ELEMENT: org.jetbrains.kotlin.psi.KtClass
// OPTIONS: derivedClasses
// PSI_ELEMENT_AS_TITLE: "interface X"
interface <caret>X {
}
open class A : X {
}
| 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 163 | intellij-community | Apache License 2.0 |
compiler/fir/checkers/src/org/jetbrains/kotlin/fir/analysis/checkers/declaration/FirPropertyAccessorChecker.kt | sab-regime | 358,713,066 | true | null | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.analysis.checkers.declaration
import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext
import org.jetbrains.kotlin.fir.analysis.diagnostics.DiagnosticReporter
import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors
import org.jetbrains.kotlin.fir.analysis.diagnostics.reportOn
import org.jetbrains.kotlin.fir.analysis.diagnostics.withSuppressedDiagnostics
import org.jetbrains.kotlin.fir.declarations.FirProperty
import org.jetbrains.kotlin.fir.types.ConeClassErrorType
import org.jetbrains.kotlin.fir.types.coneType
object FirPropertyAccessorChecker : FirPropertyChecker() {
override fun check(declaration: FirProperty, context: CheckerContext, reporter: DiagnosticReporter) {
checkSetter(declaration, context, reporter)
}
private fun checkSetter(property: FirProperty, context: CheckerContext, reporter: DiagnosticReporter) {
val setter = property.setter ?: return
withSuppressedDiagnostics(setter, context) {
if (property.isVal) {
reporter.reportOn(setter.source, FirErrors.VAL_WITH_SETTER, context)
}
val valueSetterParameter = setter.valueParameters.first()
if (valueSetterParameter.isVararg) {
return
}
val valueSetterType = valueSetterParameter.returnTypeRef.coneType
val valueSetterTypeSource = valueSetterParameter.returnTypeRef.source
val propertyType = property.returnTypeRef.coneType
if (propertyType is ConeClassErrorType || valueSetterType is ConeClassErrorType) {
return
}
if (valueSetterType != propertyType) {
withSuppressedDiagnostics(valueSetterParameter, context) {
reporter.reportOn(valueSetterTypeSource, FirErrors.WRONG_SETTER_PARAMETER_TYPE, propertyType, valueSetterType, context)
}
}
}
}
}
| 1 | null | 1 | 1 | 81a5ae778082a7b70188a28ed483a02977d4bcc3 | 2,180 | kotlin | Apache License 2.0 |
kotlinx-coroutines-core/jvm/test/NoParamAssertionsTest.kt | Kotlin | 61,722,736 | false | null | package kotlinx.coroutines
import kotlinx.coroutines.testing.*
import kotlinx.coroutines.*
import org.junit.Test
import kotlin.test.*
class NoParamAssertionsTest : TestBase() {
// These tests verify that we haven't omitted "-Xno-param-assertions" and "-Xno-receiver-assertions"
@Test
fun testNoReceiverAssertion() {
val function: (ThreadLocal<Int>, Int) -> ThreadContextElement<Int> = ThreadLocal<Int>::asContextElement
@Suppress("UNCHECKED_CAST")
val unsafeCasted = function as ((ThreadLocal<Int>?, Int) -> ThreadContextElement<Int>)
unsafeCasted(null, 42)
}
@Test
fun testNoParamAssertion() {
val function: (ThreadLocal<Any>, Any) -> ThreadContextElement<Any> = ThreadLocal<Any>::asContextElement
@Suppress("UNCHECKED_CAST")
val unsafeCasted = function as ((ThreadLocal<Any?>?, Any?) -> ThreadContextElement<Any>)
unsafeCasted(ThreadLocal.withInitial { Any() }, null)
}
}
| 295 | null | 1850 | 13,033 | 6c6df2b850382887462eeaf51f21f58bd982491d | 971 | kotlinx.coroutines | Apache License 2.0 |
kandy-lets-plot/src/main/kotlin/org/jetbrains/kotlinx/kandy/letsplot/layers/area.kt | Kotlin | 502,039,936 | false | null | /*
* Copyright 2020-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package org.jetbrains.kotlinx.kandy.letsplot.layers
import org.jetbrains.kotlinx.kandy.dsl.internal.LayerCollectorContext
import org.jetbrains.kotlinx.kandy.letsplot.internal.LetsPlotGeom
import org.jetbrains.kotlinx.kandy.letsplot.layers.context.AreaContext
@PublishedApi
internal val AREA: LetsPlotGeom = LetsPlotGeom("area")
/**
* Adds a new area layer.
*
* Creates a context in which you can configure layer. Within it, you can set mappings and settings
* on aesthetic attributes. Mappings allow you to set a relationship between data and attribute values,
* while settings allow you to assign a constant value to the attributes.
*
* Mapping can be performed via method with name of corresponding aes.
* Setting for non-positional attributes can be performed with simple assignment of variable with name of aes.
* Setting for positional attributes can be performed with `.constant()` method of special property with
* the same name as the attribute.
*
* Area aesthetics:
* * `x`
* * `y`
* * `fillColor`
* * `alpha`
* * `borderLine.color`
* * `borderLine.width`
* * `borderLine.type`
*
* Example:
*
* ```
* area {
* // positional mapping
* x(time) {
* ... // some mapping parameters
* }
*
* // non-positional settings
* alpha = 0.8
* borderLine.width = 2.5
* borderLine {
* color = Color.BLACK
* }
* // non-positional mapping
* fillColor("type")
*
* // position adjustment
* position = Position.Stack
* }
* ```
*/
public inline fun LayerCollectorContext.area(block: AreaContext.() -> Unit) {
addLayer(AreaContext(this).apply(block), AREA)
}
| 79 | Kotlin | 0 | 98 | fd613edc4dd37aac0d0ecdb4245a770e09617fc7 | 1,751 | kandy | Apache License 2.0 |
app/src/main/java/com/userapp/di/Components/AppComponent.kt | zumrywahid | 140,339,325 | false | {"Kotlin": 25522} | package com.userapp.di.Components
import android.app.Application
import com.userapp.common.UserApplication
import com.userapp.di.Modules.ActivityBindingModule
import com.userapp.di.Modules.AppModule
import com.userapp.di.Modules.ApplicationModule
import com.userapp.ui.login.LoginModule
import dagger.BindsInstance
import dagger.Component
import dagger.android.AndroidInjector
import dagger.android.support.AndroidSupportInjectionModule
import javax.inject.Singleton
/**
* Created on 7/7/18.
*/
@Singleton
@Component(modules =
[
AndroidSupportInjectionModule::class,
ApplicationModule::class,
AppModule::class,
ActivityBindingModule::class
]
)
interface AppComponent: AndroidInjector<UserApplication> {
@Component.Builder
interface Builder {
@BindsInstance
fun application(application: Application): AppComponent.Builder
fun build(): AppComponent
}
} | 0 | Kotlin | 0 | 2 | 0e8df5b4ebe074c764a79916e3794e8f45ef6be6 | 907 | UserManagementApp | Apache License 2.0 |
core/ui/src/main/java/org/expenny/core/ui/foundation/ExpennyDialog.kt | expenny-application | 712,607,222 | false | {"Kotlin": 922194} | package org.expenny.core.ui.foundation
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.window.DialogProperties
@Composable
fun ExpennyDialog(
modifier: Modifier = Modifier,
title: (@Composable () -> Unit)?,
content: @Composable (() -> Unit)? = null,
icon: (@Composable () -> Unit)? = null,
dismissButton: @Composable (() -> Unit)? = null,
confirmButton: @Composable () -> Unit,
dialogProperties: DialogProperties = DialogProperties(),
onDismissRequest: () -> Unit,
) {
AlertDialog(
modifier = modifier,
icon = icon,
title = title,
text = content,
properties = dialogProperties,
onDismissRequest = onDismissRequest,
dismissButton = dismissButton,
confirmButton = confirmButton,
containerColor = MaterialTheme.colorScheme.surfaceContainer,
iconContentColor = MaterialTheme.colorScheme.primary,
textContentColor = MaterialTheme.colorScheme.onSurface,
titleContentColor = MaterialTheme.colorScheme.onSurface,
shape = MaterialTheme.shapes.medium,
)
} | 1 | Kotlin | 0 | 1 | 70c031934341ea3b9a6120680674fd8805c7321e | 1,243 | expenny-android | Apache License 2.0 |
Audio/app/src/main/java/utils/OnItemClicked.kt | RamzyK | 247,684,123 | false | null | package utils
import network.model.albums.Albums
interface OnItemClicked {
fun albumClicked(album: Albums, type: Int)
} | 0 | Kotlin | 0 | 0 | 47c2d5b8c459aa2fa080bf98ce4b7032f760de13 | 125 | Deezer | MIT License |
src/main/java/com/github/kisaragieffective/opencommandblock/enums/CommandBlockType.kt | KisaragiArchive | 174,288,842 | false | {"Kotlin": 119308} | package com.github.kisaragieffective.opencommandblock.enums
enum class CommandBlockType(val humanReadable: String) {
IMPLUSE("impluse"),
CHAIN("chain"),
REPEAT("repeat"),
;
override fun toString(): String {
return humanReadable
}
} | 13 | Kotlin | 0 | 0 | 7f78beb8e628ac4c8ac0991d2648412cd989edc0 | 266 | OpenCommandBlock | MIT License |
kotlin-native/build-tools/src/main/kotlin/org/jetbrains/kotlin/utils/Maybe.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.utils
/**
* Wrapper over [T]?.
*
* Useful for some generalized functions that you want to pass [T]? into, but they forbid nullable types.
* For example, [ObjectFactory.newInstance][org.gradle.api.model.ObjectFactory.newInstance] cannot be used
* to construct a type that has [T]? as a constructor argument.
*
* @property orNull get underlying value.
*/
data class Maybe<T>(val orNull: T?)
/**
* Construct [Maybe]<[T]> from [T]?.
*/
inline val <T> T?.asMaybe
get() = Maybe(this)
| 157 | Kotlin | 5209 | 42,102 | 65f712ab2d54e34c5b02ffa3ca8c659740277133 | 733 | kotlin | Apache License 2.0 |
mojito/src/main/java/net/mikaelzero/mojito/Mojito.kt | mikaelzero | 156,349,533 | false | null | package net.mikaelzero.mojito
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import net.mikaelzero.mojito.bean.ActivityConfig
import net.mikaelzero.mojito.impl.DefaultMojitoConfig
import net.mikaelzero.mojito.interfaces.IMojitoConfig
import net.mikaelzero.mojito.interfaces.ImageViewLoadFactory
import net.mikaelzero.mojito.loader.ImageLoader
import net.mikaelzero.mojito.tools.DataWrapUtil
import net.mikaelzero.mojito.ui.ImageMojitoActivity
import java.lang.ref.WeakReference
class Mojito {
companion object {
@JvmStatic
fun initialize(
imageLoader: ImageLoader,
imageViewLoadFactory: ImageViewLoadFactory
) {
MojitoLoader.instance.mImageLoader = imageLoader
MojitoLoader.instance.imageViewLoadFactory = imageViewLoadFactory
}
@JvmStatic
fun initialize(
imageLoader: ImageLoader,
imageViewLoadFactory: ImageViewLoadFactory,
mojitoConfig: IMojitoConfig
) {
MojitoLoader.instance.mImageLoader = imageLoader
MojitoLoader.instance.imageViewLoadFactory = imageViewLoadFactory
MojitoLoader.instance.mojitoConfig = mojitoConfig
}
@JvmStatic
fun imageLoader(): ImageLoader? {
return MojitoLoader.instance.mImageLoader
}
@JvmStatic
fun imageViewFactory(): ImageViewLoadFactory? {
return MojitoLoader.instance.imageViewLoadFactory
}
@JvmStatic
fun mojitoConfig(): IMojitoConfig {
if (MojitoLoader.instance.mojitoConfig == null) {
MojitoLoader.instance.mojitoConfig = DefaultMojitoConfig()
}
return MojitoLoader.instance.mojitoConfig!!
}
@JvmStatic
fun cleanCache() {
MojitoLoader.instance.mImageLoader?.cleanCache()
}
fun clean() {
DataWrapUtil.remove()
imageLoader()?.cancelAll()
}
fun start(context: Context?, builder: MojitoBuilder.() -> Unit = {}) {
val configBean = MojitoBuilder().apply(builder).build()
ImageMojitoActivity.hasShowedAnimMap[configBean.position] = false
DataWrapUtil.put(configBean)
val activity = scanForActivity(context)
val intent = Intent(activity, ImageMojitoActivity::class.java)
activity?.startActivity(intent)
activity?.overridePendingTransition(0, 0)
}
fun finish() {
currentActivity?.get()?.backToMin()
}
private fun scanForActivity(context: Context?): Activity? {
if (context == null) return null
if (context is Activity) {
return context
} else if (context is ContextWrapper) {
return scanForActivity(context.baseContext)
}
return null
}
var currentActivity: WeakReference<ImageMojitoActivity>? = null
}
} | 10 | null | 164 | 1,508 | 3d773f3e9236e6816a5bbbace318c6a87c7f89f2 | 3,086 | mojito | Apache License 2.0 |
src/mobile/app/src/main/java/com/duckest/duckest/ui/home/feed/adapter/TestItem.kt | Duckest | 340,424,151 | false | null | package com.duckest.duckest.ui.home.feed.adapter
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
class TestItem(
@StringRes
val title: Int,
@DrawableRes
val icon: Int,
var done: Boolean = false
) | 1 | null | 1 | 1 | b84b61e5a76387c5bc690b0490a4d8dcbc9dce21 | 245 | Duckest | MIT License |
flaircore/src/main/java/com/rasalexman/flaircore/interfaces/ICommand.kt | Rasalexman | 134,755,003 | false | null | package com.rasalexman.flaircore.interfaces
/**
* Created by a.minkin on 21.11.2017.
*/
interface ICommand : IMultitonKey {
/**
* Execute the ICommand's logic to handle a given INotification
*
* @param notification - an INotification to handle.
*/
fun execute(notification: INotification)
} | 1 | Kotlin | 6 | 31 | bb4325e958993d8a51f91361080ef6a30018c4b0 | 321 | Flair | The Unlicense |
les/src/main/kotlin/org/apache/tuweni/les/ReceiptsMessage.kt | Consensys | 693,991,624 | true | {"SVG": 2, "Java Properties": 2, "Markdown": 64, "Gradle": 64, "Shell": 3, "EditorConfig": 1, "YAML": 13760, "Git Attributes": 1, "Batchfile": 1, "Text": 33, "Ignore List": 2, "Git Config": 1, "Kotlin": 393, "TOML": 8, "Java": 443, "XML": 18, "JSON": 17343, "JavaScript": 4, "CSS": 1, "HTML": 8, "SQL": 5, "INI": 3, "ANTLR": 2, "Public Key": 1, "Dockerfile": 2} | // Copyright The Tuweni Authors
// SPDX-License-Identifier: Apache-2.0
package org.apache.tuweni.les
import org.apache.tuweni.bytes.Bytes
import org.apache.tuweni.eth.TransactionReceipt
import org.apache.tuweni.rlp.RLP
internal data class ReceiptsMessage(
val reqID: Long,
val bufferValue: Long,
val receipts: List<List<TransactionReceipt>>,
) {
fun toBytes(): Bytes {
return RLP.encodeList { writer ->
writer.writeLong(reqID)
writer.writeLong(bufferValue)
writer.writeList(receipts) {
eltWriter, listOfReceipts ->
eltWriter.writeList(listOfReceipts) {
txWriter, txReceipt ->
txReceipt.writeTo(txWriter)
}
}
}
}
companion object {
fun read(bytes: Bytes): ReceiptsMessage {
return RLP.decodeList(
bytes,
) { reader ->
ReceiptsMessage(
reader.readLong(),
reader.readLong(),
reader.readListContents { listTx -> listTx.readListContents { TransactionReceipt.readFrom(it) } },
)
}
}
}
}
| 1 | Java | 2 | 0 | d780a654afc90f5fd3c16540d592259487e0a190 | 1,060 | tuweni | Apache License 2.0 |
core/src/main/java/app/allever/android/lib/core/function/permission/WhyRequestPermissionDialog.kt | devallever | 446,030,743 | false | {"Gradle": 25, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 24, "Batchfile": 1, "Markdown": 3, "INI": 23, "Proguard": 23, "XML": 153, "Kotlin": 352, "Java": 115, "JSON": 1} | package app.allever.android.lib.core.function.permission
import android.content.Context
import android.widget.TextView
import app.allever.android.lib.core.R
class WhyRequestPermissionDialog(
context: Context,
title: String? = "获取权限",
message: String? = "使用更多功能",
val requestTask: Runnable? = null
) :
PermissionDialog(context, title, message) {
override fun initView() {
super.initView()
findViewById<TextView>(R.id.tvConfirm).text = "确定"
}
override fun onClickConfirm() {
requestTask?.run()
}
} | 1 | Java | 8 | 52 | b5ec21078c8a6f509822c763fc90d6106b64bde3 | 560 | AndroidBaseLibs | Apache License 2.0 |
compiler/testData/codegen/box/objects/kt3238.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | // TARGET_BACKEND: JVM
// TARGET_BACKEND: JVM_IR
// WITH_STDLIB
object Obj {
class Inner() {
fun ok() = "OK"
}
}
fun box() : String {
val klass = Obj.Inner::class.java
val cons = klass.getConstructors()!![0]
val inner = cons.newInstance(*(arrayOfNulls<String>(0) as Array<String>))
return "OK"
}
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 330 | kotlin | Apache License 2.0 |
app/src/main/java/com/albineli/udacity/popularmovies/repository/RepositoryBase.kt | hbsis-luanalbineli | 108,592,583 | false | null | package com.albineli.udacity.popularmovies.repository
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
abstract class RepositoryBase {
protected fun <T> observeOnMainThread(observable: Observable<T>): Observable<T> {
return observable.observeOn(AndroidSchedulers.mainThread())
}
protected fun observeOnMainThread(completable: Completable): Completable {
return completable.observeOn(AndroidSchedulers.mainThread())
}
}
| 1 | null | 1 | 1 | 844535a3dc84c6dbd97930d7fa74854134341e97 | 526 | popularmovies | Apache License 2.0 |
android/versioned-abis/expoview-abi45_0_0/src/main/java/abi45_0_0/expo/modules/sharing/SharingPackage.kt | amandeepmittal | 507,944,343 | false | {"Gemfile.lock": 1, "YAML": 111, "Git Config": 2, "JSON with Comments": 144, "Ignore List": 216, "JSON": 989, "Markdown": 1261, "JavaScript": 1601, "Text": 56, "Git Attributes": 7, "Shell": 136, "Ruby": 222, "TSX": 752, "Gradle": 108, "Java Properties": 6, "Batchfile": 7, "INI": 9, "Starlark": 358, "Proguard": 13, "XML": 367, "Java": 2879, "C++": 4294, "Makefile": 194, "Dotenv": 7, "OpenStep Property List": 28, "Objective-C": 6744, "Objective-C++": 673, "Diff": 19, "CODEOWNERS": 1, "Kotlin": 2689, "CMake": 123, "C": 364, "Graphviz (DOT)": 1, "Unix Assembly": 21, "Motorola 68K Assembly": 3, "Swift": 723, "Jest Snapshot": 157, "HTML": 5, "MATLAB": 4, "Checksums": 6, "GraphQL": 19, "robots.txt": 1, "SVG": 5, "CSS": 2, "Cloud Firestore Security Rules": 1} | package abi45_0_0.expo.modules.sharing
import android.content.Context
import abi45_0_0.expo.modules.core.BasePackage
class SharingPackage : BasePackage() {
override fun createExportedModules(context: Context) =
listOf(SharingModule(context))
}
| 1 | null | 1 | 1 | 8fe49195a63f665ce9cab8c0aca294acb0d6ff56 | 252 | expo | MIT License |
examples/hello-ktor/src/main/kotlin/org/koin/sample/Components.kt | InsertKoinIO | 93,515,203 | false | {"Kotlin": 825588, "Java": 4138, "Shell": 259} | package org.koin.sample
import org.koin.sample.Counter.init
import java.util.UUID
class HelloRepository {
fun getHello(): String = "Ktor & Koin"
}
interface HelloService {
fun sayHello(): String
}
object Counter {
var init = 0
}
class HelloServiceImpl(val helloRepository: HelloRepository) : HelloService {
init {
println("created at start")
init++
}
override fun sayHello() = "Hello ${helloRepository.getHello()}!"
}
class HelloService2() : HelloService{
override fun sayHello() = "Hello Again!"
}
class ScopeComponent {
val id = UUID.randomUUID().toString()
} | 105 | Kotlin | 711 | 8,934 | f870a02fd32a2cf1ff8b69406ebf555c26ffe39f | 616 | koin | Apache License 2.0 |
nodecore-spv/src/test/java/veriblock/lite/core/MerklePathTests.kt | paucasafont | 270,580,517 | false | {"INI": 2, "Gradle Kotlin DSL": 20, "Shell": 1, "Markdown": 7, "Batchfile": 1, "Kotlin": 316, "Java": 431, "Dockerfile": 4, "Java Properties": 1} | // VeriBlock Blockchain Project
// Copyright 2017-2018 VeriBlock, Inc
// Copyright 2018-2020 <NAME>
// All rights reserved.
// https://www.veriblock.org
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
package veriblock.lite.core
import org.junit.Assert
import org.junit.Test
import org.veriblock.core.crypto.Sha256Hash
import veriblock.model.MerkleBranch
import java.util.*
class MerklePathTests {
@Test
fun verify() {
val subject = Sha256Hash.wrap(
"C929570584BEB05F69B974ABAA5E742FC37AC0001F35E0EBB0B8C8E2FEBFB418"
)
val path = listOf(
Sha256Hash.wrap("0000000000000000000000000000000000000000000000000000000000000000"),
Sha256Hash.wrap("953855AD90E483B0492E812CD0581D82F0514675732C24D054AC473EB689D110")
)
val merklePath = MerkleBranch(0, subject, path, true)
Assert.assertTrue(
merklePath.verify(Sha256Hash.wrap("9610685BCE24913B2C8562A95A8A4248B216B3ECA4F6D6D0", 24))
)
}
@Test
fun verifyWhenFourRegularTransactionsAndPositionThree() {
val subject = Sha256Hash.wrap(
"C929570584BEB05F69B974ABAA5E742FC37AC0001F35E0EBB0B8C8E2FEBFB418"
)
val path = listOf(
Sha256Hash.wrap("F8D22055FDADA935C8977DF3105E014C4E5862EA2FA3E0C37805D00445377932"),
Sha256Hash.wrap("2328CD579BFAA48229689CAEC41504FC510C81E458FE9097466A728B5390E0DE"),
Sha256Hash.wrap("0000000000000000000000000000000000000000000000000000000000000000"),
Sha256Hash.wrap("953855AD90E483B0492E812CD0581D82F0514675732C24D054AC473EB689D110")
)
val merklePath = MerkleBranch(3, subject, path, true)
Assert.assertTrue(
merklePath.verify(Sha256Hash.wrap("9D5EC2CEB02657B9B2A74A188FE6C593BABE07B297B99F200DFD065906D35795"))
)
}
@Test
fun verifyWhenFourRegularTransactionsAndPositionTwo() {
val subject = Sha256Hash.wrap(
"C929570584BEB05F69B974ABAA5E742FC37AC0001F35E0EBB0B8C8E2FEBFB418"
)
val path = listOf(
Sha256Hash.wrap("F8D22055FDADA935C8977DF3105E014C4E5862EA2FA3E0C37805D00445377932"),
Sha256Hash.wrap("2328CD579BFAA48229689CAEC41504FC510C81E458FE9097466A728B5390E0DE"),
Sha256Hash.wrap("0000000000000000000000000000000000000000000000000000000000000000"),
Sha256Hash.wrap("953855AD90E483B0492E812CD0581D82F0514675732C24D054AC473EB689D110")
)
val merklePath = MerkleBranch(2, subject, path, true)
Assert.assertTrue(
merklePath.verify(Sha256Hash.wrap("9BBAE0AACC6DD72146C5612B3C625208AFD27EB7F61A3A0FB7D660CA63EF5671"))
)
}
}
| 1 | null | 1 | 1 | 904f69339e8e152ac54f8f5a63aea6eddfaba27b | 2,777 | nodecore | MIT License |
term4/dsa/practice/practice2/MixBoyerMoore.kt | nsidnev | 115,162,522 | false | {"C": 118714, "C++": 50420, "Java": 23083, "Dart": 12683, "Kotlin": 11536, "Python": 8072, "Makefile": 5695, "Objective-C": 2259, "HTML": 904} | package dsa.practice.second
import java.util.ArrayList
import java.util.HashMap
object MixBoyerMoore {
fun match(pattern: String, text: String): List<Int> {
val matches = ArrayList<Int>()
val m = text.length
val n = pattern.length
var iter = 0
val rightMostIndexes = preprocessMixForBadCharacterShift(pattern)
var alignedAt = 0
while (alignedAt + (n - 1) < m) {
for (indexInPattern in n - 1 downTo 0) {
val indexInText = alignedAt + indexInPattern
val x = text[indexInText]
val y = pattern[indexInPattern]
if (indexInText >= m) break
if (x != y) {
val r = rightMostIndexes[x]
if (r == null) {
alignedAt = indexInText + 1
} else {
val shift = indexInText - (alignedAt + r)
alignedAt += if (shift > 0) shift else 1
}
break
} else if (indexInPattern == 0) {
matches.add(alignedAt)
alignedAt++
}
}
iter++
}
print("\nNumber of MIX BOYER Iterations: $iter")
return matches
}
fun getMixIndexArray(stringImage: String): IntArray {
var table = IntArray(stringImage.length)
table[0] = 0
for (i in 1 until table.size) {
var k = table[i - 1]
while (stringImage[k] != stringImage[i] && k > 0) {
k = table[k - 1]
}
if (stringImage[k] == stringImage[i]) {
table[i] = ++k
} else {
table[i] = 0
}
}
print("\nKnuth-like table:\n ")
for (i in table) {
print(" $i")
}
return table
}
private fun preprocessMixForBadCharacterShift(pattern: String): Map<Char, Int> {
val map = HashMap<Char, Int>()
for (i in pattern.length - 1 downTo 0) {
val c = pattern[i]
if (!map.containsKey(c)) map[c] = i
}
return map
}
}
| 0 | C | 0 | 0 | b2f5963811e0e4225ccabf1225eb7a3e06e7aeb7 | 2,215 | mirea | MIT License |
buildSrc/src/main/kotlin/ru/surfstudio/android/build/tasks/generate_release_notes_diff/WriteToFileReleaseNotesDiff.kt | surfstudio | 175,407,898 | false | null | package ru.surfstudio.android.build.tasks.generate_release_notes_diff
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import ru.surfstudio.android.build.Components
import ru.surfstudio.android.build.GradleProperties
import ru.surfstudio.android.build.ReleaseNotes
import ru.surfstudio.android.build.exceptions.component.ComponentNotFoundException
import ru.surfstudio.android.build.model.Component
import ru.surfstudio.android.build.tasks.changed_components.GitCommandRunner
import ru.surfstudio.android.build.utils.EMPTY_STRING
import java.io.File
/**
* Task to see the differences between two revisions of RELEASE_NOTES.md in each module of a project.
*/
open class WriteToFileReleaseNotesDiff: DefaultTask() {
companion object {
const val RELEASE_NOTES_CHANGES_FILE_URL = "buildSrc/build/tmp/releaseNotesChanges.txt"
}
private lateinit var componentName: String
private lateinit var revisionToCompare: String
private lateinit var currentRevision: String
private var releaseNotesChanges = ""
private val gitRunner: GitCommandRunner = GitCommandRunner()
@TaskAction
fun generate() {
extractInputArguments()
if (componentName.isNotEmpty()) {
val component = findComponent()
generateComponentDiff(component)
} else {
Components.value.forEach(::generateComponentDiff)
}
writeChangesToFile()
}
protected open fun addLineChange(change: String) {
releaseNotesChanges += change + "\n"
}
private fun findComponent(): Component =
Components.value.find { it.name == componentName }
?: throw ComponentNotFoundException(componentName)
private fun generateComponentDiff(component: Component) {
val rawDiff = extractRawDiff(component)
val diffs = parseRawDiff(rawDiff)
if (diffs.isNotEmpty()) addLineChange(component.name)
writeDiff(diffs)
if (diffs.isNotEmpty()) println()
}
private fun writeChangesToFile() {
val file = File(RELEASE_NOTES_CHANGES_FILE_URL)
with(file) {
if (exists()) {
delete()
}
createNewFile()
appendText(releaseNotesChanges)
}
}
private fun writeDiff(diffs: List<GitDiff>) {
var prev: GitDiff? = null
diffs.forEach { diff ->
writeLine(diff, prev)
prev = diff
}
}
private fun writeLine(diff: GitDiff, prev: GitDiff?) {
val paddingSpaces = getSpaces(diff.lineNumber)
val lineToPrint = when {
prev == null -> return
diff.type == GitDiff.Type.SEPARATE -> "..."
else -> "${diff.lineNumber}$paddingSpaces${diff.line}"
}
addLineChange(lineToPrint)
}
private fun parseRawDiff(diff: String): List<GitDiff> = SimpleGitDiffParser().parse(diff)
.filter {
val lineWithoutPlusAndMinus = it.line.trim()
.replace("+", EMPTY_STRING)
.replace("-", EMPTY_STRING)
lineWithoutPlusAndMinus != EMPTY_STRING
}
private fun extractRawDiff(component: Component): String {
val filePath = ReleaseNotes.getReleaseNotesFilePath(component)
return gitRunner.getDiffWithoutSpace(currentRevision, revisionToCompare, filePath) ?: ""
}
/**
* Simple padding method which adds spaces according to line length
*/
private fun getSpaces(currentLine: Int): String {
val space = " "
val spacesCount = when {
currentLine / 10 == 0 -> 3
currentLine / 100 == 0 -> 2
else -> 1
}
return space.repeat(spacesCount)
}
private fun extractInputArguments() {
componentName = if (!project.hasProperty(GradleProperties.COMPONENT)) {
EMPTY_STRING
} else {
project.findProperty(GradleProperties.COMPONENT) as String
}
revisionToCompare = if (!project.hasProperty(GradleProperties.COMPONENTS_CHANGED_REVISION_TO_COMPARE)) {
EMPTY_STRING
} else {
project.findProperty(GradleProperties.COMPONENTS_CHANGED_REVISION_TO_COMPARE) as String
}
currentRevision = if (project.hasProperty(GradleProperties.CURRENT_REVISION)) {
project.findProperty(GradleProperties.CURRENT_REVISION) as String
} else {
gitRunner.getCurrentRevisionShort()
}
}
} | 1 | null | 2 | 27 | 5f68262ac148bc090c600121295f81c7ce3486c0 | 4,552 | EasyAdapter | Apache License 2.0 |
plugins/gitlab/src/org/jetbrains/plugins/gitlab/authentication/accounts/GitLabPersistentAccounts.kt | opticyclic | 5,859,423 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gitlab.authentication.accounts
import com.intellij.collaboration.auth.AccountsRepository
import com.intellij.openapi.components.SerializablePersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.util.SimpleModificationTracker
import kotlinx.serialization.Serializable
@State(name = "GitLabAccounts", storages = [Storage(value = "gitlab.xml")], reportStatistic = false)
internal class GitLabPersistentAccounts
: AccountsRepository<GitLabAccount>,
SerializablePersistentStateComponent<GitLabPersistentAccounts.GitLabAccountsState>(GitLabAccountsState()) {
@Serializable
data class GitLabAccountsState(var accounts: Set<GitLabAccount> = setOf())
private val tracker = SimpleModificationTracker()
override var accounts: Set<GitLabAccount>
get() = state.accounts.toSet()
set(value) {
state.accounts = value.toSet()
tracker.incModificationCount()
}
override fun getStateModificationCount(): Long = tracker.modificationCount
} | 1 | null | 1 | 1 | 838997d4d208d92c823cd1919827690be8def9be | 1,206 | intellij-community | Apache License 2.0 |
src/main/kotlin/biodivine/algebra/ia/Interval.kt | daemontus | 160,796,526 | false | null | package biodivine.algebra.ia
import biodivine.algebra.NumQ
import biodivine.algebra.rootisolation.Root
import cc.redberry.rings.Rational
import cc.redberry.rings.Rings
import cc.redberry.rings.bigint.BigDecimal
import cc.redberry.rings.bigint.BigInteger
import biodivine.algebra.rootisolation.compareTo
import kotlin.math.max
import kotlin.math.min
data class Interval(
val low: NumQ, val high: NumQ
) {
init {
if (low > high) error("Empty interval [$low,$high]")
}
constructor(low: Int, high: Int) : this(
NumQ(Rings.Q.ring, BigInteger.valueOf(low)),
NumQ(Rings.Q.ring, BigInteger.valueOf(high))
)
val size: NumQ
get() = high - low
val hasZero: Boolean
get() = low <= Rings.Q.zero && high >= Rings.Q.zero
val center: NumQ
get() = low + size/2
operator fun plus(that: Interval): Interval {
return Interval(this.low + that.low, this.high + that.high)
}
operator fun minus(that: Interval): Interval {
return Interval(this.low - that.high, this.high - that.low)
}
operator fun times(that: Interval): Interval {
val (x1, x2) = this
val (y1, y2) = that
val x1y1 = x1 * y1
val x1y2 = x1 * y2
val x2y1 = x2 * y1
val x2y2 = x2 * y2
return Interval(
low = min(min(x1y1, x1y2), min(x2y1,x2y2)),
high = max(max(x1y1, x1y2), max(x2y1,x2y2))
)
}
operator fun div(that: Interval): Interval {
if (that.low.signum() != that.high.signum()) error("Zero in division $this / $that")
val (y1, y2) = that
return this * Interval(
NumQ(y2.ring, y2.denominator(), y2.numerator()),
NumQ(y1.ring, y1.denominator(), y1.numerator())
)
}
operator fun times(that: NumQ): Interval {
return if (that < Rings.Q.zero) {
Interval(high * that, low * that)
} else {
Interval(low * that, high * that)
}
}
infix fun intersects(that: Interval): Boolean = this.high >= that.low && this.low <= that.high
infix fun intersect(that: Interval): Interval? {
val low = if (this.low < that.low) that.low else this.low
val high = if (this.high < that.high) this.high else that.high
return Interval(low, high)
}
operator fun contains(num: NumQ): Boolean = this.low <= num && num <= this.high
operator fun contains(root: Root): Boolean = this.low <= root && root <= this.high
fun isNumber(): Boolean = this.low == this.high
}
operator fun NumQ.plus(that: NumQ): NumQ = this.add(that)
operator fun NumQ.times(that: NumQ): NumQ = this.multiply(that)
operator fun NumQ.minus(that: NumQ): NumQ = this.subtract(that)
operator fun NumQ.times(that: Interval) = Interval(this * that.low, this * that.high)
operator fun NumQ.unaryMinus(): NumQ = this.negate()
operator fun NumQ.div(that: Int): NumQ = this.divide(BigInteger.valueOf(that))
operator fun NumQ.times(that: Int): NumQ = this.multiply(BigInteger.valueOf(that))
operator fun NumQ.div(that: NumQ) = this.divide(that)
fun min(a: NumQ, b: NumQ): NumQ {
return if (a < b) a else b
}
fun max(a: NumQ, b: NumQ): NumQ {
return if (a > b) a else b
}
fun NumQ.decimalString(): String {
return BigDecimal(this.numerator()).divide(BigDecimal(this.denominator())).toString()
} | 1 | null | 1 | 1 | ed4fd35015b73ea3ac36aecb1c5a568f6be7f14c | 3,372 | biodivine-algebraic-toolkit | MIT License |
ext/src/main/kotlin/me/jiangcai/common/ext/boot/ApplicationHolder.kt | mingshz | 166,675,112 | false | {"Gradle": 20, "INI": 11, "Shell": 2, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 10, "XML": 8, "Kotlin": 311, "JavaScript": 1, "HTML": 4, "Java Properties": 10, "Java": 71, "JSON": 2} | package me.jiangcai.common.ext.boot
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.SpringApplication
import org.springframework.boot.runApplication
import org.springframework.context.ConfigurableApplicationContext
/**
* 可以管理一个 spring boot 的实例,比如实施重启等操作。
* 用法如下:
* ```kotlin
* fun main(args: Array<String>) {
* ApplicationHolder.start<Application>(args)
* }
* ```
* @author CJ
*/
@Suppress("unused")
class ApplicationHolder {
companion object {
var context: ConfigurableApplicationContext? = null
var lastAppClass: Class<*>? = null
inline fun <reified T : Any> start(args: Array<String>) {
context = runApplication<T>(*args)
lastAppClass = T::class.java
}
/**
* 重新启动
*/
fun restart() {
if (context == null || lastAppClass == null)
throw RuntimeException("必须使用, ApplicationHolder.start() 方式启动应用。")
val args = context!!.getBean(ApplicationArguments::class.java)
val thread = Thread {
context?.close()
context = SpringApplication.run(lastAppClass, *args.sourceArgs)
}
thread.isDaemon = false
thread.start()
}
}
} | 1 | null | 1 | 1 | 8c9566723e6fe39c4fadc1262212a9e4aa3fd660 | 1,289 | library | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.