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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/commonMain/kotlin/datalayer/functions/updateBlockHeight.kt
|
luca992
| 716,489,959
| false
|
{"Kotlin": 57317, "HTML": 359, "CSS": 108}
|
package datalayer.functions
import Repository
import com.ionspin.kotlin.bignum.integer.toBigInteger
suspend fun Repository.updateBlockHeight() {
runtimeCache.blockHeight.value = client.getLatestBlock().block.header.height.toBigInteger()
}
| 0
|
Kotlin
|
0
| 1
|
605304dcd1b4f983d5063d18c8cf645ff476caee
| 244
|
sienna-lend-liquidator
|
MIT License
|
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/presets/dress/generated/dress3020010.kt
|
pointillion
| 415,443,028
| true
|
{"Kotlin": 1212476, "HTML": 26704, "CSS": 26127, "JavaScript": 1640}
|
package xyz.qwewqa.relive.simulator.core.presets.dress.generated
import xyz.qwewqa.relive.simulator.core.stage.actor.ActType
import xyz.qwewqa.relive.simulator.core.stage.actor.Attribute
import xyz.qwewqa.relive.simulator.core.stage.actor.StatData
import xyz.qwewqa.relive.simulator.core.stage.dress.ActParameters
import xyz.qwewqa.relive.simulator.core.stage.dress.ActBlueprint
import xyz.qwewqa.relive.simulator.core.stage.dress.PartialDressBlueprint
import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoost
import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoostType
import xyz.qwewqa.relive.simulator.stage.character.Character
import xyz.qwewqa.relive.simulator.stage.character.DamageType
import xyz.qwewqa.relive.simulator.stage.character.Position
val dress3020010 = PartialDressBlueprint(
id = 3020010,
name = "トール",
baseRarity = 4,
character = Character.Misora,
attribute = Attribute.Wind,
damageType = DamageType.Normal,
position = Position.Middle,
positionValue = 23050,
stats = StatData(
hp = 12000,
actPower = 700,
normalDefense = 950,
specialDefense = 350,
agility = 440,
dexterity = 5,
critical = 50,
accuracy = 0,
evasion = 0,
),
growthStats = StatData(
hp = 73000,
actPower = 4600,
normalDefense = 3200,
specialDefense = 1900,
agility = 4050,
),
actParameters = mapOf(
ActType.Act1 to ActBlueprint(
name = "キラめきの一閃",
type = ActType.Act1,
apCost = 1,
icon = 89,
parameters = listOf(
ActParameters(
values = listOf(93, 98, 102, 107, 112),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(20, 20, 20, 20, 20),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
),
),
ActType.Act2 to ActBlueprint(
name = "メギンギョルズ",
type = ActType.Act2,
apCost = 2,
icon = 1012,
parameters = listOf(
ActParameters(
values = listOf(165, 173, 181, 189, 198),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
),
),
ActType.Act3 to ActBlueprint(
name = "ヤールングレイプル",
type = ActType.Act3,
apCost = 3,
icon = 114,
parameters = listOf(
ActParameters(
values = listOf(165, 173, 181, 189, 198),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(20, 22, 24, 26, 30),
times = listOf(3, 3, 3, 3, 3),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
),
),
ActType.ClimaxAct to ActBlueprint(
name = "雷鳴のミョルニル",
type = ActType.ClimaxAct,
apCost = 2,
icon = 156,
parameters = listOf(
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(1, 1, 1, 1, 1),
),
ActParameters(
values = listOf(200, 210, 220, 230, 240),
times = listOf(5, 5, 5, 5, 5),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
ActParameters(
values = listOf(0, 0, 0, 0, 0),
times = listOf(0, 0, 0, 0, 0),
),
),
),
),
autoSkillRanks = listOf(1, 4, 9, null),
autoSkillPanels = listOf(0, 0, 5, 0),
rankPanels = listOf(
listOf(
StatBoost(StatBoostType.Hp, 1),
StatBoost(StatBoostType.ActPower, 1),
StatBoost(StatBoostType.Act2Level, 0),
StatBoost(StatBoostType.NormalDefense, 1),
StatBoost(StatBoostType.ActPower, 2),
StatBoost(StatBoostType.Hp, 2),
StatBoost(StatBoostType.Act3Level, 0),
StatBoost(StatBoostType.SpecialDefense, 1),
),
listOf(
StatBoost(StatBoostType.Hp, 2),
StatBoost(StatBoostType.NormalDefense, 2),
StatBoost(StatBoostType.NormalDefense, 2),
StatBoost(StatBoostType.Agility, 7),
StatBoost(StatBoostType.ClimaxActLevel, 0),
StatBoost(StatBoostType.ActPower, 2),
StatBoost(StatBoostType.Hp, 3),
StatBoost(StatBoostType.Act1Level, 0),
),
listOf(
StatBoost(StatBoostType.ActPower, 3),
StatBoost(StatBoostType.SpecialDefense, 2),
StatBoost(StatBoostType.Act2Level, 0),
StatBoost(StatBoostType.Hp, 3),
StatBoost(StatBoostType.ActPower, 3),
StatBoost(StatBoostType.SpecialDefense, 5),
StatBoost(StatBoostType.Act3Level, 0),
StatBoost(StatBoostType.Hp, 4),
),
listOf(
StatBoost(StatBoostType.SpecialDefense, 3),
StatBoost(StatBoostType.NormalDefense, 7),
StatBoost(StatBoostType.NormalDefense, 3),
StatBoost(StatBoostType.Agility, 8),
StatBoost(StatBoostType.ClimaxActLevel, 0),
StatBoost(StatBoostType.ActPower, 4),
StatBoost(StatBoostType.Hp, 4),
StatBoost(StatBoostType.Act1Level, 0),
),
listOf(
StatBoost(StatBoostType.ActPower, 4),
StatBoost(StatBoostType.Act1Level, 0),
StatBoost(StatBoostType.Act2Level, 0),
StatBoost(StatBoostType.SpecialDefense, 8),
StatBoost(StatBoostType.ActPower, 5),
StatBoost(StatBoostType.SpecialDefense, 5),
StatBoost(StatBoostType.Act3Level, 0),
StatBoost(StatBoostType.Hp, 5),
),
listOf(
StatBoost(StatBoostType.Hp, 5),
StatBoost(StatBoostType.NormalDefense, 8),
StatBoost(StatBoostType.SpecialDefense, 5),
StatBoost(StatBoostType.Agility, 9),
StatBoost(StatBoostType.ClimaxActLevel, 0),
StatBoost(StatBoostType.ActPower, 5),
StatBoost(StatBoostType.NormalDefense, 8),
StatBoost(StatBoostType.NormalDefense, 4),
),
listOf(
StatBoost(StatBoostType.SpecialDefense, 6),
StatBoost(StatBoostType.Hp, 6),
StatBoost(StatBoostType.Act2Level, 0),
StatBoost(StatBoostType.Agility, 11),
StatBoost(StatBoostType.ClimaxActLevel, 0),
StatBoost(StatBoostType.ActPower, 6),
StatBoost(StatBoostType.Act3Level, 0),
StatBoost(StatBoostType.Act1Level, 0),
),
listOf(
StatBoost(StatBoostType.ActPower, 6),
StatBoost(StatBoostType.NormalDefense, 6),
StatBoost(StatBoostType.ActPower, 6),
StatBoost(StatBoostType.SpecialDefense, 6),
StatBoost(StatBoostType.Hp, 6),
StatBoost(StatBoostType.NormalDefense, 6),
StatBoost(StatBoostType.Hp, 6),
StatBoost(StatBoostType.SpecialDefense, 6),
),
listOf(
StatBoost(StatBoostType.ActPower, 6),
StatBoost(StatBoostType.SpecialDefense, 6),
StatBoost(StatBoostType.Hp, 6),
StatBoost(StatBoostType.NormalDefense, 6),
StatBoost(StatBoostType.None, 0),
StatBoost(StatBoostType.SpecialDefense, 6),
StatBoost(StatBoostType.ActPower, 6),
StatBoost(StatBoostType.NormalDefense, 6),
),
),
friendshipPanels = listOf(
StatBoost(StatBoostType.None, 0),
StatBoost(StatBoostType.None, 0),
StatBoost(StatBoostType.None, 0),
StatBoost(StatBoostType.ActPower, 1),
StatBoost(StatBoostType.Hp, 1),
StatBoost(StatBoostType.NormalDefense, 1),
StatBoost(StatBoostType.SpecialDefense, 1),
StatBoost(StatBoostType.Agility, 1),
StatBoost(StatBoostType.None, 0),
StatBoost(StatBoostType.ActPower, 1),
StatBoost(StatBoostType.Hp, 1),
StatBoost(StatBoostType.NormalDefense, 1),
StatBoost(StatBoostType.SpecialDefense, 1),
StatBoost(StatBoostType.Agility, 1),
StatBoost(StatBoostType.None, 0),
StatBoost(StatBoostType.ActPower, 2),
StatBoost(StatBoostType.Hp, 2),
StatBoost(StatBoostType.NormalDefense, 2),
StatBoost(StatBoostType.SpecialDefense, 2),
StatBoost(StatBoostType.Agility, 1),
StatBoost(StatBoostType.None, 0),
StatBoost(StatBoostType.ActPower, 2),
StatBoost(StatBoostType.Hp, 2),
StatBoost(StatBoostType.NormalDefense, 2),
StatBoost(StatBoostType.SpecialDefense, 2),
StatBoost(StatBoostType.Agility, 2),
StatBoost(StatBoostType.None, 0),
StatBoost(StatBoostType.None, 0),
StatBoost(StatBoostType.Agility, 2),
StatBoost(StatBoostType.None, 0),
StatBoost(StatBoostType.ActPower, 2),
StatBoost(StatBoostType.Hp, 2),
StatBoost(StatBoostType.NormalDefense, 2),
StatBoost(StatBoostType.SpecialDefense, 2),
StatBoost(StatBoostType.Agility, 2),
StatBoost(StatBoostType.ActPower, 2),
StatBoost(StatBoostType.Hp, 2),
StatBoost(StatBoostType.NormalDefense, 2),
StatBoost(StatBoostType.SpecialDefense, 2),
StatBoost(StatBoostType.Agility, 2),
StatBoost(StatBoostType.ActPower, 2),
StatBoost(StatBoostType.Hp, 2),
StatBoost(StatBoostType.NormalDefense, 2),
StatBoost(StatBoostType.SpecialDefense, 2),
StatBoost(StatBoostType.Agility, 2),
StatBoost(StatBoostType.ActPower, 2),
StatBoost(StatBoostType.Hp, 2),
StatBoost(StatBoostType.NormalDefense, 2),
StatBoost(StatBoostType.SpecialDefense, 2),
StatBoost(StatBoostType.Agility, 2),
),
remakeParameters = listOf(
StatData(
hp = 7500,
actPower = 330,
normalDefense = 450,
specialDefense = 450,
agility = 60,
),
StatData(
hp = 12500,
actPower = 550,
normalDefense = 750,
specialDefense = 750,
agility = 100,
),
StatData(
hp = 20000,
actPower = 880,
normalDefense = 1200,
specialDefense = 1200,
agility = 160,
),
StatData(
hp = 25000,
actPower = 1100,
normalDefense = 1500,
specialDefense = 1500,
agility = 200,
),
),
)
| 0
|
Kotlin
|
0
| 0
|
4c7a14047ee5cdec2ad2f59f0491d99d2efef5ea
| 10,789
|
relive-simulator
|
MIT License
|
lib-gson/src/main/java/net/codefeet/lemmyandroidclient/gen/types/PostReportResponse.kt
|
Flex4Reddit
| 648,927,752
| false
| null |
package net.codefeet.lemmyandroidclient.gen.types
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize
@Parcelize
public data class PostReportResponse(
@SerializedName("post_report_view")
public val postReportView: PostReportView,
) : Parcelable
| 0
|
Kotlin
|
0
| 0
|
8028bbf4fc50d7c945d20c7034d6da2de4b7c0ac
| 313
|
lemmy-android-client
|
MIT License
|
app/src/main/java/com/mospolytech/mospolyhelper/domain/schedule/repository/ScheduleSourcesRepository.kt
|
mospolyhelper
| 259,442,737
| false
|
{"Kotlin": 839539, "Batchfile": 69}
|
package com.mospolytech.mospolyhelper.domain.schedule.repository
import com.mospolytech.mospolyhelper.domain.schedule.model.ScheduleSource
import kotlinx.coroutines.flow.Flow
interface ScheduleSourcesRepository {
fun getFavoriteScheduleSources(): Flow<List<ScheduleSource>>
suspend fun addFavoriteScheduleSource(source: ScheduleSource)
suspend fun removeFavoriteScheduleSource(source: ScheduleSource)
fun getScheduleSources(): Flow<List<ScheduleSource>>
fun getSelectedScheduleSource(): Flow<ScheduleSource?>
suspend fun setSelectedScheduleSource(source: ScheduleSource?)
}
| 2
|
Kotlin
|
2
| 8
|
4f37c3617cf7523f22f03a22d7de2d7ecc74a098
| 601
|
mospolyhelper-android
|
MIT License
|
domain/src/main/kotlin/com/muradtop/kitsu/domain/models/manga/MangaModel.kt
|
muradtop
| 493,279,085
| false
|
{"Kotlin": 139828}
|
package com.muradtop.kitsu.domain.models.manga
data class MangaModel(
val createdAt: String,
val updatedAt: String,
val slug: String,
val synopsis: String,
val coverImageTopOffset: Int,
val titles: com.muradtop.kitsu.domain.models.manga.TitlesModel,
val canonicalTitle: String,
val abbreviatedTitles: Any,
val averageRating: String?,
val ratingFrequencies: com.muradtop.kitsu.domain.models.manga.RatingFrequenciesModel,
val userCount: Int,
val favoritesCount: Int,
val startDate: String?,
val endDate: String?,
val nextRelease: Any?,
val popularityRank: Int,
val ratingRank: Int?,
val ageRating: String?,
val ageRatingGuide: String?,
val subtype: String,
val status: String,
val tba: String?,
val posterImage: com.muradtop.kitsu.domain.models.manga.PosterImageModel,
val coverImage: com.muradtop.kitsu.domain.models.manga.CoverImageModel?,
val chapterCount: Any?,
val volumeCount: Int,
val serialization: String?,
val mangaType: String
)
| 0
|
Kotlin
|
0
| 0
|
087deab6fb04c81671f6c64f78430159d72f35ca
| 1,050
|
Kitsu-Api
|
MIT License
|
domain/src/main/kotlin/com/muradtop/kitsu/domain/models/manga/MangaModel.kt
|
muradtop
| 493,279,085
| false
|
{"Kotlin": 139828}
|
package com.muradtop.kitsu.domain.models.manga
data class MangaModel(
val createdAt: String,
val updatedAt: String,
val slug: String,
val synopsis: String,
val coverImageTopOffset: Int,
val titles: com.muradtop.kitsu.domain.models.manga.TitlesModel,
val canonicalTitle: String,
val abbreviatedTitles: Any,
val averageRating: String?,
val ratingFrequencies: com.muradtop.kitsu.domain.models.manga.RatingFrequenciesModel,
val userCount: Int,
val favoritesCount: Int,
val startDate: String?,
val endDate: String?,
val nextRelease: Any?,
val popularityRank: Int,
val ratingRank: Int?,
val ageRating: String?,
val ageRatingGuide: String?,
val subtype: String,
val status: String,
val tba: String?,
val posterImage: com.muradtop.kitsu.domain.models.manga.PosterImageModel,
val coverImage: com.muradtop.kitsu.domain.models.manga.CoverImageModel?,
val chapterCount: Any?,
val volumeCount: Int,
val serialization: String?,
val mangaType: String
)
| 0
|
Kotlin
|
0
| 0
|
087deab6fb04c81671f6c64f78430159d72f35ca
| 1,050
|
Kitsu-Api
|
MIT License
|
EarthGardener-Android/app/src/main/java/team/gdsc/earthgardener/presentation/user/signup/retrofit/SignUpRetrofitInterface.kt
|
gdsckoreahackathon2022
| 454,347,534
| false
| null |
package team.gdsc.earthgardener.presentation.user.signup.retrofit
import okhttp3.MultipartBody
import okhttp3.RequestBody
import retrofit2.Call
import retrofit2.http.Multipart
import retrofit2.http.POST
import retrofit2.http.Part
import retrofit2.http.PartMap
interface SignUpRetrofitInterface {
@Multipart
@POST("user/signup")
fun postSignUp(
@PartMap data: HashMap<String, RequestBody>,
@Part image: MultipartBody.Part
): Call<SignUpResponse>
}
| 0
|
Kotlin
|
0
| 0
|
f36bb9cc0d5dbddfb0bad67f88c1b670766d0867
| 481
|
41_EarthGardener
|
MIT License
|
app/src/main/java/com/keykat/keykat/brawlkat/common/util/DataViewModel.kt
|
betterafter
| 275,093,766
| false
|
{"Java": 333257, "Kotlin": 87511}
|
package com.keykat.keykat.brawlkat.common.util
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class DataViewModel : ViewModel() {
private val _isBackgroundServiceOn = MutableLiveData<Boolean>()
val isBackgroundServiceOn: LiveData<Boolean> = _isBackgroundServiceOn
}
| 11
|
Java
|
1
| 1
|
e44ed64fffe9d5adabd446de3291a84e2ec171e2
| 342
|
BrawlKat
|
MIT License
|
pdf-classifier/src/main/kotlin/de/ideasinlogic/tools/imappdf/PdfClassifier.kt
|
elektro-wolle
| 125,924,218
| false
|
{"Kotlin": 23592, "Dockerfile": 708, "Shell": 491}
|
package de.ideasinlogic.tools.imappdf
import mu.KotlinLogging
import org.apache.pdfbox.io.RandomAccessBuffer
import org.apache.pdfbox.pdfparser.PDFParser
import org.apache.pdfbox.pdmodel.PDDocument
import org.apache.pdfbox.rendering.PDFRenderer
import org.apache.pdfbox.text.PDFTextStripper
import org.apache.pdfbox.text.TextPosition
import java.awt.Color
import java.awt.Graphics2D
import java.awt.RenderingHints
import java.awt.image.BufferedImage
import java.awt.image.BufferedImageOp
import java.awt.image.ByteLookupTable
import java.awt.image.LookupOp
import java.io.File
import java.io.FileInputStream
import java.nio.file.NoSuchFileException
import javax.imageio.ImageIO
import kotlin.math.max
import kotlin.math.min
import kotlin.random.Random
class PdfClassifier(
file: File,
whiteSpaceMax: Float = 0.04f,
minWhiteSpaceRun: Int = 5,
minSizeInMM: Float = 8f,
private val segmentationWithDPI: Float = 36f
) {
private val segmentation = Segmentation(whiteSpaceMax, minWhiteSpaceRun, minSizeInMM / 25.4f * segmentationWithDPI)
private val parser: PDFParser
private var minG = 255
private var maxG = 0
private val SCALE_DOWN = 2
init {
if (!file.isFile) {
throw NoSuchFileException("$file is not a file")
}
FileInputStream(file).use {
parser = PDFParser(RandomAccessBuffer(it))
parser.parse()
}
}
// Extract text from PDF Document
fun pdftoText(): Map<Int, List<TextRectangle>> {
return parser.document.use { cosDoc ->
PDDocument(cosDoc).use { pdDoc ->
(0 until pdDoc.numberOfPages).map { currentPage ->
currentPage to segmentSinglePage(pdDoc, currentPage)
}.toMap()
}
}
}
private fun segmentSinglePage(pdDoc: PDDocument, currentPage: Int): List<TextRectangle> {
// render with double resolution
val image = PDFRenderer(pdDoc).renderImageWithDPI(currentPage, SCALE_DOWN * segmentationWithDPI)
// scale down to target DPI
val grayImg = generateGrayScaleImage(image, currentPage)
// find min/max for normalization
findMinMaxValues(grayImg)
// create 2d Array with ints, where text is found
val textFoundAt = findTextFragments(grayImg, currentPage)
// start segmentation with full page
val rect = BoundingRectangle(0 until grayImg.width, 0 until grayImg.height)
// find segments
val segments = segmentation.segmentize(textFoundAt, rect)
val fragments =
segments.mapNotNull { segment ->
extractTextInSegment(currentPage, segment, pdDoc)
?.let {
TextRectangle(
segment.xRange,
segment.yRange,
it
)
}
}
fragments.forEach {
log.debug { "rect: $it" }
}
renderSegments(grayImg, fragments, currentPage)
return fragments
}
private fun renderSegments(img: BufferedImage, segments: List<TextRectangle>, currentPage: Int) {
val image = BufferedImage(img.width, img.height, BufferedImage.TYPE_INT_RGB)
(image.graphics as Graphics2D).addRenderingHints(mapOf(RenderingHints.KEY_ANTIALIASING to RenderingHints.VALUE_ANTIALIAS_ON))
image.graphics.drawImage(img, 0, 0, null)
val g = image.graphics
var hue = 0f
segments.forEachIndexed { idx, bbox ->
val hsbColor = Color.getHSBColor(hue, 0.6f, 0.5f)
hue += 0.2f + Random.nextFloat() / 5f
hue -= hue.toInt()
g.color = Color(hsbColor.red, hsbColor.green, hsbColor.blue, 50)
g.fillRect(bbox.getX(), bbox.getY(), bbox.getW(), bbox.getH())
}
ImageIO.write(image, "png", File("target/segments-$currentPage.png"))
}
private fun findTextFragments(
grayImg: BufferedImage, currentPage: Int
): BufferedImage {
var textFoundAt = arrayOf<Array<Int>>()
val invert = ByteArray(256)
for (i in 0..255) {
invert[i] = (256.0 - ((256.0 * (i - minG)) / (maxG - minG))).coerceIn(0.0, 255.0).toInt().toByte()
}
val invertOp: BufferedImageOp = LookupOp(ByteLookupTable(0, invert), null)
val normalized = invertOp.filter(grayImg, null)
for (y in 0 until (normalized.height)) {
var array = arrayOf<Int>()
for (x in 0 until (normalized.width)) {
val grayVal = normalized.getRGB(x, y).and(0xff)
array += grayVal
}
textFoundAt += array
}
ImageIO.write(normalized, "png", File("target/normalize-$currentPage.png"))
return normalized
}
private fun findMinMaxValues(grayImg: BufferedImage) {
minG = 255
maxG = 0
for (y in 0 until grayImg.height) {
val line = (0 until grayImg.width).map { grayImg.getRGB(it, y).and(0xff) }
minG = min(minG, line.minOrNull() ?: 255)
maxG = max(maxG, line.maxOrNull() ?: 0)
}
}
private fun generateGrayScaleImage(
image: BufferedImage,
currentPage: Int
): BufferedImage {
val grayImg = BufferedImage(image.width / SCALE_DOWN, image.height / SCALE_DOWN, BufferedImage.TYPE_BYTE_GRAY)
(grayImg.graphics as Graphics2D).addRenderingHints(mapOf(RenderingHints.KEY_ANTIALIASING to RenderingHints.VALUE_ANTIALIAS_ON))
grayImg.graphics.drawImage(image, 0, 0, grayImg.width, grayImg.height, null)
ImageIO.write(grayImg, "png", File("target/gray-$currentPage.png"))
return grayImg
}
private fun extractTextInSegment(
page: Int,
segment: BoundingRectangle,
pdDoc: PDDocument
): String? {
val sb = StringBuffer()
val pdfStripper = object : PDFTextStripper() {
override fun writeString(text: String?, textPositions: MutableList<TextPosition>?) {
textPositions
?.filter { segment.contains(it, SCALE_DOWN) }
?.forEach { tp ->
sb.append(tp.characterCodes.map { c -> c.toChar() }.joinToString(""))
}
sb.append(" ")
super.writeString(text, textPositions)
}
}
pdfStripper.startPage = page + 1
pdfStripper.endPage = page + 1
pdfStripper.setShouldSeparateByBeads(true)
pdfStripper.sortByPosition = false
// pdfStripper.spacingTolerance = 0.1f
pdfStripper.getText(pdDoc)
val str = sb.toString().trim()
return if (str.isNotBlank()) str else null
}
companion object {
private val log = KotlinLogging.logger {}
@JvmStatic
fun main(args: Array<String>) {
PdfClassifier(File("src/test/resources/Alexander Glas_.pdf")).pdftoText()
}
}
}
| 0
|
Kotlin
|
0
| 4
|
cf3205998addb328ff12366a8f328be2821e62d0
| 6,016
|
imap-pdf-ocr
|
Apache License 2.0
|
NOCI/app/src/main/java/com/example/noci/lists/input/ListsInputFragment.kt
|
Maarchosias
| 291,082,916
| false
| null |
package com.example.noci.lists.input
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.noci.*
import com.example.noci.database_lists.items.Items
import com.example.noci.databinding.FragmentInputListsBinding
import com.example.noci.lists.ITEM_DELETER_CHECKER
import com.example.noci.lists.PLM
import com.orhanobut.hawk.Hawk
class ListsInputFragment : Fragment(), ItemsAdapterEdit, ItemsAdapterDelete {
private lateinit var binding: FragmentInputListsBinding
private lateinit var inputViewModel: ListsInputViewModel
private val adapter = ItemsAdapter(this, this)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_input_lists, container, false)
inputViewModel = ViewModelProvider(this).get(ListsInputViewModel::class.java)
binding.inputViewModel = inputViewModel
binding.showList.adapter = adapter
return binding.root
}
override fun onStart() {
super.onStart()
// get arguments from the bundle that came from the ListFragment via navigation
val details = ListsInputFragmentArgs.fromBundle(requireArguments()).lists
if (details != null) {
binding.addTitle.text = details.title
binding.editTitle.setText(details.title)
}
// read all items from the database of the specific list
inputViewModel.itemsReadAll?.observe(viewLifecycleOwner, Observer {
it?.let {
adapter.submitList(it)
}
Hawk.delete(ITEM_DELETER_CHECKER)
})
// insert item to the database
inputViewModel.insertInitializer.observe(viewLifecycleOwner, Observer {
val noteTitle = binding.addTitle.text.toString()
if (TextUtils.isEmpty(noteTitle)) {
Toast.makeText(context, "Title field can't be empty!", Toast.LENGTH_SHORT).show()
} else {
onGoBack()
}
})
// update title of the list
inputViewModel.onChangeTitle.observe(viewLifecycleOwner, Observer {
if (it) {
binding.addTitle.visibility = View.INVISIBLE
binding.editTitle.visibility = View.VISIBLE
binding.editTitle.requestFocus()
}
binding.editTitle.onFocusChangeListener =
View.OnFocusChangeListener() { view: View, b: Boolean ->
if (!binding.editTitle.hasFocus()) {
binding.addTitle.visibility = View.VISIBLE
binding.editTitle.visibility = View.INVISIBLE
val newTitle: String = binding.editTitle.text.toString()
binding.addTitle.text = newTitle
// check if this goes as intended
if (details != null) {
inputViewModel.updateTitle(details.id, newTitle)
}
}
}
})
// go back to main
inputViewModel.onGoBackToMain.observe(viewLifecycleOwner, Observer {
if (it) {
val intent = Intent(context, NotesActivity::class.java)
startActivity(intent)
}
})
// activate the _addToListBool value when user pressed Enter, which adds the item into database / the function below
binding.itemName.setOnKeyListener(View.OnKeyListener { v, keyCode, event ->
if (keyCode == KeyEvent.KEYCODE_ENTER) {
inputViewModel.addToList()
//binding.itemName.requestFocus()
}
false
})
// adds item in the database of the specific list
inputViewModel.addToListBool.observe(viewLifecycleOwner, Observer {
if (it) {
val item = binding.itemName.text.toString()
val listId = details?.id
if (item.isNotEmpty()) {
if (listId != null) {
inputViewModel.addNote(item, listId)
}
}
binding.itemName.setText("")
}
})
// sets the ItemState variable in the item database of the specific list to true/false depending on already stored value
inputViewModel.onSelectAllBool.observe(viewLifecycleOwner, Observer {
if (it) {
if (details != null) {
if (!SelectKey.getSelect()) {
SelectKey.setSelect(true)
inputViewModel.selectAllItems(details.id, true)
} else {
SelectKey.setSelect(false)
inputViewModel.selectAllItems(details.id, false)
}
}
}
})
inputViewModel.onDeleteSelectedBool.observe(viewLifecycleOwner, Observer {
if (it) {
if (details != null) {
inputViewModel.onDeleteSelectedItems(details.id)
}
}
})
// binding.itemName.setOnFocusChangeListener { view: View, b: Boolean ->
//// if(!view.hasFocus()) {
//// binding.itemName.requestFocus()
//// val inputMethodManager = context?.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
//// inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, SOFT_INPUT_STATE_VISIBLE)
// }
}
// override for interfaces in the ItemsAdapter class
override fun editItem(id: Int, newState: Boolean) {
inputViewModel.changeItemState(id, newState)
}
override fun deleteItem(currentItem: Items) {
inputViewModel.deleteFromLocalDB(currentItem)
}
fun onGoBack() {
val intent = Intent(context, ListsInputActivity::class.java)
startActivity(intent)
}
}
| 0
|
Kotlin
|
0
| 0
|
da86524942a1521128c99221faa4c82dc13a7d5a
| 6,440
|
android.development
|
MIT License
|
app/src/main/java/uk/co/sentinelweb/cuer/app/db/dao/MediaDao.kt
|
sentinelweb
| 220,796,368
| false
| null |
package uk.co.sentinelweb.cuer.app.db.dao
import androidx.room.*
import uk.co.sentinelweb.cuer.app.db.entity.MediaAndChannel
import uk.co.sentinelweb.cuer.app.db.entity.MediaEntity
@Dao
interface MediaDao {
@Transaction
@Query("SELECT * FROM media")
suspend fun getAll(): List<MediaAndChannel>
@Query("SELECT count() FROM media")
suspend fun count(): Int
//Transaction
@Query("SELECT * FROM media WHERE id IN (:mediaIds)")
suspend fun loadAllByIds(mediaIds: LongArray): List<MediaAndChannel>
//@Transaction
@Query("SELECT * FROM media WHERE id == :id")
suspend fun load(id: Long): MediaAndChannel?
//@Transaction
@Query("SELECT * FROM media WHERE media_id LIKE :mediaId LIMIT 1")
suspend fun findByMediaId(mediaId: String): MediaAndChannel?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(medias: List<MediaEntity>): List<Long>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(media: MediaEntity): Long
@Update
suspend fun update(media: MediaEntity)
@Delete
suspend fun delete(media: MediaEntity)
@Query("DELETE FROM media")
suspend fun deleteAll()
@Query("SELECT * FROM media WHERE flags & :flags == :flags")
suspend fun loadAllByFlags(flags: Long): List<MediaAndChannel>
@Query("SELECT flags FROM media WHERE id == :id")
suspend fun getFlags(id: Long): Long
//@Update(entity = MediaPositionUpdateEntity::class, onConflict = OnConflictStrategy.REPLACE)
@Query("UPDATE media SET date_last_played=:dateLastPlayed, positon=:position, duration=:duration, flags=:flags where id=:id")
fun updatePosition(id: Long, dateLastPlayed: String, position: Long?, duration: Long?, flags: Long)
}
| 59
|
Kotlin
|
0
| 0
|
e9b3baf857c9e08eb21444291e8c4f8b8ca0838d
| 1,763
|
cuer
|
Apache License 2.0
|
DictionaryApp/app/src/main/java/tr/com/abdulsamet/dictionary/view/fragment/DetailFragment.kt
|
AbdulsametAyyildiz
| 589,340,352
| false
| null |
package tr.com.abdulsamet.dictionary.view.fragment
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import tr.com.abdulsamet.dictionary.R
import tr.com.abdulsamet.dictionary.base.BaseFragment
import tr.com.abdulsamet.dictionary.base.ResponseResource
import tr.com.abdulsamet.dictionary.databinding.FragmentDetailBinding
import tr.com.abdulsamet.dictionary.view.adapter.MeaningAdapter
import tr.com.abdulsamet.dictionary.view.adapter.SynonymAdapter
import tr.com.abdulsamet.dictionary.viewmodel.DetailViewModel
import javax.inject.Inject
/**
* @author <NAME> at 10.01.2023
*/
class DetailFragment @Inject constructor(
private val meaningAdapter: MeaningAdapter,
private val synonymAdapter: SynonymAdapter,
private val speechAdapter: SynonymAdapter
) : BaseFragment<DetailViewModel, FragmentDetailBinding>() {
override fun getViewModel(): Class<DetailViewModel> {
return DetailViewModel::class.java
}
override fun getLayoutRes(): Int {
return R.layout.fragment_detail
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arguments?.let {
val word = it.getString("word", "")
if (word.isNotEmpty()) {
if (parentActivity.checkConnection()) {
viewModel.getMeaning(word)
viewModel.getSynonym(word)
} else {
Toast.makeText(
parentActivity,
parentActivity.getText(R.string.error_internet),
Toast.LENGTH_SHORT
).show()
parentActivity.onBackPressedDispatcher.onBackPressed()
}
} else {
Toast.makeText(
parentActivity,
parentActivity.getText(R.string.error_unexpected),
Toast.LENGTH_SHORT
).show()
parentActivity.onBackPressedDispatcher.onBackPressed()
}
}
setView()
setObserver()
}
private fun setView() {
dataBinding.recyclerSpeech.layoutManager =
LinearLayoutManager(parentActivity, LinearLayoutManager.HORIZONTAL, false)
dataBinding.recyclerSynonym.layoutManager =
LinearLayoutManager(parentActivity, LinearLayoutManager.HORIZONTAL, false)
dataBinding.recyclerMeaning.addItemDecoration(
DividerItemDecoration(
parentActivity,
LinearLayoutManager.VERTICAL
)
)
dataBinding.recyclerMeaning.adapter = meaningAdapter
dataBinding.recyclerSynonym.adapter = synonymAdapter
dataBinding.recyclerSpeech.adapter = speechAdapter
dataBinding.buttonBack.setOnClickListener {
parentActivity.onBackPressedDispatcher.onBackPressed()
}
}
private fun setObserver() {
viewModel.meaningLiveData.observe(viewLifecycleOwner) {
it?.let {
when (it.status) {
ResponseResource.Status.SUCCESS -> {
viewModel.synonymLiveData.value?.let { synonymData ->
if (synonymData.status != ResponseResource.Status.LOADING) {
dataBinding.progressBar.visibility = View.GONE
}
}
it.data?.let { meaning ->
dataBinding.meaningResponse = meaning[0]
val processedMeaning = viewModel.convertFormattedMeaningList(meaning[0])
meaningAdapter.meaningList = processedMeaning.meaningList
speechAdapter.stringList = processedMeaning.speechList
}
dataBinding.dataView.visibility = View.VISIBLE
}
ResponseResource.Status.LOADING -> {
dataBinding.dataView.visibility = View.GONE
dataBinding.progressBar.visibility = View.VISIBLE
}
ResponseResource.Status.ERROR -> {
Toast.makeText(
parentActivity,
it.message,
Toast.LENGTH_SHORT
).show()
parentActivity.onBackPressedDispatcher.onBackPressed()
}
}
}
}
viewModel.synonymLiveData.observe(viewLifecycleOwner) {
it?.let {
when (it.status) {
ResponseResource.Status.SUCCESS -> {
viewModel.meaningLiveData.value?.let { meaningData ->
if (meaningData.status != ResponseResource.Status.LOADING) {
dataBinding.progressBar.visibility = View.GONE
}
}
it.data?.let { synonym ->
synonymAdapter.stringList =
viewModel.convertFormattedSynonymList(synonym)
}
dataBinding.synonymView.visibility = View.VISIBLE
}
ResponseResource.Status.LOADING -> {
dataBinding.synonymView.visibility = View.GONE
dataBinding.progressBar.visibility = View.VISIBLE
}
ResponseResource.Status.ERROR -> {
Toast.makeText(
parentActivity,
it.message,
Toast.LENGTH_SHORT
).show()
dataBinding.synonymView.visibility = View.GONE
dataBinding.progressBar.visibility = View.GONE
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
b51b61e0f3db7df478b9d856eddbd1aec457eda9
| 6,202
|
DictionaryApp-Android
|
MIT License
|
http4k/src/test/kotlin/com/github/christophpickl/kpotpourri/http4k/api_test.kt
|
christophpickl
| 83,411,497
| false
| null |
package com.github.christophpickl.kpotpourri.http4k
import com.github.christophpickl.kpotpourri.http4k.non_test.testDummy
import com.github.christophpickl.kpotpourri.test4k.hamkrest_matcher.shouldMatchValue
import org.testng.annotations.Test
@Test class Response4kTest {
fun `readJson sunshine`() {
Response4k.testDummy.copy(bodyAsString = "{\"number\":42}").readJson(Dto::class) shouldMatchValue Dto(42)
}
private data class Dto(val number: Int)
}
| 0
|
Kotlin
|
0
| 4
|
eb6ad4d00be86ce88417d32dcb49370a632a9c1e
| 474
|
kpotpourri
|
Apache License 2.0
|
app/src/main/java/com/ahmedtikiwa/fxapp/network/models/NetworkHistoricalResponse.kt
|
akitikkx
| 371,123,034
| false
| null |
package com.ahmedtikiwa.fxapp.network.models
import com.google.gson.internal.LinkedTreeMap
data class NetworkHistoricalResponse(
val date: String,
val price: LinkedTreeMap<String, Double>
)
| 0
|
Kotlin
|
0
| 0
|
a782a5a5f6960b3926e670faa37d8f9b5f4355e1
| 199
|
fx-app
|
MIT License
|
feature/metis/src/test/kotlin/de/tum/informatics/www1/artemis/native_app/feature/metis/ConversationBaseTest.kt
|
ls1intum
| 537,104,541
| false
| null |
package de.tum.informatics.www1.artemis.native_app.feature.metis
import android.content.Context
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.test.platform.app.InstrumentationRegistry
import de.tum.informatics.www1.artemis.native_app.core.model.Course
import de.tum.informatics.www1.artemis.native_app.core.model.exercise.TextExercise
import de.tum.informatics.www1.artemis.native_app.core.test.coreTestModules
import de.tum.informatics.www1.artemis.native_app.core.test.test_setup.course_creation.createCourse
import de.tum.informatics.www1.artemis.native_app.core.test.test_setup.setTestServerUrl
import de.tum.informatics.www1.artemis.native_app.core.test.test_setup.testServerUrl
import de.tum.informatics.www1.artemis.native_app.core.websocket.impl.WebsocketProvider
import de.tum.informatics.www1.artemis.native_app.feature.login.loginModule
import de.tum.informatics.www1.artemis.native_app.feature.login.test.getAdminAccessToken
import de.tum.informatics.www1.artemis.native_app.feature.login.test.performTestLogin
import de.tum.informatics.www1.artemis.native_app.feature.login.test.testLoginModule
import de.tum.informatics.www1.artemis.native_app.feature.metis.content.OneToOneChat
import de.tum.informatics.www1.artemis.native_app.feature.metis.service.ConversationService
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import org.junit.Before
import org.junit.Rule
import org.koin.android.ext.koin.androidContext
import org.koin.dsl.module
import org.koin.test.KoinTest
import org.koin.test.KoinTestRule
import org.koin.test.get
abstract class ConversationBaseTest : KoinTest {
protected val testDispatcher = UnconfinedTestDispatcher()
protected val context: Context get() = InstrumentationRegistry.getInstrumentation().context
@get:Rule
val composeTestRule = createComposeRule()
@get:Rule
val koinTestRule = KoinTestRule.create {
androidContext(context)
modules(coreTestModules)
modules(loginModule, communicationModule, testLoginModule, module {
single<MetisDatabaseProvider> { MetisDatabaseProviderMock(context) }
single<WebsocketProvider> {
WebsocketProvider(
serverConfigurationService = get(),
accountService = get(),
jsonProvider = get(),
networkStatusProvider = get(),
coroutineContext = testDispatcher
)
}
})
}
protected lateinit var accessToken: String
protected lateinit var course: Course
protected lateinit var exercise: TextExercise
protected val conversationService: ConversationService get() = get()
protected val user2Username: String = System.getenv("user2Username") ?: "test_user_2"
protected val user3Username: String = System.getenv("user3Username") ?: "test_user_3"
protected val user2DisplayName: String = System.getenv("user2Name") ?: "Test User2"
@Before
open fun setup() {
runBlocking {
setTestServerUrl()
accessToken = performTestLogin()
course = createCourse(getAdminAccessToken())
}
}
protected suspend fun createPersonalConversation(): OneToOneChat =
conversationService.createOneToOneConversation(
course.id!!,
user2Username,
accessToken,
testServerUrl
).orThrow("Could not create one to one conversation")
}
| 2
|
Kotlin
|
0
| 2
|
466a1c60c3b2f9a9b57c4a98adac0361e4c711c3
| 3,530
|
artemis-android
|
Apache License 2.0
|
app/src/main/java/com/krossmanzs/kateringyuk/AboutActivity.kt
|
krossmanzs
| 430,032,621
| false
|
{"Kotlin": 20250}
|
package com.krossmanzs.kateringyuk
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class AboutActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_about)
supportActionBar?.title = getString(R.string.about)
}
}
| 0
|
Kotlin
|
0
| 0
|
3d94d3a73ef2ecb6210518d8073c19b142fb36c5
| 369
|
Katering-Yuk
|
MIT License
|
fontawesome/src/de/msrd0/fontawesome/icons/FA_EARTH_AFRICA.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
/** Earth Africa */
object FA_EARTH_AFRICA: Icon {
override val name get() = "Earth Africa"
override val unicode get() = "f57c"
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="M512 256C512 397.4 397.4 512 256 512C114.6 512 0 397.4 0 256C0 114.6 114.6 0 256 0C397.4 0 512 114.6 512 256zM177.8 63.19L187.8 80.62C190.5 85.46 192 90.93 192 96.5V137.9C192 141.8 193.6 145.6 196.3 148.3C202.6 154.6 212.8 153.1 218.3 147.1L231.9 130.1C236.6 124.2 244.8 122.4 251.6 125.8L266.8 133.4C270.2 135.1 273.1 136 277.8 136C284.3 136 290.6 133.4 295.2 128.8L299.1 124.9C302 121.1 306.5 121.2 310.1 123.1L339.4 137.7C347.1 141.6 352 149.5 352 158.1C352 168.6 344.9 177.8 334.7 180.3L299.3 189.2C291.9 191 284.2 190.7 276.1 188.3L244.1 177.7C241.7 176.6 238.2 176 234.8 176C227.8 176 220.1 178.3 215.4 182.5L176 212C165.9 219.6 160 231.4 160 244V272C160 298.5 181.5 320 208 320H240C248.8 320 256 327.2 256 336V384C256 401.7 270.3 416 288 416C298.1 416 307.6 411.3 313.6 403.2L339.2 369.1C347.5 357.1 352 344.5 352 330.7V318.6C352 314.7 354.6 311.3 358.4 310.4L363.7 309.1C375.6 306.1 384 295.4 384 283.1C384 275.1 381.2 269.2 376.2 264.2L342.7 230.7C338.1 226.1 338.1 221 342.7 217.3C348.4 211.6 356.8 209.6 364.5 212.2L378.6 216.9C390.9 220.1 404.3 215.4 410.1 203.8C413.6 196.8 421.3 193.1 428.1 194.6L456.4 200.1C431.1 112.4 351.5 48 256 48C228.3 48 201.1 53.4 177.8 63.19L177.8 63.19z"/></svg>"""
else -> null
}
}
/** Alias for [FA_EARTH_AFRICA]. */
val FA_GLOBE_AFRICA = FA_EARTH_AFRICA
| 0
|
Kotlin
|
0
| 0
|
ee6a62d201fd5df2555859271cb0c6a7ee887e7a
| 2,497
|
fontawesome-kt
|
Apache License 2.0
|
src/main/kotlin/com/example/spring/boot/web/failure/analyzer/MyPortInUseFailureAnalyzer.kt
|
ShassBeleth
| 233,717,293
| false
| null |
package com.example.spring.boot.web.failure.analyzer
import org.springframework.boot.diagnostics.AbstractFailureAnalyzer
import org.springframework.boot.diagnostics.FailureAnalysis
import org.springframework.boot.web.server.PortInUseException
/**
* アプリ起動時に指定のポートが既に使われていた場合に起きるExceptionの分析
*/
class MyPortInUseFailureAnalyzer : AbstractFailureAnalyzer<PortInUseException>() {
override fun analyze(rootFailure:Throwable, cause:PortInUseException):FailureAnalysis {
return FailureAnalysis(
"Web server failed to start. Port " + cause.port + " was already in use." ,
"Identify and stop the process that's listening on port " + cause.port + " or configure this application to listen on another port.",
cause
)
}
}
| 0
|
Kotlin
|
0
| 0
|
5bb6aec2f58febf71475bb5e0bf3f2e13f5af77a
| 782
|
SpringBootExample
|
MIT License
|
app/src/main/java/jp/cordea/ribsdemo/ui/region/RegionScope.kt
|
CORDEA
| 163,973,049
| false
| null |
package jp.cordea.ribsdemo.ui.region
import javax.inject.Scope
@Scope
@Retention(AnnotationRetention.BINARY)
annotation class RegionScope
| 0
|
Kotlin
|
0
| 2
|
3ff23b50b9d59ca42ba95cdf437d36f2ddd4bda0
| 140
|
RIBsDemo
|
Apache License 2.0
|
OpenDaySkill/src/main/kotlin/furhatos/app/opendayskill/flow/main/OpenDay.kt
|
TeresaRM
| 540,570,003
| false
|
{"Kotlin": 63183, "HTML": 3375, "CSS": 1380}
|
package furhatos.app.opendayskill.flow.main
import furhatos.flow.kotlin.*
import furhatos.app.opendayskill.flow.Parent
import furhatos.app.opendayskill.flow.nlu.NegativeRemark
import furhatos.app.opendayskill.flow.nlu.PositiveRemark
import furhatos.app.opendayskill.setting.name
import furhatos.gestures.Gestures
val OpenDay: State = state(Parent) {
onEntry {
furhat.gesture(Gestures.BrowRaise, async = true)
furhat.say {
random {
+ "Well, one last question ${users.current.name}, I'm genuinely interested!"
+ "Well, one last question ${users.current.name} and I'll let you go."
}
}
delay(200)
furhat.ask {
random {
+ "Are you liking the open day so far?"
+ "Are you enjoying the open day?"
}
}
}
onResponse<PositiveRemark> {
furhat.say {
random {
+ "That's great to hear! Students have worked really hard for it"
+ "I'm glad you are enjoying the open day. Make sure to check out as many stands and activities as possible!"
}
}
furhat.gesture(Gestures.BigSmile, async = false)
delay(200)
goto(Farewell)
}
onResponse<NegativeRemark> {
furhat.say {
random {
+ "Thanks for the feedback ${users.current.name}. Me and my team will remember that"
+ "I guess you must be really tired. Grab some coffee, I heard it's human's preferred energy source"
}
}
furhat.gesture(Gestures.Smile, async = false)
delay(200)
goto(Farewell)
}
onResponse {
furhat.say("I didn't quite catch that, but I'll assume you are having fun speaking to me.")
furhat.gesture(Gestures.Smile, async = false)
delay(200)
goto(Farewell)
}
onNoResponse {
furhat.say("${users.current.name} are you okay? I didn't quite catch that")
furhat.listen()
}
}
| 0
|
Kotlin
|
0
| 0
|
529a90df65523c8296ba65209a57cf59846375a5
| 2,056
|
Furhat-skills
|
Creative Commons Zero v1.0 Universal
|
app/src/main/java/dalian/razvan/cucer/ibm/core/repository/IBMRepositoryImpl.kt
|
daliaan
| 367,817,053
| false
| null |
package dalian.razvan.cucer.ibm.core.repository
import android.util.Log
import dalian.razvan.cucer.ibm.core.network.API
import dalian.razvan.cucer.ibm.core.network.Result
import dalian.razvan.cucer.ibm.core.network.model.APIResponse
import dalian.razvan.cucer.ibm.core.network.safeApiCall
import dalian.razvan.cucer.ibm.models.Currency
import dalian.razvan.cucer.ibm.models.Rate
import dalian.razvan.cucer.ibm.models.SKUValue
import dalian.razvan.cucer.ibm.models.Transaction
class IBMRepositoryImpl(private val api: API): IBMRepository {
private lateinit var selectedCurrency: Currency
private val rates = arrayListOf<Rate>()
private val transactions = arrayListOf<Transaction>()
private val skuValues = arrayListOf<SKUValue>()
private val currencies = arrayListOf<Currency>()
private val currenciesNames = arrayListOf<String>()
override suspend fun loadRates(): Result<ArrayList<Rate>?> = safeApiCall {
api.getRates()
}
override suspend fun loadTransactions(): Result<ArrayList<Transaction>?> = safeApiCall {
api.getTransactions()
}
override fun setRates(list: ArrayList<Rate>) {
Log.e(javaClass.simpleName, "rates $list")
this.rates.addAll(list)
}
override fun setTransactions(list: ArrayList<Transaction>) {
Log.e(javaClass.simpleName, "transactions $list")
this.transactions.addAll(list)
}
override fun setSKUValues(list: ArrayList<SKUValue>) {
Log.e(javaClass.simpleName, "skuValues $list")
this.skuValues.addAll(list)
}
override fun setCurrencies(list: ArrayList<Currency>) {
Log.e(javaClass.simpleName, "currencies $list")
this.currencies.addAll(list)
}
override fun setCurrenciesNames(list: ArrayList<String>) {
this.currenciesNames.addAll(list)
}
override fun setSelectedCurrency(item: Currency) {
this.selectedCurrency = item
}
override fun getRates(): ArrayList<Rate> = rates
override fun getSKUValues(): ArrayList<SKUValue> =skuValues
override fun getTransactions(): ArrayList<Transaction> = transactions
override fun getCurrencies(): ArrayList<Currency> = currencies
override fun getCurrenciesNames(list: ArrayList<String>) = currenciesNames
override fun getSelectedCurrency(): Currency = selectedCurrency
}
| 0
|
Kotlin
|
0
| 0
|
f1c87dd1745ee8477d486b036dc5c45aacabe59e
| 2,341
|
IBM
|
Apache License 2.0
|
kotlin/aoc2018/src/test/kotlin/Day04Tests.kt
|
aochsner
| 160,386,044
| false
| null |
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.io.File
class Day04Tests {
@Test
fun `example part 1`() {
// act
val result = Day04().part1(listOf(
"[1518-11-01 00:00] Guard #10 begins shift",
"[1518-11-01 00:05] falls asleep",
"[1518-11-01 00:25] wakes up",
"[1518-11-01 00:30] falls asleep",
"[1518-11-01 00:55] wakes up",
"[1518-11-01 23:58] Guard #99 begins shift",
"[1518-11-02 00:40] falls asleep",
"[1518-11-02 00:50] wakes up",
"[1518-11-03 00:05] Guard #10 begins shift",
"[1518-11-03 00:24] falls asleep",
"[1518-11-03 00:29] wakes up",
"[1518-11-04 00:02] Guard #99 begins shift",
"[1518-11-04 00:36] falls asleep",
"[1518-11-04 00:46] wakes up",
"[1518-11-05 00:03] Guard #99 begins shift",
"[1518-11-05 00:45] falls asleep",
"[1518-11-05 00:55] wakes up"
))
// assert
assertThat(result).isEqualTo(240)
}
@Test
fun `do it part 1`() {
// arrange
val values = File(this.javaClass.getResource("input_day4").toURI()).readLines()
// act
val result = Day04().part1(values)
// assert
assertThat(result).isEqualTo(4716)
}
@Test
fun `example part 2`() {
// act
val result = Day04().part2(listOf(
"[1518-11-01 00:00] Guard #10 begins shift",
"[1518-11-01 00:05] falls asleep",
"[1518-11-01 00:25] wakes up",
"[1518-11-01 00:30] falls asleep",
"[1518-11-01 00:55] wakes up",
"[1518-11-01 23:58] Guard #99 begins shift",
"[1518-11-02 00:40] falls asleep",
"[1518-11-02 00:50] wakes up",
"[1518-11-03 00:05] Guard #10 begins shift",
"[1518-11-03 00:24] falls asleep",
"[1518-11-03 00:29] wakes up",
"[1518-11-04 00:02] Guard #99 begins shift",
"[1518-11-04 00:36] falls asleep",
"[1518-11-04 00:46] wakes up",
"[1518-11-05 00:03] Guard #99 begins shift",
"[1518-11-05 00:45] falls asleep",
"[1518-11-05 00:55] wakes up"
))
// assert
assertThat(result).isEqualTo(4455)
}
@Test
fun `do it part 2`() {
// arrange
val values = File(this.javaClass.getResource("input_day4").toURI()).readLines()
// act
val result = Day04().part2(values)
// assert
assertThat(result).isEqualTo(117061)
}
}
| 0
|
Kotlin
|
0
| 1
|
7c42ec9c20147c4be056d03e5a1492c137e63615
| 2,605
|
adventofcode2018
|
MIT License
|
android/src/main/kotlin/com/adyen/checkout/flutter/components/card/session/CardSessionCallback.kt
|
Adyen
| 665,573,538
| false
|
{"Dart": 324930, "Swift": 211098, "Kotlin": 197710, "Ruby": 2348, "Objective-C": 38}
|
package com.adyen.checkout.flutter.components.card.session
import ComponentFlutterInterface
import com.adyen.checkout.card.CardComponentState
import com.adyen.checkout.components.core.action.Action
import com.adyen.checkout.flutter.components.ComponentHeightMessenger
import com.adyen.checkout.flutter.components.base.ComponentSessionCallback
class CardSessionCallback(
private val componentFlutterApi: ComponentFlutterInterface,
private val componentId: String,
private val onActionCallback: (Action) -> Unit,
private val assignCurrentComponent: () -> Unit
) : ComponentSessionCallback<CardComponentState>(componentFlutterApi, componentId, onActionCallback) {
override fun onStateChanged(state: CardComponentState) {
ComponentHeightMessenger.sendResult(1)
}
override fun onSubmit(state: CardComponentState): Boolean {
assignCurrentComponent()
return super.onSubmit(state)
}
}
| 5
|
Dart
|
3
| 17
|
c7d5a08ef12335410898e0c3c854047d4fbc4e28
| 936
|
adyen-flutter
|
MIT License
|
src/test/kotlin/no/nav/familie/ef/mottak/api/SøknadControllerTest.kt
|
blommish-test
| 359,384,928
| true
|
{"Kotlin": 312719, "Shell": 269, "Dockerfile": 141}
|
package no.nav.familie.ef.mottak.api
import no.nav.familie.ef.mottak.IntegrasjonSpringRunnerTest
import no.nav.familie.ef.mottak.service.Testdata.søknadBarnetilsyn
import no.nav.familie.ef.mottak.service.Testdata.søknadOvergangsstønad
import no.nav.familie.ef.mottak.service.Testdata.søknadSkolepenger
import no.nav.familie.http.client.MultipartBuilder
import no.nav.familie.kontrakter.ef.søknad.SøknadMedVedlegg
import no.nav.familie.kontrakter.ef.søknad.Vedlegg
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.boot.test.web.client.exchange
import org.springframework.http.*
import org.springframework.test.context.ActiveProfiles
import java.util.*
@ActiveProfiles("local")
internal class SøknadControllerTest : IntegrasjonSpringRunnerTest() {
@BeforeEach
fun setUp() {
headers.setBearerAuth(lokalTestToken)
}
@Test
internal fun `overgangsstønad ok request`() {
verifySøknadMedVedleggRequest(SøknadMedVedlegg(søknadOvergangsstønad, listOf(lagVedlegg(), lagVedlegg())), "/api/soknad")
verifySøknadMedVedleggRequest(SøknadMedVedlegg(søknadOvergangsstønad, listOf(lagVedlegg(), lagVedlegg())),
"/api/soknad/overgangsstonad")
}
@Test
internal fun `barnetilsyn ok request`() {
val søknad = SøknadMedVedlegg(søknadBarnetilsyn, listOf(lagVedlegg(), lagVedlegg()))
verifySøknadMedVedleggRequest(søknad, "/api/soknad/barnetilsyn")
}
@Test
internal fun `skolepenger ok request`() {
val søknad = SøknadMedVedlegg(søknadSkolepenger, listOf(lagVedlegg(), lagVedlegg()))
verifySøknadMedVedleggRequest(søknad, "/api/soknad/skolepenger")
}
@Test
internal fun `det skal ikke være mulig å sende inn samme vedlegg på nytt med ny søknad`() {
val vedleggId = UUID.randomUUID().toString()
val søknad = SøknadMedVedlegg(søknadOvergangsstønad, listOf(lagVedlegg(vedleggId)))
verifySøknadMedVedleggRequest(søknad, "/api/soknad/overgangsstonad")
verifySøknadMedVedleggRequest(søknad, "/api/soknad/overgangsstonad", HttpStatus.BAD_REQUEST)
}
@Test
internal fun `vedlegg savnes i json`() {
headers.set(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
val request = MultipartBuilder()
.withJson("søknad", SøknadMedVedlegg(søknadOvergangsstønad, listOf(lagVedlegg())))
.build()
val response: ResponseEntity<Any> =
restTemplate.exchange(localhost("/api/soknad"),
HttpMethod.POST,
HttpEntity(request, headers))
assertThat(response.statusCode).isEqualTo(HttpStatus.BAD_REQUEST)
}
@Test
internal fun `vedlegg savnes i listen med vedlegg`() {
headers.set(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
val request = MultipartBuilder()
.withJson("søknad", SøknadMedVedlegg(søknadOvergangsstønad, listOf(lagVedlegg("1"))))
.withByteArray("vedlegg", "1", byteArrayOf(12))
.withByteArray("vedlegg", "2", byteArrayOf(12))
.build()
val response: ResponseEntity<Any> =
restTemplate.exchange(localhost("/api/soknad"),
HttpMethod.POST,
HttpEntity(request, headers))
assertThat(response.statusCode).isEqualTo(HttpStatus.BAD_REQUEST)
}
private fun <T> verifySøknadMedVedleggRequest(søknad: SøknadMedVedlegg<T>,
url: String,
forventetHttpStatus: HttpStatus = HttpStatus.OK) {
headers.set(HttpHeaders.CONTENT_TYPE, MediaType.MULTIPART_FORM_DATA_VALUE)
val multipartBuilder = MultipartBuilder()
.withJson("søknad", søknad)
søknad.vedlegg.forEach {
multipartBuilder.withByteArray("vedlegg", it.id, byteArrayOf(12))
}
val response: ResponseEntity<Any> =
restTemplate.exchange(localhost(url),
HttpMethod.POST,
HttpEntity(multipartBuilder.build(), headers))
assertThat(response.statusCode).isEqualTo(forventetHttpStatus)
}
private fun lagVedlegg(id: String = UUID.randomUUID().toString()) = Vedlegg(id, "navn", "tittel")
}
| 0
| null |
0
| 0
|
9719027a081bd3255bb3f429585612c90ec4f57d
| 4,552
|
familie-ef-mottak
|
MIT License
|
sourceamazing-schema/src/main/kotlin/org/codeblessing/sourceamazing/schema/datacollection/validation/exceptions/UnknownConceptException.kt
|
code-blessing
| 695,574,460
| false
|
{"Kotlin": 325769}
|
package org.codeblessing.sourceamazing.schema.datacollection.validation.exceptions
class UnknownConceptException(msg: String): SchemaValidationException(msg)
| 4
|
Kotlin
|
0
| 0
|
1d5545d838b18b74912d96be80e5acaa177fcdbe
| 160
|
sourceamazing
|
MIT License
|
library/src/main/kotlin/com/android/pandora/display/ClaysAdapter.kt
|
contafu
| 193,933,691
| false
|
{"Gradle": 5, "Markdown": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "INI": 2, "Proguard": 2, "XML": 22, "Kotlin": 13, "Java": 3}
|
package com.android.pandora.display
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.android.pandora.Clay
import com.android.pandora.R
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import java.io.File
import java.util.*
/**
* Created by tangchao on 2017/8/8.
*/
internal class ClaysAdapter(val context: Context, private val arrayList: MutableList<Clay>, private val block: ((Clay) -> Unit)) : RecyclerView.Adapter<ClaysAdapter.Holder>() {
override fun getItemCount(): Int = arrayList.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
val view: View = LayoutInflater.from(context).inflate(R.layout.lib_pandora_adapter_album_item, parent, false)
return Holder(view)
}
override fun onBindViewHolder(holder: Holder, position: Int) {
val `var` = arrayList[position]
val view = holder.imageView
if (null != view) {
Glide.with(context)
.load(File(`var`.data))
.apply(RequestOptions().centerInside())
.thumbnail(0.1f)
.into(view)
}
holder.name?.text = `var`.name
holder.count?.text = String.format(Locale.CHINA, context.resources.getString(R.string.lib_pandora_number), `var`.count)
if (`var`.check) {
holder.checkBox?.visibility = View.VISIBLE
} else {
holder.checkBox?.visibility = View.INVISIBLE
}
holder.itemView?.setOnClickListener {
block.invoke(arrayList[position])
if (!`var`.check) {
`var`.check = true
highlightItem(position)
}
}
}
inner class Holder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var imageView = itemView.findViewById<ImageView?>(R.id.lib_pandora_adapter_album_image_view)
var checkBox = itemView.findViewById<ImageView?>(R.id.lib_pandora_adapter_album_check_box)
var name = itemView.findViewById<TextView?>(R.id.lib_pandora_adapter_album_name)
var count = itemView.findViewById<TextView?>(R.id.lib_pandora_adapter_album_count)
}
fun update(arrayList: MutableList<Clay>) {
this.arrayList.clear()
this.arrayList.addAll(arrayList)
notifyDataSetChanged()
}
/**
* 高亮指定条目
*/
private fun highlightItem(position: Int) {
arrayList.forEach {
it.check = false
}
arrayList[position].check = true
notifyDataSetChanged()
}
}
| 0
|
Kotlin
|
0
| 2
|
cc5e498252015c81045154da1ab3e5542e342d01
| 2,756
|
pandora
|
Apache License 2.0
|
dorm/core/src/main/kotlin/org/sirius/dorm/json/ObjectModule.kt
|
coolsamson7
| 856,851,180
| false
|
{"Kotlin": 243947, "ANTLR": 13837}
|
package org.sirius.dorm.json
import org.sirius.dorm.`object`.DataObject
import com.fasterxml.jackson.databind.module.SimpleDeserializers
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.databind.module.SimpleSerializers
class ObjectModule: SimpleModule() {
// override
override fun getModuleName(): String = this.javaClass.simpleName
override fun setupModule(context: SetupContext) {
// serializer
val serializers = SimpleSerializers()
serializers.addSerializer(DataObject::class.java, ObjectSerializer())
context.addSerializers(serializers)
// deserializer
val deserializers = SimpleDeserializers()
deserializers.addDeserializer(DataObject::class.java, ObjectDeserializer())
context.addDeserializers(deserializers)
}
}
| 0
|
Kotlin
|
0
| 1
|
85c2da7608171bb0703d974a5ac0b3ce6034515e
| 848
|
dorm
|
Apache License 2.0
|
zeppelin/implementation/src/org/intellij/plugin/zeppelin/api/remote/rest/RestApiException.kt
|
veor12
| 124,130,369
| false
|
{"Kotlin": 158204, "Java": 36950, "Scala": 5054}
|
package org.intellij.plugin.zeppelin.api.remote.rest
import org.intellij.plugin.zeppelin.models.ZeppelinException
data class RestApiException(val customMessage: String, val error: String) : ZeppelinException() {
override val message: String
get() = "$customMessage.\nError: $error"
}
| 5
|
Kotlin
|
1
| 1
|
90dfce523d9ccca40d0001158ce4117eb2c18780
| 297
|
Zeppelin-Remote-Run
|
Apache License 2.0
|
cottontaildb-dbms/src/main/kotlin/org/vitrivr/cottontail/dbms/index/pq/rebuilder/AsyncPQIndexRebuilder.kt
|
vitrivr
| 160,775,368
| false
|
{"Kotlin": 2769415, "TypeScript": 98011, "Java": 97672, "HTML": 38965, "ANTLR": 23679, "CSS": 8582, "SCSS": 1690, "JavaScript": 1441, "Dockerfile": 548}
|
package org.vitrivr.cottontail.dbms.index.pq.rebuilder
import jetbrains.exodus.env.Store
import jetbrains.exodus.env.StoreConfig
import org.vitrivr.cottontail.core.database.ColumnDef
import org.vitrivr.cottontail.core.database.TupleId
import org.vitrivr.cottontail.core.queries.functions.Signature
import org.vitrivr.cottontail.core.queries.functions.math.distance.binary.VectorDistance
import org.vitrivr.cottontail.core.types.Types
import org.vitrivr.cottontail.core.types.VectorValue
import org.vitrivr.cottontail.dbms.catalogue.entries.IndexStructCatalogueEntry
import org.vitrivr.cottontail.dbms.catalogue.entries.NameBinding
import org.vitrivr.cottontail.dbms.catalogue.storeName
import org.vitrivr.cottontail.dbms.catalogue.toKey
import org.vitrivr.cottontail.dbms.events.DataEvent
import org.vitrivr.cottontail.dbms.exceptions.DatabaseException
import org.vitrivr.cottontail.dbms.index.basic.IndexMetadata
import org.vitrivr.cottontail.dbms.index.basic.rebuilder.AbstractAsyncIndexRebuilder
import org.vitrivr.cottontail.dbms.index.basic.rebuilder.IndexRebuilderState
import org.vitrivr.cottontail.dbms.index.pq.PQIndex
import org.vitrivr.cottontail.dbms.index.pq.PQIndexConfig
import org.vitrivr.cottontail.dbms.index.pq.quantizer.SerializableSingleStageProductQuantizer
import org.vitrivr.cottontail.dbms.index.pq.quantizer.SingleStageQuantizer
import org.vitrivr.cottontail.dbms.index.pq.signature.SPQSignature
import org.vitrivr.cottontail.dbms.index.va.rebuilder.AsyncVAFIndexRebuilder
import org.vitrivr.cottontail.dbms.queries.context.QueryContext
import java.util.concurrent.ConcurrentLinkedQueue
/**
* An [AbstractAsyncIndexRebuilder] that can be used to concurrently rebuild a [PQIndex].
*
* @author Ralph Gasser
* @version 1.0.0
*/
class AsyncPQIndexRebuilder(index: PQIndex, context: QueryContext): AbstractAsyncIndexRebuilder<PQIndex>(index, context.catalogue, context.txn.manager) {
/** The (temporary) Xodus [Store] used to store [SPQSignature]s. */
private val tmpDataStore: Store = this.tmpEnvironment.openStore(this.index.name.storeName(), StoreConfig.WITHOUT_DUPLICATES, this.tmpTx, true)
?: throw DatabaseException.DataCorruptionException("Temporary data store for index ${this.index.name} could not be created.")
/** Reference to [SingleStageQuantizer] used by this [AsyncPQIndexRebuilder] (only available after [IndexRebuilderState.INITIALIZED]). */
private val newQuantizer: SingleStageQuantizer
/** Reference to [ColumnDef] indexed by this [AsyncPQIndexRebuilder] (only available after [IndexRebuilderState.INITIALIZED]). */
private val indexedColumn: ColumnDef<*>
/** A [ConcurrentLinkedQueue] that acts as log for side-channel events. TODO: Make persistent. */
private val log = ConcurrentLinkedQueue<PQIndexingEvent>()
init {
/* Read basic index properties. */
val indexMetadataStore = IndexMetadata.store(this.index.catalogue, context.txn.xodusTx)
val indexEntryRaw = indexMetadataStore.get(context.txn.xodusTx, NameBinding.Index.toEntry(this@AsyncPQIndexRebuilder.index.name)) ?: throw DatabaseException.DataCorruptionException("Failed to rebuild index ${this@AsyncPQIndexRebuilder.index.name}: Could not read catalogue entry for index.")
val indexEntry = IndexMetadata.fromEntry(indexEntryRaw)
val config = indexEntry.config as PQIndexConfig
val column = this.index.name.entity().column(indexEntry.columns[0])
/* Tx objects required for index rebuilding. */
val entityTx = this.index.parent.newTx(context)
val columnTx = entityTx.columnForName(column).newTx(context)
val count = entityTx.count()
this.indexedColumn = columnTx.columnDef
/* Generate and obtain signature and distance function. */
val signature = Signature.Closed(config.distance, arrayOf(this.indexedColumn.type, this.indexedColumn.type), Types.Double)
val distanceFunction: VectorDistance<*> = this.index.catalogue.functions.obtain(signature) as VectorDistance<*>
/* Generates new product quantize. */
val fraction = ((3.0f * config.numCentroids) / count)
val seed = System.currentTimeMillis()
val learningData = DataCollectionUtilities.acquireLearningData(columnTx, fraction, seed)
this.newQuantizer = SingleStageQuantizer.learnFromData(distanceFunction, learningData, config)
}
/**
* Internal scan method that is being executed when executing the BUILD stage of this [AsyncPQIndexRebuilder].
*
* @param context The [QueryContext] to execute the BUILD stage in.
* @return True on success, false otherwise.
*/
override fun internalBuild(context: QueryContext): Boolean {
/* Tx objects required for index rebuilding. */
val entityTx = this.index.parent.newTx(context)
val columnTx = entityTx.columnForName(this.indexedColumn.name).newTx(context)
val count = entityTx.count()
/* Iterate over entity and update index with entries. */
var counter = 0
columnTx.cursor().use { cursor ->
while (cursor.hasNext()) {
if (this.state != IndexRebuilderState.REBUILDING) return false
val value = cursor.value()
if (value is VectorValue<*>) {
if (!this.tmpDataStore.add(this.tmpTx, cursor.key().toKey(), this.newQuantizer.quantize(value).toEntry())) {
return false
}
if ((++counter) % 1_000_000 == 0) {
LOGGER.debug("Rebuilding index (SCAN) {} ({}) still running ({} / {})...", this.index.name, this.index.type, counter, count)
if (!this.tmpTx.flush()) {
return false
}
}
}
}
}
return true
}
/**
* Internal merge method that is being executed when executing the MERGE stage of this [AsyncVAFIndexRebuilder].
*
* @param context The [QueryContext] to execute the MERGE stage in.
* @param store The [Store] to merge data into.
* @return True on success, false otherwise.
*/
override fun internalReplace(context: QueryContext, store: Store): Boolean {
/* Start replacement process. */
val count = this.tmpDataStore.count(this.tmpTx)
this.tmpDataStore.openCursor(this.tmpTx).use { cursor ->
var counter = 0
while (cursor.next) {
if (this.state != IndexRebuilderState.REPLACING) return false
if (!store.add(context.txn.xodusTx, cursor.key, cursor.value)) {
return false
}
/* Data is flushed every once in a while. */
if ((++counter) % 1_000_000 == 0) {
LOGGER.debug("Rebuilding index (MERGE) {} ({}) still running ({} / {})...", this.index.name, this.index.type, counter, count)
if (!context.txn.xodusTx.flush()) {
return false
}
}
}
}
/* Update stored ProductQuantizer. */
IndexStructCatalogueEntry.write(this.index.name, this.newQuantizer.toSerializableProductQuantizer(), this.index.catalogue, context.txn.xodusTx, SerializableSingleStageProductQuantizer.Binding)
return true
}
/**
* Processes a [DataEvent] received from the side-channel, converts it to a [PQIndexingEvent] and appends it to the log.
*
* @param event The [DataEvent] that should be processed,
*/
override fun processSideChannelEvent(event: DataEvent): Boolean = when(event) {
/* Process side-channel INSERT. */
is DataEvent.Insert -> {
val value = event.data[this.indexedColumn]
if (value is VectorValue<*>) {
this.log.offer(PQIndexingEvent.Set(event.tupleId, this.newQuantizer.quantize(value)))
}
true
}
/* Process side-channel DELETE. */
is DataEvent.Delete -> {
val value = event.data[this.indexedColumn]
if (value != null) {
this.log.offer(PQIndexingEvent.Unset(event.tupleId))
}
true
}
/* Process side-channel UPDATE. */
is DataEvent.Update -> {
/* Extract value and perform sanity check. */
val oldValue = event.data[this.indexedColumn]?.first
val newValue = event.data[this.indexedColumn]?.second
/* Obtain marks and update them. */
if (newValue is VectorValue<*>) { /* Case 1: New value is not null, i.e., update to new value. */
this.log.offer(PQIndexingEvent.Set(event.tupleId, this.newQuantizer.quantize(newValue)))
} else if (oldValue is VectorValue<*>) { /* Case 2: New value is null but old value wasn't, i.e., delete index entry. */
this.log.offer(PQIndexingEvent.Unset(event.tupleId))
}
true
}
}
/**
* Drains and processes all [PQIndexingEvent]s that are currently waiting on the [log].
*
* @return True on success, false otherwise.
*/
override fun drainAndMergeLog(): Boolean {
var next = this.log.poll()
while (next != null) {
val success = when (next) {
is PQIndexingEvent.Set -> this.tmpDataStore.put(this.tmpTx, next.tupleId.toKey(), next.signature.toEntry())
is PQIndexingEvent.Unset -> this.tmpDataStore.delete(this.tmpTx, next.tupleId.toKey())
}
if (!success) return false
next = this.log.poll()
}
return true
}
/**
* An internal helper interface used by the [AsyncPQIndexRebuilder].
*
* Every [DataEvent] is converted to a [PQIndexingEvent.Set] or [PQIndexingEvent.Unset].
* Order of operations is ensured by the log.
*/
private sealed interface PQIndexingEvent {
val tupleId: TupleId
/**
* A log entry that signifies the appending of a [SPQSignature] to the index.
*/
data class Set(override val tupleId: TupleId, val signature: SPQSignature): PQIndexingEvent
/**
* A log entry that signifies the removal of a [SPQSignature] from the index.
*/
data class Unset(override val tupleId: TupleId): PQIndexingEvent
}
}
| 24
|
Kotlin
|
20
| 38
|
bc4d0aa435aac78628fa7771dbf8333f1fe5a971
| 10,500
|
cottontaildb
|
MIT License
|
app/src/main/java/com/yamin/chatchat/MainActivity.kt
|
YaminArafat
| 609,940,129
| false
| null |
package com.yamin.chatchat
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.yamin.chatchat.fragments.AppWelcomeScreenFragment
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setWelcomeScreenFragment()
}
private fun setWelcomeScreenFragment(){
val welcomeScreenFragment = AppWelcomeScreenFragment()
supportFragmentManager.beginTransaction().add(R.id.main_activity_fragment_container, welcomeScreenFragment).commit()
}
}
| 0
|
Kotlin
|
0
| 0
|
88b605caa6e2f22f166cfdfc6ccb0d82b9ebc6b8
| 635
|
ChatChat
|
Apache License 2.0
|
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/inspect/XmlPluginsSpecificationProvider.kt
|
JetBrains
| 49,584,664
| false
|
{"Kotlin": 2711266, "C#": 319161, "Java": 95520, "Dockerfile": 831, "CSS": 123}
|
package jetbrains.buildServer.inspect
import jetbrains.buildServer.XmlElement
import jetbrains.buildServer.agent.Version
import jetbrains.buildServer.agent.runner.LoggerService
import java.io.ByteArrayOutputStream
class XmlPluginsSpecificationProvider(
private val _pluginDescriptorsProvider: PluginDescriptorsProvider,
private val _xmlWriter: XmlWriter,
private val _loggerService: LoggerService,
xmlElementGenerators: List<PluginXmlElementGenerator>
) : PluginsSpecificationProvider {
private val _sourceIdToXmlElementGenerator = xmlElementGenerators.associateBy { it.sourceId.lowercase() }
override fun getPluginsSpecification(): String? {
val pluginXmlElements = _pluginDescriptorsProvider.getPluginDescriptors()
.mapNotNull {
if (PluginDescriptorType.SOURCE == it.type) {
val matchResult = PluginDescriptorType.SOURCE.regex.matchEntire(it.value)
if (matchResult != null) {
val sourceId = matchResult.groupValues[1]
val value = matchResult.groupValues[2]
val generator = _sourceIdToXmlElementGenerator[sourceId.lowercase()]
if (generator != null) {
return@mapNotNull generator.generateXmlElement(value)
}
}
}
logInvalidDescriptor(it)
return@mapNotNull null
}
val pluginsXmlElement = XmlElement("Packages", pluginXmlElements.asSequence())
if (!pluginsXmlElement.isEmpty) {
ByteArrayOutputStream().use {
_xmlWriter.write(pluginsXmlElement, it)
return it.toString(Charsets.UTF_8.name())
}
}
return null
}
private fun logInvalidDescriptor(pluginDescriptor: PluginDescriptor) = _loggerService.writeWarning(
"Invalid R# CLT plugin descriptor: \"${pluginDescriptor.value}\", " +
"R# CLT versions below ${Version.FirstInspectCodeWithExtensionsOptionVersion} support only " +
"${_sourceIdToXmlElementGenerator.keys} descriptors, it will be ignored."
)
}
| 3
|
Kotlin
|
25
| 94
|
c7f12409b67420d5655780ce6e50638ce4ca1f8d
| 2,226
|
teamcity-dotnet-plugin
|
Apache License 2.0
|
simplified-main/src/main/java/org/librarysimplified/main/MainTransifex.kt
|
NatLibFi
| 730,988,035
| false
|
{"Kotlin": 3589739, "JavaScript": 853788, "Java": 403841, "CSS": 65407, "HTML": 49894, "Shell": 18611, "Ruby": 7554}
|
package org.librarysimplified.main
import android.content.Context
import com.transifex.txnative.LocaleState
import com.transifex.txnative.TxNative
import com.transifex.txnative.missingpolicy.WrappedStringPolicy
import fi.kansalliskirjasto.ekirjasto.util.SecretsUtil
import java.io.FileNotFoundException
import java.util.Properties
import org.slf4j.LoggerFactory
/**
* Functions to enable Transifex string translation.
*/
object MainTransifex {
private val logger = LoggerFactory.getLogger(MainTransifex::class.java)
/**
* Configure Transifex.
*
* Will warn about an empty token for Transifex, if not set.
*/
@Suppress("KotlinConstantConditions")
fun configure(applicationContext: Context) {
this.logger.debug("MainTransifex.configure()")
val transifexToken = SecretsUtil.getTransifexToken()
if (transifexToken.isBlank()) {
logger.warn("Transifex token not set, Transifex will only use cached localizations")
}
val languages = BuildConfig.LANGUAGES.split(",")
this.logger.debug("Languages: " + languages.joinToString(", "))
val localeState =
LocaleState(
applicationContext,
languages.first(),
languages.toTypedArray(),
null
)
val stringPolicy =
if (BuildConfig.DEBUG) {
WrappedStringPolicy("[[", "]]")
} else {
WrappedStringPolicy(null, null)
}
this.logger.debug("Initializing Transifex")
TxNative.init(
applicationContext,
localeState,
transifexToken,
null,
null,
stringPolicy
)
this.logger.debug("Retrieving Transifex string translations")
TxNative.fetchTranslations(null, null)
}
}
| 1
|
Kotlin
|
0
| 0
|
e4fc752f3cba3427d3822ccae259c57983488e46
| 1,691
|
ekirjasto-android-core
|
Apache License 2.0
|
business/splash/src/test/java/com/alessandrocandolini/splash/WeatherApiTest.kt
|
alessandrocandolini
| 297,105,248
| false
| null |
package com.alessandrocandolini.splash
import com.alessandrocandolini.withMockServer
import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.collections.shouldBeIn
import io.kotest.property.Exhaustive
import io.kotest.property.Gen
import io.kotest.property.checkAll
import io.kotest.property.exhaustive.collection
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.mockwebserver.Dispatcher
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.RecordedRequest
import retrofit2.Retrofit
import retrofit2.create
class WeatherApiTest : FunSpec() {
init {
test("WeatherApi can correctly return parsed responses when the server return 200 with valid json response body") {
withMockServer { server ->
val validJsonResponses: Gen<String> = Exhaustive.collection(
setOf(
"""
{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03n"}],"base":"stations","main":{"temp":279.48,"feels_like":276.56,"temp_min":278.71,"temp_max":280.37,"pressure":1017,"humidity":81},"visibility":10000,"wind":{"speed":2.1,"deg":50},"clouds":{"all":40},"dt":1606501853,"sys":{"type":1,"id":1414,"country":"GB","sunrise":1606462727,"sunset":1606492689},"timezone":0,"id":2643743,"name":"London","cod":200}
""",
"""
{"coord":{"lon":147.22,"lat":-9.52},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03n"}],"base":"stations","main":{"temp":296.15,"feels_like":298.32,"temp_min":296.15,"temp_max":296.15,"pressure":1007,"humidity":94},"visibility":10000,"wind":{"speed":3.6,"deg":320},"clouds":{"all":40},"dt":1606503876,"sys":{"type":1,"id":42,"country":"PG","sunrise":1606506038,"sunset":1606551473},"timezone":36000,"id":2088122,"name":"Pari","cod":200}
""",
"""
{"coord":{"lon":-10.59,"lat":6.65},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03n"}],"base":"stations","main":{"temp":301.15,"feels_like":306.42,"temp_min":301.15,"temp_max":301.15,"pressure":1010,"humidity":83},"visibility":10000,"wind":{"speed":1.5,"deg":190},"clouds":{"all":40},"dt":1606503899,"sys":{"type":1,"id":2389,"country":"LR","sunrise":1606459026,"sunset":1606501412},"timezone":0,"id":2274890,"name":"New","cod":200}
"""
).map { it.trimIndent() }
)
val retrofit = Retrofit.Builder()
.addConverterFactory(Json {
ignoreUnknownKeys = true
}.asConverterFactory("application/json".toMediaType()))
.baseUrl(server.url("/"))
.build()
val weatherApi: WeatherApi = retrofit.create()
checkAll(validJsonResponses) { body ->
server.dispatcher = object : Dispatcher() {
override fun dispatch(request: RecordedRequest): MockResponse =
when (request.requestUrl?.encodedPath) {
"/data/2.5/weather" -> MockResponse().setResponseCode(200)
.setBody(body)
else -> MockResponse().setResponseCode(404)
}
}
weatherApi.fetchByCityName(city = "anyCity") shouldBeIn listOf(
WeatherResponse(2643743, "London"),
WeatherResponse(2088122, "Pari"),
WeatherResponse(2274890, "New"),
)
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
e6a7108aacbc18f173e42e20c5213ba7de835997
| 3,862
|
di-alternatives
|
MIT License
|
Sample/sdkA/src/main/kotlin/io/popbrain/sdk/a/HelloWorkImpl.kt
|
Popbrain
| 236,398,711
| false
| null |
package io.popbrain.sdk.a
import io.popbrain.hellowork.HelloWork
import io.popbrain.hellowork.Job
import io.popbrain.sdk.a.api.WorkerResultHandlingAdapter
class HelloWorkImpl {
companion object {
fun <T: Job> build(job: Class<T>): T {
return HelloWork.Dispatcher()
.addFrontDeskAdapterFactory(WorkerResultHandlingAdapter.AdapterFactory())
.build()
.callWorker(job)
}
}
}
| 0
|
Kotlin
|
0
| 2
|
9a9eb133bb7c1712113e0001e5f52e653ab36023
| 460
|
HelloWork
|
Apache License 2.0
|
app/src/main/java/jp/juggler/subwaytooter/api/entity/TootApplication.kt
|
geckour
| 143,372,698
| true
|
{"Java Properties": 2, "Perl": 4, "Text": 11, "JSON": 6, "Gradle": 9, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Ignore List": 8, "Git Config": 1, "Proguard": 6, "XML": 120, "Java": 34, "INI": 1, "Kotlin": 211}
|
package jp.juggler.subwaytooter.api.entity
import org.json.JSONObject
import jp.juggler.subwaytooter.util.parseString
class TootApplication(
val name : String?,
@Suppress("unused") private val website : String?
) {
constructor(src : JSONObject) : this(
name = src.parseString("name"),
website = src.parseString("website")
)
}
| 0
|
Java
|
0
| 0
|
881a9fda46051ae55630d9c8d473853e78a45ecc
| 339
|
SubwayTooter
|
Apache License 2.0
|
src/main/kotlin/before/청년이룸_과제3/ATM/Main.kt
|
K-Diger
| 642,489,846
| false
|
{"Kotlin": 105578, "Java": 49568}
|
package before.청년이룸_과제3.ATM
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
private val br = BufferedReader(InputStreamReader(System.`in`))
private val bw = BufferedWriter(OutputStreamWriter(System.out))
fun main() {
val n = br.readLine().toInt()
val times = br.readLine().split(" ").map { it.toInt() }.toIntArray()
br.close()
times.sort()
var temp = 0
var totalTime = 0
for (time in times) {
temp += time
totalTime += temp
}
bw.write(totalTime.toString())
bw.close()
}
| 0
|
Kotlin
|
0
| 0
|
344cf6c78b6491460219d1c23e381d4beda1d839
| 611
|
algorithm-rehab
|
MIT License
|
mnn/src/main/java/ru/gordinmitya/mnn/ConvertedModel.kt
|
gordinmitya
| 229,242,123
| false
| null |
package ru.gordinmitya.mnn
import ru.gordinmitya.common.Model
import ru.gordinmitya.common.classification.MobileNetModel
import ru.gordinmitya.common.segmentation.DeepLabModel
class ConvertedModel<T> private constructor(
val model: T,
val fileName: String
) {
companion object {
val mobilenet_v2 = ConvertedModel(
MobileNetModel,
"mnn/mobilenet_v2.mnn"
)
val deeplab_v3 = ConvertedModel(
DeepLabModel,
"mnn/deeplab_v3.mnn"
)
fun <T : Model> getByModel(model: Model): ConvertedModel<T>? {
@Suppress("UNCHECKED_CAST")
return all.find {
it.model == model
} as ConvertedModel<T>?
}
val all = arrayListOf(
mobilenet_v2,
deeplab_v3
)
}
}
| 6
| null |
4
| 15
|
ee8363a47ac91602c8babf791aaf2423578b606c
| 840
|
dnn_benchmark
|
MIT License
|
core/nativeMain/src/kotlinx/serialization/internal/Platform.kt
|
Kotlin
| 97,827,246
| false
| null |
/*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.internal
import kotlinx.serialization.*
import kotlin.reflect.*
@Suppress("NOTHING_TO_INLINE")
internal actual inline fun <T> Array<T>.getChecked(index: Int): T {
return get(index)
}
@Suppress("NOTHING_TO_INLINE")
internal actual inline fun BooleanArray.getChecked(index: Int): Boolean {
return get(index)
}
internal actual fun KClass<*>.platformSpecificSerializerNotRegistered(): Nothing {
throw SerializationException(
"Serializer for class '${simpleName}' is not found.\n" +
"Mark the class as @Serializable or provide the serializer explicitly.\n" +
"On Kotlin/Native explicitly declared serializer should be used for interfaces and enums without @Serializable annotation"
)
}
@Suppress(
"UNCHECKED_CAST",
"DEPRECATION_ERROR"
)
@OptIn(ExperimentalAssociatedObjects::class)
internal actual fun <T : Any> KClass<T>.constructSerializerForGivenTypeArgs(vararg args: KSerializer<Any?>): KSerializer<T>? =
when (val assocObject = findAssociatedObject<SerializableWith>()) {
is KSerializer<*> -> assocObject as KSerializer<T>
is kotlinx.serialization.internal.SerializerFactory -> assocObject.serializer(*args) as KSerializer<T>
else -> null
}
@Suppress(
"UNCHECKED_CAST",
"DEPRECATION_ERROR"
)
@OptIn(ExperimentalAssociatedObjects::class)
internal actual fun <T : Any> KClass<T>.compiledSerializerImpl(): KSerializer<T>? =
this.constructSerializerForGivenTypeArgs()
internal actual fun <T : Any, E : T?> ArrayList<E>.toNativeArrayImpl(eClass: KClass<T>): Array<E> {
val result = arrayOfAnyNulls<E>(size)
var index = 0
for (element in this) result[index++] = element
@Suppress("UNCHECKED_CAST", "USELESS_CAST")
return result as Array<E>
}
@Suppress("UNCHECKED_CAST")
private fun <T> arrayOfAnyNulls(size: Int): Array<T> = arrayOfNulls<Any>(size) as Array<T>
internal actual fun Any.isInstanceOf(kclass: KClass<*>): Boolean = kclass.isInstance(this)
internal actual fun isReferenceArray(rootClass: KClass<Any>): Boolean = rootClass == Array::class
| 351
|
Kotlin
|
481
| 3,787
|
784892467f292dae27d3544148515795cd8eeee8
| 2,223
|
kotlinx.serialization
|
Apache License 2.0
|
batteryview/src/main/java/iam/thevoid/batteryview/BatteryView.kt
|
iamthevoid
| 108,580,690
| false
| null |
@file:Suppress("unused", "MemberVisibilityCanBePrivate")
package iam.thevoid.batteryview
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.content.ContextCompat
/**
* Created by iam on 24.10.17.
*/
class BatteryView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = -1
) : AppCompatImageView(context, attrs, defStyleAttr) {
companion object {
const val DEFAULT_BORDER_WIDTH = 0.06f
const val DEFAULT_INTERNAL_SPACING = 0.5f
}
private var batteryLevelPaint: Paint = Paint()
private var borderThickness = 0f
private var batteryLevelCornerRadius = 0f
private val rect = RectF(0f, 0f, 0f, 0f)
/**
* Border coefficient. Border is part of icon, so this is just relative dimension to draw other
* aspects
*/
private val borderThicknessPercent: Float = DEFAULT_BORDER_WIDTH
/**
* Charging percent
*/
var batteryLevel = 0
set(value) {
field = value.limit(0, 100)
invalidate()
}
var isCharging: Boolean = false
set(value) {
field = value
setImageResource(if (isCharging) R.drawable.ic_charging else R.drawable.ic_battery)
if (isCharging) setColorFilter(infillColor) else setColorFilter(borderColor)
invalidate()
}
/**
* View infill color.
*/
@ColorInt
var infillColor = Color.WHITE
set(newColor) {
if (isCharging) setColorFilter(newColor)
field = newColor
batteryLevelPaint = Paint().apply {
color = newColor
isAntiAlias = true
}
invalidate()
}
/**
* View border color
*/
@ColorInt
var borderColor = Color.BLACK
set(newBorderColor) {
field = newBorderColor
if (!isCharging) setColorFilter(newBorderColor)
}
/**
* Spacing between border and internal charge-level rect. Relative as [borderThicknessPercent],
* but relative to border thickness. Actually is percent of border thickness.
*/
var internalSpacing: Float = DEFAULT_INTERNAL_SPACING
set(value) {
field = value
invalidate()
}
init {
attrs?.also(::obtainAttributes)
super.setScaleType(ScaleType.FIT_XY)
super.setImageResource(R.drawable.ic_battery)
setWillNotDraw(false)
}
private fun obtainAttributes(attrs: AttributeSet) {
val a = context.theme.obtainStyledAttributes(
attrs,
R.styleable.BatteryView,
0, 0
)
try {
isCharging = a.getBoolean(R.styleable.BatteryView_bv_charging, false)
borderColor = a.getColor(R.styleable.BatteryView_bv_borderColor, Color.BLACK)
infillColor = a.getColor(R.styleable.BatteryView_bv_infillColor, Color.WHITE)
batteryLevel = a.getInteger(R.styleable.BatteryView_bv_percent, 0)
internalSpacing =
a.getFloat(R.styleable.BatteryView_bv_internalSpacing, DEFAULT_INTERNAL_SPACING)
} finally {
a.recycle()
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
var widthSpec = widthMeasureSpec
var heightSpec = heightMeasureSpec
val min = kotlin.math.min(MeasureSpec.getSize(widthSpec), MeasureSpec.getSize(heightSpec))
widthSpec =
MeasureSpec.makeMeasureSpec((min.toFloat() / 22f * 17f).toInt(), MeasureSpec.EXACTLY)
heightSpec =
MeasureSpec.makeMeasureSpec((min.toFloat() / 17f * 22f).toInt(), MeasureSpec.EXACTLY)
borderThickness = min.toFloat() * borderThicknessPercent
batteryLevelCornerRadius = borderThickness
super.onMeasure(widthSpec, heightSpec)
}
fun setInfillColorRes(@ColorRes colorRes: Int) {
infillColor = ContextCompat.getColor(context, colorRes)
}
fun setBorderColorRes(@ColorRes colorRes: Int) {
borderColor = ContextCompat.getColor(context, colorRes)
}
/**
* magic numbers for paddings of inside rect
* 4 is the two battery strokes and two spaces
* 6 is the stroke, battery top (3 x stroke) andtwo spaces
* 2 is the one stroke and one space
*/
override fun onDraw(canvas: Canvas) {
if (!isCharging) {
val rectMarginBorderMultiplier = 1 + internalSpacing
val width = getWidth().toFloat() - 2 * rectMarginBorderMultiplier * borderThickness
val height =
(getHeight().toFloat() - (2 + 2 * rectMarginBorderMultiplier) * borderThickness) * batteryLevel.toFloat() / 100f
val left = rectMarginBorderMultiplier * borderThickness
val top = getHeight().toFloat() - borderThickness * rectMarginBorderMultiplier - height
val right = left + width
val bottom = top + height
rect[left, top, right] = bottom
canvas.drawRoundRect(
rect,
batteryLevelCornerRadius,
batteryLevelCornerRadius,
batteryLevelPaint
)
}
super.onDraw(canvas)
}
}
private fun Float.limit(min: Float, max: Float): Float {
return if (this < min) min else if (this > max) max else this
}
private fun Int.limit(min: Int, max: Int): Int {
return if (this < min) min else if (this > max) max else this
}
| 1
| null |
1
| 17
|
fb5ce00e92b6e8029bcbb017fec2b682bb2d0924
| 5,776
|
battery-view-android
|
MIT License
|
quicklist-presentation/src/main/java/com/unatxe/quicklist/features/detailScreen/component/QListDetailColumn.kt
|
PepitoStudios
| 491,644,872
| false
| null |
package com.unatxe.quicklist.features.detailScreen.component
import android.util.Log
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.unatxe.quicklist.R
import com.unatxe.quicklist.components.QListDetailCheckItemComponent
import com.unatxe.quicklist.entities.qList.QListView
import com.unatxe.quicklist.entities.qList.item.QListItemTypesEnum
import com.unatxe.quicklist.entities.qList.item.QListItemView
import com.unatxe.quicklist.entities.qList.item.QListItemViewCheckBoxImpl
import com.unatxe.quicklist.features.detailScreen.DetailViewModelEvent
import kotlinx.coroutines.delay
@Composable
fun QListItemLazyComponent(
modifier: Modifier,
uiState: QListView,
eventEmitter: (event: DetailViewModelEvent) -> Unit
) {
val listState = rememberLazyListState() //
if (uiState.componentSelected.value != null) {
Log.d("Test", "Selected Mode ${uiState.componentSelected.value!!.text}")
LaunchedEffect(Unit) {
delay(100)
val index = uiState.items.indexOfFirst {
it == uiState.componentSelected.value
}
listState.scrollToItem(index)
}
}
if (uiState.isEditMode.value) {
LaunchedEffect(Unit) {
delay(100)
val index = uiState.items.indexOfFirst {
it == uiState.componentSelected.value
}
listState.scrollToItem(index)
}
}
LazyColumnComponent(
listState,
modifier,
uiState,
eventEmitter
)
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun LazyColumnComponent(
listState: LazyListState,
modifier: Modifier,
uiState: QListView,
eventEmitter: (event: DetailViewModelEvent) -> Unit
) {
val uiStateRemember = remember {
uiState
}
LazyColumn(
state = listState,
modifier = modifier,
userScrollEnabled = uiState.isEditMode.value.not()
) {
item { // Keep this for prevent the first item scrolling behaviour
Box() {
Text("")
}
}
items(
items = uiState.items,
key = { it.hashCode() },
contentType = { it.typeItem }
) { qLisItem ->
val animateComponentModifier = remember { Modifier.animateItemPlacement() }
val qListItemRemember = remember {
qLisItem
}
QListItemColumnComponent(
animateComponentModifier,
qListItemRemember,
uiStateRemember,
eventEmitter
)
}
item {
BoxWithConstraints(modifier = Modifier.height(400.dp)) {
Image(
modifier = Modifier.fillMaxWidth().fillMaxHeight(),
alignment = Alignment.BottomCenter,
painter = painterResource(id = R.drawable.item_list_empty),
contentDescription = stringResource(
id = R.string.item_list_empty
)
)
}
}
}
}
@Composable
fun QListItemColumnComponent(
modifier: Modifier,
qLisItem: QListItemView,
uiState: QListView,
eventEmitter: (event: DetailViewModelEvent) -> Unit
) {
when (qLisItem.typeItem) {
QListItemTypesEnum.QListItemCheckBox -> {
val qListItemCheckBox = qLisItem as QListItemViewCheckBoxImpl
QListDetailCheckItemComponent(
modifier = modifier,
model = qListItemCheckBox,
eventEmitter = eventEmitter
)
}
QListItemTypesEnum.QListItemDoneTitle -> {
val showDone by remember {
derivedStateOf {
uiState.numCheckedItems.value > 0
}
}
if (showDone) {
QListDefaultDoneItemComponent(
modifier = Modifier.clickable {
eventEmitter.invoke(DetailViewModelEvent.DoneClicked)
}.padding(start = 16.dp),
text = stringResource(id = R.string.done),
checkedItems = uiState.numCheckedItems,
showDoneItems = uiState.showUncheckedItems
)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
5d640ba44f33a29e0fc8ee06c00c1d55ac5eb1d1
| 5,437
|
one-for-all
|
Apache License 2.0
|
frontend-example/modules/spacex-crew/src/jsMain/kotlin/io/github/andrewk2112/kjsbox/frontend/example/spacexcrew/data/RemoteDataSourceExceptionsCatcher.kt
|
andrew-k-21-12
| 497,585,003
| false
|
{"Kotlin": 399649, "JavaScript": 7404, "HTML": 726}
|
package io.github.andrewk2112.kjsbox.frontend.example.spacexcrew.data
import io.github.andrewk2112.utility.common.utility.Result
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlin.coroutines.cancellation.CancellationException
/**
* Provides middleware to catch all possible exceptions and wrap (convert) them into typed [Result.Failure]s.
*
* One of possible alternative ways - is to use some [CoroutineExceptionHandler],
* but it's limited only to `suspend` contexts and doesn't support return values.
*
* It's better to have an abstraction extracted:
*
* ```kotlin
* interface ExceptionsCatcher<E : Throwable> {
* suspend operator fun <T> invoke(block: suspend () -> T): Result<T, E>
* }
* ```
*
* Keeping it with the built-in implementation to simplify the overall example.
*/
class RemoteDataSourceExceptionsCatcher {
/**
* The exceptions-catching middleware itself.
*
* In the ideal case it should not rethrow any exceptions to guarantee single source of errors to be processed,
* but for some safe cases - such as, for example [CancellationException]s - it's ok to throw exceptions further.
*/
suspend operator fun <T> invoke(block: suspend () -> T): Result<T, RemoteDataSourceException> =
// Unfortunately Kotlin/JS uses `Throwable` (`JsError`) as the base one for all JS exceptions
// (so it's impossible to differentiate between JS-related and other errors).
try {
Result.Success(block())
} catch (throwable: Throwable) {
if (throwable is CancellationException) throw throwable // preserving cancellations from coroutines
Result.Failure(RemoteDataSourceException(throwable))
}
}
| 0
|
Kotlin
|
0
| 3
|
80493596e7fee976df1aaa74a11d136de9cad13c
| 1,735
|
kjs-box
|
MIT License
|
app/src/main/java/com/techgv/themovielibrary/ui/MoviesFragment.kt
|
GvHarish9894
| 506,704,556
| false
|
{"Kotlin": 73843}
|
package com.techgv.themovielibrary.ui
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.techgv.themovielibrary.data.CategorySet
import com.techgv.themovielibrary.databinding.FragmentMoviesBinding
import com.techgv.themovielibrary.ui.fragment.home.MovieViewModel
import com.techgv.themovielibrary.ui.fragment.home.ParentAdapter
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MoviesFragment : Fragment() {
private var _binding: FragmentMoviesBinding? = null
private val binding get() = _binding!!
private val viewModel: MovieViewModel by viewModels()
private var list: MutableList<CategorySet> = mutableListOf()
private lateinit var adapter: ParentAdapter
private var movieApiResponse = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
}
initialData()
}
override fun onResume() {
super.onResume()
showView()
}
override fun onPause() {
super.onPause()
Log.i("MoviesFragment", "onPause")
}
private fun observers() {
viewModel.popularMoviesLiveData.observe(viewLifecycleOwner) {
list.add(CategorySet(Pair("Popular","popular"), it.results))
binding.homeRV.adapter?.notifyItemInserted(list.size)
showView()
}
viewModel.topRatedMoviesLiveData.observe(viewLifecycleOwner) {
list.add(CategorySet(Pair("Top Rated","top_rated"), it.results))
binding.homeRV.adapter?.notifyItemInserted(list.size)
showView()
}
viewModel.upcomingMoviesLiveData.observe(viewLifecycleOwner) {
list.add(CategorySet(Pair("Up Coming","upcoming"), it.results))
binding.homeRV.adapter?.notifyItemInserted(list.size)
showView()
}
viewModel.nowPlayingMoviesLiveData.observe(viewLifecycleOwner) {
list.add(CategorySet(Pair("Now Playing","now_playing"), it.results))
binding.homeRV.adapter?.notifyItemInserted(list.size)
showView()
}
}
private fun initialData() {
viewModel.popularMovies()
viewModel.topRatedMovies()
viewModel.upcomingMovies()
viewModel.nowPlayingMovies()
viewModel.latestMovies()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentMoviesBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
list.clear()
initView()
observers()
}
private fun initView() {
adapter = ParentAdapter(list,requireContext())
binding.homeRV.adapter = adapter
binding.homeRV.setHasFixedSize(true)
binding.homeRV.layoutManager = LinearLayoutManager(requireContext())
adapter.onChildItemClickItem = { child, parent ->
val action = MoviesFragmentDirections.actionMoviesFragmentToMovieDetailsFragment(list[parent].item[child].id.toLong())
findNavController().navigate(action)
}
adapter.onCategoryClick ={
val action = MoviesFragmentDirections.actionMoviesFragmentToCategoryDetailsFragment(list[it].title.first,list[it].title.second)
findNavController().navigate(action)
}
}
private fun showView() {
movieApiResponse++
if (movieApiResponse > 4) {
binding.shimmer.visibility = View.GONE
binding.homeRV.visibility = View.VISIBLE
}
}
override fun onDestroy() {
super.onDestroy()
_binding = null
Log.i("MoviesFragment", "onDestroy")
}
}
| 0
|
Kotlin
|
0
| 0
|
3bfd3721f4d7c5bae2f950c177691eabfa7bada0
| 4,151
|
TheMovieLibrary
|
Apache License 2.0
|
app/src/main/java/com/jumpingphantom/weather/ExtendedForecastFragment.kt
|
JumpingPhantom
| 786,273,042
| false
|
{"Kotlin": 9247}
|
package com.jumpingphantom.weather
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
class ExtendedForecastFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
super.onCreateView(inflater, container, savedInstanceState)
return inflater.inflate(R.layout.fragment_extended_forecast, container)
}
}
| 0
|
Kotlin
|
0
| 0
|
c19da4f4394b39e429774dcc576acc4c806321cb
| 538
|
WeatherApp
|
Apache License 2.0
|
app/src/main/java/com/huseyincan/financemobile/data/adapter/PortfolioAdapter.kt
|
huseyincn
| 750,915,865
| false
|
{"Kotlin": 52256}
|
package com.huseyincan.financemobile.data.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.huseyincan.financemobile.R
import com.huseyincan.financemobile.data.model.Portfolio
class PortfolioAdapter(private var items: List<Portfolio> = emptyList()) :
RecyclerView.Adapter<PortfolioAdapter.ViewHolder>() {
private var listenerItems: onItemClickListener? = null
fun setOnItemClickListener(listener: onItemClickListener) {
this.listenerItems = listener
}
fun getItem(position: Int): Portfolio {
return items[position]
}
class ViewHolder(view: View, private val listener: onItemClickListener?) :
RecyclerView.ViewHolder(view), View.OnClickListener {
val pUsername: TextView
val pRevenue: TextView
init {
// Define click listener for the ViewHolder's View
pUsername = view.findViewById(R.id.portfoliocreator)
pRevenue = view.findViewById(R.id.prevenue)
view.setOnClickListener(this)
}
override fun onClick(v: View?) {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
listener?.onItemClick(position)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
// Create a new view, which defines the UI of the list item
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.portfolio_card, parent, false)
return ViewHolder(view, listenerItems)
}
override fun getItemCount(): Int {
return items.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val tmp: Portfolio = items.get(position)
holder.pUsername.text = tmp.userName
holder.pRevenue.text = String.format("%.6f", tmp.revenue)
}
interface onItemClickListener {
fun onItemClick(position: Int)
}
fun updateItems(newItems: List<Portfolio>) {
this.items = newItems
notifyDataSetChanged()
}
}
| 0
|
Kotlin
|
0
| 0
|
9e9a8cd2fc737573cea53963a5a5ed3f991971e6
| 2,207
|
Finance-fe
|
MIT License
|
code/bookStoreApp/app/src/main/java/com/example/fragment/ShoppingCartFragment.kt
|
99611400
| 318,499,414
| false
| null |
package com.example.fragment
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Adapter
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.JsonArrayRequest
import com.example.adapter.BooksAdapter
import com.example.adapter.ShoppingCartAdapter
import com.example.entity.Book
import com.example.entity.ResultMessage
import com.example.entity.UserShoppingCartOrOrder
import com.example.test.R
import com.example.util.GetConfig
import com.example.util.VolleySingleton
import com.example.viewModel.BooksViewModel
import com.example.viewModel.ShoppingCartViewModel
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_book_detail.*
import kotlinx.android.synthetic.main.books_fragment.*
import kotlinx.android.synthetic.main.shopping_cart_fragment.*
import org.json.JSONArray
import org.json.JSONObject
class ShoppingCartFragment : Fragment() {
private lateinit var baseUrl:String
companion object {
fun newInstance() = ShoppingCartFragment()
}
private lateinit var viewModel: ShoppingCartViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.shopping_cart_fragment, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val jsonObject: JSONObject = GetConfig(requireContext().assets).getJsonConfig()
baseUrl = jsonObject["baseUrl"] as String
val shoppingCartAdapter = ShoppingCartAdapter()
shopping_cart_recycler.adapter = shoppingCartAdapter // 注意区别!!!!! bookTypeAdapter 和 booksAdapter
shopping_cart_recycler.layoutManager = LinearLayoutManager(requireContext())
// 主要进行总价的计算
shoppingCartAdapter.checkedMapInShoppingCart.observe(viewLifecycleOwner, Observer {
var tempDouble :Double = 0.0
it.forEach{ tempDouble += it.value.bookPrice}
// 保留两位小数
shopping_cart_fra_totalPrice.setText(String.format("%.2f", tempDouble))
})
viewModel = ViewModelProvider(this,ViewModelProvider.AndroidViewModelFactory(requireActivity().application)).get(ShoppingCartViewModel::class.java)
// 视图更新
viewModel.shoppingCartBookListLive.observe(viewLifecycleOwner, Observer {
shoppingCartAdapter.submitList(it)
})
// 删除按钮点击监听
shopping_cart_fra_clearAll_btn.setOnClickListener {
if(shoppingCartAdapter.checkedMapInShoppingCart.value!=null){
viewModel.deleteFromShopping(shoppingCartAdapter.checkedMapInShoppingCart.value!!)
Toast.makeText(requireContext(),"删除选中成功",Toast.LENGTH_SHORT).show()
}
}
// 结算按钮点击
shopping_cart_fra_addToMine.setOnClickListener {
if(shoppingCartAdapter.checkedMapInShoppingCart.value!=null) {
viewModel.addToMine(shoppingCartAdapter.checkedMapInShoppingCart.value!!)
Toast.makeText(requireContext(), "结算成功", Toast.LENGTH_SHORT).show()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d028770ac632138900301e691af35fbfd51f5dda
| 3,517
|
SdustAndroidDevelopmentExperiment
|
Apache License 2.0
|
src/test/kotlin/nl/jackploeg/aoc/_2023/calendar/day19/Day19Test.kt
|
jackploeg
| 736,755,380
| false
|
{"Kotlin": 318734}
|
package nl.jackploeg.aoc._2023.calendar.day19
import javax.inject.Inject
import nl.jackploeg.aoc._2023.DaggerTestDayComponent
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
internal class Day19Test {
@Inject
lateinit var day19: Day19
@BeforeEach
fun setup() {
DaggerTestDayComponent.create().inject(this)
}
@Test
fun testDay19PartOneTestInput() {
assertEquals(19114, day19.partOne(DAY_19_TEST))
}
@Test
fun testDay19PartTwoTestInput() {
assertEquals(167409079868000, day19.partTwo(DAY_19_TEST))
}
@Test
fun testDay19PartOne() {
assertEquals(346230, day19.partOne(DAY_19))
}
@Test
fun testDay19PartTwo() {
assertEquals(124693661917133, day19.partTwo(DAY_19))
}
companion object {
private const val DAY_19: String = "advent-of-code-input/2023/day19.input"
private const val DAY_19_TEST: String = "advent-of-code-input/2023/day19.test"
}
}
| 0
|
Kotlin
|
0
| 0
|
f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76
| 993
|
advent-of-code
|
MIT License
|
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/dotcover/report/model/AssemblyInfo.kt
|
JetBrains
| 49,584,664
| false
|
{"Kotlin": 2713429, "C#": 319161, "Java": 96855, "Dockerfile": 831, "CSS": 123}
|
package jetbrains.buildServer.dotcover.report.model
class AssemblyInfo(private val _assemblyName: String) {
val assemblyName: String
get() = _assemblyName
fun newNamespace(name: String): NamespaceInfo {
return NamespaceInfo(this, name)
}
}
| 3
|
Kotlin
|
25
| 94
|
5f444c22b3354955d1060e08478d543d2b0b99b0
| 271
|
teamcity-dotnet-plugin
|
Apache License 2.0
|
detekt-cli/src/main/kotlin/io/gitlab/arturbosch/detekt/cli/Main.kt
|
supersven
| 221,434,333
| true
|
{"Kotlin": 1531402, "Groovy": 3832, "HTML": 3416, "Shell": 1057}
|
@file:JvmName("Main")
package io.gitlab.arturbosch.detekt.cli
import io.gitlab.arturbosch.detekt.cli.runners.AstPrinter
import io.gitlab.arturbosch.detekt.cli.runners.ConfigExporter
import io.gitlab.arturbosch.detekt.cli.runners.Executable
import io.gitlab.arturbosch.detekt.cli.runners.Runner
import io.gitlab.arturbosch.detekt.cli.runners.SingleRuleRunner
import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty
import kotlin.system.exitProcess
@Suppress("TooGenericExceptionCaught")
fun main(args: Array<String>) {
try {
buildRunner(args).execute()
} catch (e: InvalidConfig) {
e.printStackTrace()
exitProcess(ExitCode.INVALID_CONFIG.number)
} catch (e: BuildFailure) {
e.printStackTrace()
exitProcess(ExitCode.MAX_ISSUES_REACHED.number)
} catch (e: Exception) {
e.printStackTrace()
exitProcess(ExitCode.UNEXPECTED_DETEKT_ERROR.number)
}
exitProcess(ExitCode.NORMAL_RUN.number)
}
fun buildRunner(args: Array<String>): Executable {
val arguments = parseArguments(args)
return when {
arguments.generateConfig -> ConfigExporter(arguments)
arguments.runRule != null -> SingleRuleRunner(arguments)
arguments.printAst -> AstPrinter(arguments)
else -> Runner(arguments)
}
}
private fun parseArguments(args: Array<String>): CliArgs {
val (arguments, jcommander) = parseArguments<CliArgs>(args)
val messages = validateCli(arguments)
messages.ifNotEmpty {
jcommander.failWithErrorMessages(messages)
}
return arguments
}
private fun validateCli(arguments: CliArgs): List<String> {
val violations = ArrayList<String>()
with(arguments) {
if (createBaseline && baseline == null) {
violations += "Creating a baseline.xml requires the --baseline parameter to specify a path."
}
}
return violations
}
| 0
|
Kotlin
|
0
| 0
|
867db13594ae6a1888a7ace4d6db9a0cb10ce6a8
| 1,890
|
detekt
|
Apache License 2.0
|
app/src/main/java/com/bluehub/mixi/common/utils/Ext.kt
|
ashfaq1701
| 275,871,797
| false
| null |
package com.bluehub.mixi.common.utils
import android.R
import android.os.Build
import android.util.TypedValue
import android.view.View
import java.util.*
fun <T> List<T>.areEqual(anotherList: List<T>): Boolean {
if (this.size != anotherList.size) return false
return this.zip(anotherList).all { (x, y) -> x == y }
}
fun <T> MutableList<T>.reInitList(anotherList: List<T>) {
removeAll { true }
this.addAll(anotherList)
}
fun View.getCurrentBackground(): Int? {
val a = TypedValue()
context.theme.resolveAttribute(R.attr.windowBackground, a, true)
val isColorType = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
a.type >= TypedValue.TYPE_FIRST_COLOR_INT && a.type <= TypedValue.TYPE_LAST_COLOR_INT
} else a.isColorType
return if (isColorType) {
a.data
} else null
}
fun getRandomString(length: Int) : String {
val allowedChars = ('A'..'Z') + ('a'..'z') + ('0'..'9')
return (1..length)
.map { allowedChars.random() }
.joinToString("")
}
| 0
|
C
|
9
| 48
|
dc9b650d8a07afb9da27057aa1336482b83e2010
| 1,029
|
fast-mixer
|
Creative Commons Zero v1.0 Universal
|
app/src/main/java/com/viewbindingsample/ui/core/BaseFragment.kt
|
Ashwagandha-coder
| 580,717,181
| false
| null |
package com.viewbindingsample.ui.core
| 0
|
Kotlin
|
0
| 0
|
b960503b274dc64a508a5efe4f0334622a0c07e0
| 41
|
viewbinding
|
MIT License
|
multiitem/src/main/java/com/sanniou/multiitem/ItemSpanSizeLookup.kt
|
sanniou
| 232,019,052
| false
| null |
package com.sanniou.multiitem
import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup
class ItemSpanSizeLookup(private val data: List<DataItem>, private val span: Int) :
SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
if (data.size > position) {
val itemSpan = data[position].getGridSpan()
return if (itemSpan == -1) span else itemSpan
}
return span
}
}
| 0
|
Kotlin
|
0
| 1
|
7f16bf40f78d46790a57dc55114a4570d9e4949c
| 447
|
MultiItemKit
|
Apache License 2.0
|
app/src/main/java/com/findmyphone/clapping/find/resource/utils/Extension.kt
|
daovu97
| 813,479,646
| false
|
{"Kotlin": 113404, "Java": 134}
|
package com.findmyphone.clapping.find.resource.utils
import android.content.Context
import android.content.pm.PackageManager
import android.content.res.Resources
import android.graphics.drawable.Drawable
import android.os.Build
import android.util.DisplayMetrics
import android.view.View
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.findmyphone.clapping.find.application.base.MyActivity
import com.nlbn.ads.util.Admob
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
fun Context.getAdmobIfNeed(): Admob? {
return if (checkNetWork(this) == true) {
return if (FBConfig.shared.isShowAds()) Admob.getInstance()
else null
} else null
}
fun Context.getAdmobInterIfNeed(): Admob? {
return if (checkNetWork(this) == true) {
return if (FBConfig.shared.isShowAdsInter()) Admob.getInstance()
else null
} else null
}
object Constant {
val screenWidth: Int = Resources.getSystem().displayMetrics.widthPixels
val screenHeight: Int = Resources.getSystem().displayMetrics.heightPixels
}
fun Context.compatColor(int: Int): Int {
return ContextCompat.getColor(this, int)
}
fun Context.compactDrawable(int: Int): Drawable? {
return ContextCompat.getDrawable(this, int)
}
object Converter {
fun dpFromPx(px: Int): Float {
return px / Resources.getSystem().displayMetrics.density
}
fun pixelsToSp(pixels: Int): Float {
val scaledDensity = Resources.getSystem().displayMetrics.scaledDensity
return pixels / scaledDensity
}
fun asPixels(value: Int): Int {
val scale = Resources.getSystem().displayMetrics.density
val dpAsPixels = (value * scale + 0.5f)
return dpAsPixels.toInt()
}
}
fun MyActivity.delay(timeMillis: Long, completion: () -> Unit) {
activityScope.launch {
kotlinx.coroutines.delay(timeMillis)
completion.invoke()
}
}
fun View.visible() {
this.visibility = View.VISIBLE
this.isEnabled = true
}
fun View.hidden() {
this.visibility = View.INVISIBLE
this.isEnabled = false
}
fun View.gone() {
this.visibility = View.GONE
this.isEnabled = false
}
fun Context?.convertDpToPixel(dp: Float): Float {
this ?: return 0f
return dp * (resources
.displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
}
@RequiresApi(Build.VERSION_CODES.O)
fun LocalDateTime.string(pattern: String = "yyyy-MM-dd HH:mm"): String {
val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern(pattern)
return this.format(formatter)
}
fun Context?.hasPermissions(permissions: Array<String>): Boolean = permissions.all {
this ?: return@all false
ActivityCompat.checkSelfPermission(this, it) == PackageManager.PERMISSION_GRANTED
}
fun View.asPixels(value: Int): Int {
val scale = resources.displayMetrics.density
val dpAsPixels = (value * scale + 0.5f)
return dpAsPixels.toInt()
}
| 0
|
Kotlin
|
0
| 0
|
f139270dc79580afa0145e6c2b4898b016c060bd
| 3,013
|
clapfinder
|
MIT License
|
meetnote3/src/nativeMain/kotlin/meetnote3/Logger.kt
|
tokuhirom
| 817,853,357
| false
|
{"Kotlin": 45540, "Python": 3927}
|
package meetnote3
import platform.posix.getenv
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.toKString
const val LOG_LEVEL_TRACE = 0
const val LOG_LEVEL_DEBUG = 1
const val LOG_LEVEL_INFO = 2
const val LOG_LEVEL_WARNING = 3
const val LOG_LEVEL_ERROR = 4
private var logLevel = LOG_LEVEL_INFO
@OptIn(ExperimentalForeignApi::class)
fun initLogger() {
val logLevelStringOrNull = getenv("LOG_LEVEL")?.toKString()
when (logLevelStringOrNull) {
"TRACE" -> logLevel = LOG_LEVEL_TRACE
"DEBUG" -> logLevel = LOG_LEVEL_DEBUG
"INFO" -> logLevel = LOG_LEVEL_INFO
"WARNING" -> logLevel = LOG_LEVEL_WARNING
"ERROR" -> logLevel = LOG_LEVEL_ERROR
else -> LOG_LEVEL_INFO
}
}
fun setLogLevel(level: Int) {
logLevel = level
}
fun trace(message: String) {
if (logLevel <= LOG_LEVEL_TRACE) {
println("[TRACE] $message")
}
}
fun debug(message: String) {
if (logLevel <= LOG_LEVEL_DEBUG) {
println("[DEBUG] $message")
}
}
fun info(message: String) {
if (logLevel <= LOG_LEVEL_INFO) {
println("[INFO] $message")
}
}
fun warning(message: String) {
if (logLevel <= LOG_LEVEL_WARNING) {
eprintln("[WARNING] $message")
}
}
fun error(message: String) {
if (logLevel <= LOG_LEVEL_ERROR) {
eprintln("[ERROR] $message")
}
}
| 1
|
Kotlin
|
0
| 0
|
06356e1b07a682295655ebf28d85fc964763ab3f
| 1,372
|
meetnote3
|
MIT License
|
client/src/main/kotlin/com.chrynan.sitetheme/binder/HomeBinder.kt
|
chRyNaN
| 200,936,464
| false
|
{"JavaScript": 5798148, "CSS": 485678, "Kotlin": 88005, "PHP": 62866, "HTML": 475}
|
package com.chrynan.sitetheme.binder
import com.chrynan.sitetheme.viewmodel.PostItemViewModel
interface HomeBinder : HeaderFooterBinder {
fun bindPosts(models: List<PostItemViewModel>)
}
| 0
|
JavaScript
|
0
| 0
|
a398f21f02d0b059694d533e81505b49fcc63594
| 193
|
old-site-theme-experiment
|
Apache License 2.0
|
shared/src/commonMain/kotlin/de/jensklingenberg/showdown/model/ShowdownError.kt
|
cybernetics
| 284,643,634
| true
|
{"Kotlin": 100658, "HTML": 1189, "CSS": 661, "JavaScript": 419}
|
package de.jensklingenberg.showdown.model
import kotlinx.serialization.Serializable
@Serializable
sealed class ShowdownError(var message: String) {
@Serializable
class NotAuthorizedError : ShowdownError("NotAuthorizedError")
@Serializable
class NoConnectionError : ShowdownError("NotAuthorizedError")
}
| 0
| null |
0
| 0
|
3a1993d4e7032dd4e45b5644a357c6b4dfe56958
| 323
|
Showdown
|
Apache License 2.0
|
app/src/main/java/com/example/visuallithuanian/constants/ImageStore.kt
|
klaus19
| 541,931,828
| false
|
{"Kotlin": 696917}
|
package com.example.visuallithuanian.constants
import com.example.visuallithuanian.R
object ImageStore {
val imagesNamesMap = mutableMapOf<Int, Triple<String, String,Int>>()
fun addImageResource(resId:Int,english:String,lithuanian:String,voiceClip:Int){
imagesNamesMap[resId] = Triple(english,lithuanian,voiceClip)
}
fun removeImageResource(resId: Int){
imagesNamesMap.remove(resId)
}
fun getRandomPairs(count: Int): List<Pair<Int, Triple<String, String,Int>>> {
return imagesNamesMap.entries.shuffled().take(count).map { it.toPair() }
}
}
| 10
|
Kotlin
|
4
| 9
|
07e434a018c263db43555321ce0904b369242e3d
| 595
|
Labas
|
Apache License 2.0
|
SharedCode/src/iOSMain/kotlin/MainLoopDispatcher.kt
|
armcha
| 152,214,178
| false
| null |
package org.kotlin.mpp.mobile
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Runnable
import platform.Foundation.NSRunLoop
import platform.Foundation.performBlock
import kotlin.coroutines.CoroutineContext
object MainLoopDispatcher: CoroutineDispatcher() {
override fun dispatch(context: CoroutineContext, block: Runnable) {
NSRunLoop.mainRunLoop().performBlock {
block.run()
}
}
}
| 0
|
Kotlin
|
1
| 13
|
9ea9fdc880084cdf94f491222e39ce1f0c9eea21
| 443
|
KotlinMultiplatformSample
|
Apache License 2.0
|
kord-extensions/src/main/kotlin/com/kotlindiscord/kord/extensions/commands/events/UserCommandEvents.kt
|
Kord-Extensions
| 262,018,456
| false
| null |
package com.kotlindiscord.kord.extensions.commands.events
import com.kotlindiscord.kord.extensions.commands.application.user.EphemeralUserCommand
import com.kotlindiscord.kord.extensions.commands.application.user.PublicUserCommand
import com.kotlindiscord.kord.extensions.commands.application.user.UserCommand
import dev.kord.core.event.interaction.UserCommandInteractionCreateEvent
// region Invocation events
/** Basic event emitted when a user command is invoked. **/
public interface UserCommandInvocationEvent<C : UserCommand<*>> :
CommandInvocationEvent<C, UserCommandInteractionCreateEvent>
/** Event emitted when an ephemeral user command is invoked. **/
public data class EphemeralUserCommandInvocationEvent(
override val command: EphemeralUserCommand,
override val event: UserCommandInteractionCreateEvent
) : UserCommandInvocationEvent<EphemeralUserCommand>
/** Event emitted when a public user command is invoked. **/
public data class PublicUserCommandInvocationEvent(
override val command: PublicUserCommand,
override val event: UserCommandInteractionCreateEvent
) : UserCommandInvocationEvent<PublicUserCommand>
// endregion
// region Succeeded events
/** Basic event emitted when a user command invocation succeeds. **/
public interface UserCommandSucceededEvent<C : UserCommand<*>> :
CommandSucceededEvent<C, UserCommandInteractionCreateEvent>
/** Event emitted when an ephemeral user command invocation succeeds. **/
public data class EphemeralUserCommandSucceededEvent(
override val command: EphemeralUserCommand,
override val event: UserCommandInteractionCreateEvent
) : UserCommandSucceededEvent<EphemeralUserCommand>
/** Event emitted when a public user command invocation succeeds. **/
public data class PublicUserCommandSucceededEvent(
override val command: PublicUserCommand,
override val event: UserCommandInteractionCreateEvent
) : UserCommandSucceededEvent<PublicUserCommand>
// endregion
// region Failed events
/** Basic event emitted when a user command invocation fails. **/
public sealed interface UserCommandFailedEvent<C : UserCommand<*>> :
CommandFailedEvent<C, UserCommandInteractionCreateEvent>
/** Basic event emitted when a user command's checks fail. **/
public interface UserCommandFailedChecksEvent<C : UserCommand<*>> :
UserCommandFailedEvent<C>, CommandFailedChecksEvent<C, UserCommandInteractionCreateEvent>
/** Event emitted when an ephemeral user command's checks fail. **/
public data class EphemeralUserCommandFailedChecksEvent(
override val command: EphemeralUserCommand,
override val event: UserCommandInteractionCreateEvent,
override val reason: String,
) : UserCommandFailedChecksEvent<EphemeralUserCommand>
/** Event emitted when a public user command's checks fail. **/
public data class PublicUserCommandFailedChecksEvent(
override val command: PublicUserCommand,
override val event: UserCommandInteractionCreateEvent,
override val reason: String,
) : UserCommandFailedChecksEvent<PublicUserCommand>
/** Basic event emitted when a user command invocation fails with an exception. **/
public interface UserCommandFailedWithExceptionEvent<C : UserCommand<*>> :
UserCommandFailedEvent<C>, CommandFailedWithExceptionEvent<C, UserCommandInteractionCreateEvent>
/** Event emitted when an ephemeral user command invocation fails with an exception. **/
public data class EphemeralUserCommandFailedWithExceptionEvent(
override val command: EphemeralUserCommand,
override val event: UserCommandInteractionCreateEvent,
override val throwable: Throwable
) : UserCommandFailedWithExceptionEvent<EphemeralUserCommand>
/** Event emitted when a public user command invocation fails with an exception. **/
public data class PublicUserCommandFailedWithExceptionEvent(
override val command: PublicUserCommand,
override val event: UserCommandInteractionCreateEvent,
override val throwable: Throwable
) : UserCommandFailedWithExceptionEvent<PublicUserCommand>
// endregion
| 15
|
Kotlin
|
14
| 53
|
c4a5a8cc8a65c0bd0928a4dcc6c05e3fc4fd75cf
| 4,029
|
kord-extensions
|
MIT License
|
src/main/java/com/dzen/campfire/server/executors/quests/EQuestsSaveState.kt
|
ZeonXX
| 442,862,191
| false
|
{"Kotlin": 1072092}
|
package com.dzen.campfire.server.executors.quests
import com.dzen.campfire.api.API
import com.dzen.campfire.api.models.quests.QuestDetails
import com.dzen.campfire.api.requests.quests.RQuestsSaveState
import com.dzen.campfire.api.tools.ApiException
import com.dzen.campfire.server.controllers.ControllerPublications
import com.dzen.campfire.server.tables.TQuestParts
import com.dzen.campfire.server.tables.TQuestStates
import com.sup.dev.java.libs.json.Json
import com.sup.dev.java_pc.sql.Database
import com.sup.dev.java_pc.sql.Sql
import com.sup.dev.java_pc.sql.SqlQuerySelect
import com.sup.dev.java_pc.sql.SqlQueryUpdate
class EQuestsSaveState : RQuestsSaveState(0, Json(), 0) {
private lateinit var questDetails: QuestDetails
override fun check() {
questDetails = ControllerPublications.getPublication(questId, apiAccount.id) as QuestDetails
if (questDetails.status != API.STATUS_PUBLIC) throw ApiException(API.ERROR_GONE)
val totalParts = Database.select("EQuestsSaveState count", SqlQuerySelect(TQuestParts.NAME, Sql.COUNT)
.where(TQuestParts.unit_id, "=", questId)).nextLongOrZero()
if (stateIndex >= totalParts || stateIndex < 0) throw ApiException(BAD_STATE, "stateIndex >= totalParts")
stateVariables.forEach { key, value ->
if (questDetails.variablesMap!![key.toLong()] == null) {
throw ApiException(BAD_STATE, "variable not found")
}
if (value !is String)
throw ApiException(BAD_STATE, "value !is String")
if (value.length > API.QUEST_VARIABLE_MAX_VALUE_L)
throw ApiException(BAD_STATE, "value.length > API.QUEST_VARIABLE_MAX_VALUE_L")
}
}
override fun execute(): Response {
val existingId = Database.select("EQuestsSaveState existing", SqlQuerySelect(TQuestStates.NAME, TQuestStates.id)
.where(TQuestStates.user_id, "=", apiAccount.id)
.where(TQuestStates.unit_id, "=", questId)
.count(1))
.nextLongOrZero()
val json = Json()
json.put("stateVariables", stateVariables)
json.put("stateIndex", stateIndex)
if (existingId > 0) {
Database.update("EQuestsSaveState update", SqlQueryUpdate(TQuestStates.NAME)
.updateValue(TQuestStates.json_db, json.toString()))
} else {
Database.insert(
"EQuestsSaveState insert",
TQuestStates.NAME,
TQuestStates.unit_id, questId,
TQuestStates.user_id, apiAccount.id,
TQuestStates.json_db, json.toString(),
)
}
return Response()
}
}
| 1
|
Kotlin
|
2
| 0
|
40a2fbdbbdbe6706ed852f7218cb10fd57e50445
| 2,706
|
CampfireServer
|
Apache License 2.0
|
domain-objects/src/main/kotlin/com/github/vincentfree/model/Order.kt
|
vincentfree
| 354,959,125
| false
| null |
package com.github.vincentfree.model
import io.vertx.core.json.JsonObject
import io.vertx.kotlin.core.json.jsonObjectOf
data class Order(val id: String, val name: String, val orderId: String) {
fun toJson(): JsonObject = jsonObjectOf(
"id" to id,
"name" to name,
"orderId" to orderId,
)
fun toJsonString(): String = toJson().encode()
companion object {
fun ofJson(json: JsonObject): Result<Order> {
return with(json) {
runCatching {
Order(
id = getString("id"),
name = getString("name"),
orderId = getString("orderId"),
)
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
8d97070899f6d133ec2b1c69caea01b19dc72326
| 765
|
dapr-experiments
|
MIT License
|
ObjectOrientedParadigm/Exercise-2/Book.kt
|
Johanx22x
| 674,064,501
| false
|
{"Kotlin": 19851, "Go": 18444, "F#": 13580, "Prolog": 4760, "Rust": 4512, "Makefile": 822}
|
class Book(id: Long, title: String, author: String) {
var id: Long = id
private set
var title: String = title
private set
var author: String = author
private set
var isAvailable: Boolean = true
override fun toString(): String {
return "Book(id=$id, title='$title', author='$author', isAvailable=$isAvailable)"
}
}
| 0
|
Kotlin
|
0
| 1
|
17ef99cfb4e12803a15615f235bfd3d0961ec373
| 371
|
ProgrammingLanguages
|
MIT License
|
app/src/main/java/com/sky/xposed/rmad/provider/SettingsProvider.kt
|
ijustyce
| 131,395,536
| true
|
{"Kotlin": 39468, "Java": 2346}
|
/*
* Copyright (c) 2017 The sky Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sky.xposed.rmad.provider
import android.content.ContentProvider
import android.content.ContentValues
import android.content.SharedPreferences
import android.content.UriMatcher
import android.database.Cursor
import android.database.MatrixCursor
import android.net.Uri
import android.preference.PreferenceManager
/**
* Created by sky on 17-11-2.
*/
class SettingsProvider : ContentProvider() {
private val authority = "com.sky.xposed.rmad.settings.preference"
private val stringPath = "string"
private val intPath = "int"
private val booleanPath = "boolean"
private val longPath = "long"
private val floatPath = "float"
private val allPath = "all"
private val stringCode = 1
private val intCode = 2
private val booleanCode = 3
private val longCode = 4
private val floatCode = 5
private val allCode = 6
private val uriMatcher = UriMatcher(UriMatcher.NO_MATCH)
private lateinit var mPreferences: SharedPreferences
init {
uriMatcher.addURI(authority, stringPath, stringCode)
uriMatcher.addURI(authority, intPath, intCode)
uriMatcher.addURI(authority, booleanPath, booleanCode)
uriMatcher.addURI(authority, longPath, longCode)
uriMatcher.addURI(authority, floatPath, floatCode)
uriMatcher.addURI(authority, allPath, allCode)
}
override fun onCreate(): Boolean {
// 初始化
mPreferences = PreferenceManager.getDefaultSharedPreferences(context)
return true
}
override fun query(uri: Uri, projection: Array<String>?,
selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? {
when(uriMatcher.match(uri)) {
stringCode -> return handler(selection, selectionArgs) { key, defValue -> mPreferences.getString(key, defValue) }
intCode -> return handler(selection, selectionArgs) { key, defValue -> mPreferences.getInt(key, defValue.toInt()) }
booleanCode -> return handler(selection, selectionArgs) { key, defValue -> mPreferences.getBoolean(key, defValue.toBoolean()) }
longCode -> return handler(selection, selectionArgs) { key, defValue -> mPreferences.getLong(key, defValue.toLong()) }
floatCode -> return handler(selection, selectionArgs) { key, defValue -> mPreferences.getFloat(key, defValue.toFloat()) }
allCode -> { return matrixCursor(mPreferences.all) }
}
return null
}
override fun getType(uri: Uri): String? {
throw UnsupportedOperationException("No external updates")
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
throw UnsupportedOperationException("No external updates")
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
throw UnsupportedOperationException("No external updates")
}
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int {
throw UnsupportedOperationException("No external updates")
}
private inline fun <reified T> handler(
selection: String?, selectionArgs: Array<String>?,
callback: (key: String, defValue: String) -> T): Cursor? {
if (selection == null
|| selectionArgs == null
|| selectionArgs.isEmpty()) {
return null
}
return matrixCursor(callback.invoke(selection, selectionArgs[0]))
}
private inline fun <reified T> matrixCursor(value: T): Cursor {
val cursor = MatrixCursor(arrayOf("value"), 1)
// 添加数据
cursor.addRow(arrayOf(value))
return cursor
}
private inline fun <reified T> matrixCursor(map: Map<String, T>): Cursor {
val cursor = MatrixCursor(arrayOf("key", "value"), map.size)
map.keys.forEach {
// 添加数据
cursor.addRow(arrayOf(it, map[it]))
}
return cursor
}
}
| 0
|
Kotlin
|
0
| 0
|
ef3d56dd001423c80ad7384ab79cb42446663cc7
| 4,609
|
xposed-rmad
|
Apache License 2.0
|
src/commonMain/kotlin/data/activity/user_generated_content/GetUgcRsp.kt
|
Hartie95
| 642,871,918
| false
|
{"Kotlin": 301622}
|
package data.activity.user_generated_content
import annotations.AddedIn
import data.activity.user_generated_content.music_game.UgcMusicBriefInfo
import data.activity.user_generated_content.music_game.UgcMusicRecord
import messages.VERSION
import org.anime_game_servers.annotations.*
@AddedIn(VERSION.V2_7_0)
@ProtoCommand(CommandType.RESPONSE)
interface GetUgcRsp {
var ugcGuid: Long
var ugcType: UgcType
var ugcRecordUsage: RecordUsage
@OneOf(OneOfEntry(UgcMusicRecord::class, "music_record"))
var record: OneOfType
@OneOf(OneOfEntry(UgcMusicBriefInfo::class, "music_brief_info"))
var brief: OneOfType
var retcode: Int
}
| 0
|
Kotlin
|
2
| 5
|
cb458b49dc9618e3826b890689becc0f12585998
| 655
|
anime-game-multi-proto
|
MIT License
|
src/main/kotlin/dev/lunarcoffee/beanly/exts/commands/utility/timers/BaseTimer.kt
|
LunarCoffee
| 184,699,115
| false
| null |
package dev.lunarcoffee.beanly.exts.commands.utility.timers
import net.dv8tion.jda.api.events.Event
import org.litote.kmongo.coroutine.CoroutineCollection
import java.util.*
interface BaseTimer {
val time: Date
fun <T : Any> schedule(event: Event, col: CoroutineCollection<T>)
}
| 0
|
Kotlin
|
0
| 0
|
8f428aa32dd7b69903bf57dab67e248fdbda688d
| 290
|
Beanly
|
MIT License
|
spring-boot-async-and-mockito-spies/kotlin/src/test/kotlin/x/scratch/TestAsyncConfiguration.kt
|
kandhdxhd
| 321,755,623
| true
|
{"Kotlin": 207497, "Java": 63586, "Batchfile": 16635, "Rust": 14764, "Shell": 10120, "HTML": 4668, "Dockerfile": 258}
|
package x.scratch
import org.assertj.core.api.Assertions.assertThat
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Primary
import org.springframework.core.task.TaskExecutor
import org.springframework.scheduling.annotation.EnableAsync
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.Executor
import java.util.concurrent.TimeUnit
@EnableAsync
@TestConfiguration
class TestAsyncConfiguration {
@Bean
@Primary
fun testingExecutor() = TestingExecutor("default")
@Bean(SLOW_EXECUTOR_BEAN_NAME)
fun alsoTestingExecutor() = TestingExecutor("special")
}
class TestingExecutor(val name: String)
: Executor,
TaskExecutor {
val executorsCalled = ArrayBlockingQueue<TestingExecutor>(10)
val tasksRan = ArrayBlockingQueue<Runnable>(10)
override fun execute(command: Runnable) {
assertThat(executorsCalled.offer(this))
.`as`("Too many executors called without checking")
.isTrue()
Thread {
command.run()
assertThat(tasksRan.offer(command))
.`as`("Too many tasks ran without checking")
.isTrue()
}.start()
}
fun awaitExecutorCalled(timeout: Long, unit: TimeUnit): TestingExecutor {
val executor = executorsCalled.poll(timeout, unit)
assertThat(executor)
.`as`("No executor called in time")
.isNotNull()
return executor!!
}
fun awaitTaskRan(timeout: Long, unit: TimeUnit): Runnable {
val task = tasksRan.poll(timeout, unit)
assertThat(task)
.`as`("No task ran in time")
.isNotNull()
return task!!
}
override fun toString(): String {
return "$name:${super.toString()}"
}
}
| 0
| null |
0
| 0
|
c9a9fd827b163fe4ae259a6c617cb109e3bca575
| 1,915
|
spikes
|
The Unlicense
|
ImageLoader/src/main/java/cn/quibbler/imageloader/cache/disk/impl/ext/StrictLineReader.kt
|
quibbler01
| 524,270,844
| false
|
{"Kotlin": 252007}
|
package cn.quibbler.imageloader.cache.disk.impl.ext
import java.io.*
import java.nio.charset.Charset
/**
* Buffers input from an {@link InputStream} for reading lines.
*
* <p>This class is used for buffered reading of lines. For purposes of this class, a line ends
* with "\n" or "\r\n". End of input is reported by throwing {@code EOFException}. Unterminated
* line at end of input is invalid and will be ignored, the caller may use {@code
* hasUnterminatedLine()} to detect it after catching the {@code EOFException}.
*
* <p>This class is intended for reading input that strictly consists of lines, such as line-based
* cache entries or cache journal. Unlike the {@link java.io.BufferedReader} which in conjunction
* with {@link java.io.InputStreamReader} provides similar functionality, this class uses different
* end-of-input reporting and a more restrictive definition of a line.
*
* <p>This class supports only charsets that encode '\r' and '\n' as a single byte with value 13
* and 10, respectively, and the representation of no other character contains these values.
* We currently check in constructor that the charset is one of US-ASCII, UTF-8 and ISO-8859-1.
* The default charset is US_ASCII.
*/
class StrictLineReader : Closeable {
companion object {
private const val CR = '\r'.code.toByte()
private const val LF = '\n'.code.toByte()
}
private val input: InputStream
private val charset: Charset
/*
* Buffered data is stored in {@code buf}. As long as no exception occurs, 0 <= pos <= end
* and the data in the range [pos, end) is buffered for reading. At end of input, if there is
* an unterminated line, we set end == -1, otherwise end == pos. If the underlying
* {@code InputStream} throws an {@code IOException}, end may remain as either pos or -1.
*/
private var buf: ByteArray
private var pos = 0
private var end = 0
/**
* Constructs a new {@code LineReader} with the specified charset and the default capacity.
*
* @param in the {@code InputStream} to read data from.
* @param charset the charset used to decode data. Only US-ASCII, UTF-8 and ISO-8859-1 are
* supported.
* @throws NullPointerException if {@code in} or {@code charset} is null.
* @throws IllegalArgumentException if the specified charset is not supported.
*/
constructor(input: InputStream, charset: Charset) : this(input = input, capacity = 8192, charset = charset)
/**
* Constructs a new {@code LineReader} with the specified capacity and charset.
*
* @param in the {@code InputStream} to read data from.
* @param capacity the capacity of the buffer.
* @param charset the charset used to decode data. Only US-ASCII, UTF-8 and ISO-8859-1 are
* supported.
* @throws NullPointerException if {@code in} or {@code charset} is null.
* @throws IllegalArgumentException if {@code capacity} is negative or zero
* or the specified charset is not supported.
*/
constructor(input: InputStream, capacity: Int, charset: Charset) {
if (capacity < 0) {
throw IllegalArgumentException("capacity <= 0")
}
if (charset != US_ASCII) {
throw IllegalArgumentException("Unsupported encoding")
}
this.input = input
this.charset = charset
this.buf = ByteArray(capacity)
}
/**
* Closes the reader by closing the underlying {@code InputStream} and
* marking this reader as closed.
*
* @throws IOException for errors when closing the underlying {@code InputStream}.
*/
override fun close() {
synchronized(input) {
input.close()
}
}
/**
* Reads the next line. A line ends with {@code "\n"} or {@code "\r\n"},
* this end of line marker is not included in the result.
*
* @return the next line from the input.
* @throws IOException for underlying {@code InputStream} errors.
* @throws EOFException for the end of source stream.
*/
@Throws(IOException::class)
fun readLine(): String {
synchronized(input) {
// Read more data if we are at the end of the buffered data.
// Though it's an error to read after an exception, we will let {@code fillBuf()}
// throw again if that happens; thus we need to handle end == -1 as well as end == pos.
if (pos >= end) {
fillBuf()
}
// Try to find LF in the buffered data and return the line if successful.
for (i in pos until end) {
if (buf[i] == LF) {
val lineEnd = if (i != pos && buf[i - 1] == CR) i - 1 else i
val res = String(buf, pos, lineEnd - pos, charset)
pos = i + 1
return res
}
}
// Let's anticipate up to 80 characters on top of those already read.
val out = object : ByteArrayOutputStream(end - pos + 80) {
override fun toString(): String {
val length = if ((count > 0 && buf[count - 1] == CR)) count - 1 else count
try {
return String(buf, 0, length, charset)
} catch (e: UnsupportedEncodingException) {
throw AssertionError(e)
}
}
}
while (true) {
out.write(buf, pos, end - pos)
// Mark unterminated line in case fillBuf throws EOFException or IOException.
end = -1
fillBuf()
// Try to find LF in the buffered data and return the line if successful.
// Try to find LF in the buffered data and return the line if successful.
for (i in pos until end) {
if (buf[i] == LF) {
if (i != pos) {
out.write(buf, pos, i - pos)
}
pos = i + 1
return out.toString()
}
}
}
}
}
/**
* Reads new input data into the buffer. Call only with pos == end or end == -1,
* depending on the desired outcome if the function throws.
*/
@Throws(IOException::class)
private fun fillBuf() {
val result = input.read(buf, 0, buf.size)
if (result == -1) {
throw EOFException()
}
pos = 0
end = result
}
}
| 0
|
Kotlin
|
0
| 0
|
d2fae5a52fe791f0338bd303f3f7cb128fa7e504
| 6,612
|
ImageLoader
|
Apache License 2.0
|
src/main/kotlin/br/com/alura/forum/mapper/TopicCreateMapper.kt
|
rdiego26
| 611,817,827
| false
| null |
package br.com.alura.forum.mapper
import br.com.alura.forum.dto.CreateTopic
import br.com.alura.forum.model.Topic
import br.com.alura.forum.service.CourseService
import br.com.alura.forum.service.UserService
import org.springframework.stereotype.Component
@Component
class TopicCreateMapper(
private val courseService: CourseService,
private val userService: UserService,
): Mapper<CreateTopic, Topic> {
override fun map(t: CreateTopic): Topic {
return Topic(
title = t.title,
message = t.message,
course = courseService.findById(t.idCourse)!!,
author = userService.findById(t.idAuthor)!!
)
}
}
| 0
|
Kotlin
|
0
| 0
|
046f8d1d0f75ac2b4c3974c5135d2127a85e6085
| 676
|
demo-forum-spring-boot-and-kotlin
|
MIT License
|
app/src/main/java/com/breezebengaldetergentproducts/features/stockAddCurrentStock/api/ShopAddStockProvider.kt
|
DebashisINT
| 863,405,964
| false
|
{"Kotlin": 15991783, "Java": 1032672}
|
package com.breezebengaldetergentproducts.features.stockAddCurrentStock.api
import com.breezebengaldetergentproducts.features.location.shopRevisitStatus.ShopRevisitStatusApi
import com.breezebengaldetergentproducts.features.location.shopRevisitStatus.ShopRevisitStatusRepository
object ShopAddStockProvider {
fun provideShopAddStockRepository(): ShopAddStockRepository {
return ShopAddStockRepository(ShopAddStockApi.create())
}
}
| 0
|
Kotlin
|
0
| 0
|
0cd8b29158b494893e3d7be77b87a725e3d49abf
| 448
|
BengalDetergentProducts
|
Apache License 2.0
|
pretixscan/gui/src/main/kotlin/eu/pretix/pretixscan/desktop/ui/MainController.kt
|
JonasOstergaard
| 370,630,356
| false
| null |
package eu.pretix.pretixscan.desktop.ui
import com.github.kittinunf.fuel.httpPost
import eu.pretix.libpretixsync.check.TicketCheckProvider
import eu.pretix.libpretixsync.db.Answer
import eu.pretix.pretixscan.desktop.PretixScanMain
import eu.pretix.pretixscan.desktop.VERSION
import org.json.JSONObject
import java.util.*
import kotlin.collections.List
class MainController : BaseController() {
fun toggleAsync(value: Boolean) {
configStore.asyncModeEnabled = value
(app as PretixScanMain).reloadCheckProvider()
}
fun handleSearchInput(value: String): List<TicketCheckProvider.SearchResult>? {
if (configStore.eventSlug == null || configStore.checkInListId == 0L) {
// not yet set up
return null
}
return (app as PretixScanMain).provider.search(value, 1)
}
fun handleScanInput(value: String, answers: List<Answer>? = null, ignore_pending: Boolean=false, type: TicketCheckProvider.CheckInType): TicketCheckProvider.CheckResult? {
if (answers != null) {
return (app as PretixScanMain).provider.check(value, answers, ignore_pending, true, type)
} else {
return (app as PretixScanMain).provider.check(value, ArrayList<Answer>(), ignore_pending, true, type)
}
}
fun updateCheck() {
if ((System.currentTimeMillis() - configStore.lastUpdateCheck) > 24 * 3600 * 1000) {
val payload = JSONObject()
payload.put("version", VERSION)
val request = "https://pretix.eu/.update_check/pretixscan-desktop/".httpPost().body(payload.toString())
request.headers["Content-Type"] = "application/json"
val (_, response, result) = request.responseString()
if (response.statusCode == 200) {
try {
val data = JSONObject(result.get())
if ("ok".equals(data.optString("status"))) {
if (data.getJSONObject("version").getBoolean("updatable")) {
configStore.lastUpdateCheck = System.currentTimeMillis()
configStore.updateCheckNewerVersion = data.getJSONObject("version").getString("latest")
} else {
configStore.lastUpdateCheck = System.currentTimeMillis()
configStore.updateCheckNewerVersion = ""
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
fun updateCheckNewerVersion(): String {
return configStore.updateCheckNewerVersion;
}
}
| 0
|
Kotlin
|
0
| 0
|
a769845aaa396c4ddaa1007b96691a6cf2e62395
| 2,701
|
pretixscan-windows-modified-mavea
|
Apache License 2.0
|
composeApp/src/desktopMain/kotlin/com/tecknobit/refy/viewmodels/collections/CollectionListViewModel.kt
|
N7ghtm4r3
| 832,103,900
| false
|
{"Kotlin": 391913, "Java": 1845}
|
package com.tecknobit.refy.viewmodels.collections
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.runtime.toMutableStateList
import androidx.lifecycle.ViewModel
import com.tecknobit.equinox.FetcherManager.FetcherManagerWrapper
import com.tecknobit.equinox.Requester.Companion.RESPONSE_MESSAGE_KEY
import com.tecknobit.equinoxcompose.helpers.EquinoxViewModel
import com.tecknobit.refy.ui.screens.Screen.Companion.snackbarHostState
import com.tecknobit.refy.ui.screens.items.CollectionListScreen
import com.tecknobit.refy.ui.screens.navigation.Splashscreen.Companion.localUser
import com.tecknobit.refy.ui.screens.navigation.Splashscreen.Companion.requester
import com.tecknobit.refy.viewmodels.RefyViewModel
import com.tecknobit.refycore.records.LinksCollection
import com.tecknobit.refycore.records.LinksCollection.returnCollections
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/**
* The **CollectionListViewModel** class is the support class used by [CollectionListScreen] to communicate
* with the backend and to execute the refreshing routines to update the UI data and working with the
* [LinksCollection]
*
* @author N7ghtm4r3 - Tecknobit
* @see ViewModel
* @see FetcherManagerWrapper
* @see EquinoxViewModel
* @see RefyViewModel
* @see LinksCollectionViewModelHelper
*
*/
class CollectionListViewModel : LinksCollectionViewModelHelper(
snackbarHostState = snackbarHostState
) {
/**
* **_collections** -> the current collections list displayed
*/
private val _collections = MutableStateFlow<SnapshotStateList<LinksCollection>>(
value = mutableStateListOf()
)
val collections: StateFlow<List<LinksCollection>> = _collections
/**
* Function to execute the request to get the collections list
*
* No-any params required
*/
fun getCollections() {
sendFetchRequest(
currentContext = CollectionListScreen::class.java,
request = {
requester.getCollections()
},
onSuccess = { response ->
_collections.value = returnCollections(response.getJSONArray(RESPONSE_MESSAGE_KEY))
.toMutableStateList()
localUser.setCollections(_collections.value)
}
)
}
}
| 0
|
Kotlin
|
0
| 0
|
9aad2edeac2a2e1bbe8a27c219be31b4a29dd4a4
| 2,405
|
Refy-Desktop
|
MIT License
|
app/src/androidTest/java/com/bandiago/cointrends/activity/MainActivityTest.kt
|
franticnick
| 158,977,620
| false
| null |
/*
* Copyright (c) 2018 Bandiago
*
* 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.bandiago.cointrends.activity
import android.view.View
import android.view.ViewGroup
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.Espresso.pressBack
import androidx.test.espresso.action.ViewActions.*
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.filters.LargeTest
import androidx.test.rule.ActivityTestRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.bandiago.cointrends.R
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.allOf
import org.hamcrest.TypeSafeMatcher
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@LargeTest
@RunWith(AndroidJUnit4::class)
class MainActivityTest {
@Rule
@JvmField
var mActivityTestRule = ActivityTestRule(MainActivity::class.java)
@Test
fun mainActivityTest3() {
val actionMenuItemView = onView(
allOf(
withId(R.id.search), withContentDescription("Coin Trends"),
childAtPosition(
childAtPosition(
withId(R.id.toolbar),
1
),
0
),
isDisplayed()
)
)
actionMenuItemView.perform(click())
val appCompatImageView = onView(
allOf(
withClassName(`is`("androidx.appcompat.widget.AppCompatImageView")), withContentDescription("Search"),
childAtPosition(
allOf(
withClassName(`is`("android.widget.LinearLayout")),
childAtPosition(
withId(R.id.search),
0
)
),
1
),
isDisplayed()
)
)
appCompatImageView.perform(click())
val searchAutoComplete = onView(
allOf(
withResourceName(`is`("search_src_text")),
childAtPosition(
allOf(
withClassName(`is`("android.widget.LinearLayout")),
childAtPosition(
withClassName(`is`("android.widget.LinearLayout")),
1
)
),
0
),
isDisplayed()
)
)
searchAutoComplete.perform(replaceText("btc"), closeSoftKeyboard())
val searchAutoComplete2 = onView(
allOf(
withResourceName(`is`("search_src_text")), withText("btc"),
childAtPosition(
allOf(
withClassName(`is`("android.widget.LinearLayout")),
childAtPosition(
withClassName(`is`("android.widget.LinearLayout")),
1
)
),
0
),
isDisplayed()
)
)
searchAutoComplete2.perform(pressImeActionButton())
// Added a sleep statement to match the app's execution delay.
// The recommended way to handle such scenarios is to use Espresso idling resources:
// https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
Thread.sleep(700)
val appCompatImageView2 = onView(
allOf(
withClassName(`is`("androidx.appcompat.widget.AppCompatImageView")),
withContentDescription("Clear query"),
childAtPosition(
allOf(
withClassName(`is`("android.widget.LinearLayout")),
childAtPosition(
withClassName(`is`("android.widget.LinearLayout")),
1
)
),
1
),
isDisplayed()
)
)
appCompatImageView2.perform(click())
val appCompatImageButton = onView(
allOf(
withContentDescription("Collapse"),
childAtPosition(
allOf(
withId(R.id.toolbar),
childAtPosition(
withId(R.id.activity_main),
0
)
),
1
),
isDisplayed()
)
)
appCompatImageButton.perform(click())
pressBack()
}
private fun childAtPosition(
parentMatcher: Matcher<View>, position: Int
): Matcher<View> {
return object : TypeSafeMatcher<View>() {
override fun describeTo(description: Description) {
description.appendText("Child at position $position in parent ")
parentMatcher.describeTo(description)
}
public override fun matchesSafely(view: View): Boolean {
val parent = view.parent
return parent is ViewGroup && parentMatcher.matches(parent)
&& view == parent.getChildAt(position)
}
}
}
}
| 0
|
Kotlin
|
3
| 16
|
d4b732462f78ffb0bf7c805effed1f8d04d0d79a
| 6,022
|
cointrends
|
Apache License 2.0
|
superwall/src/main/java/com/superwall/sdk/misc/CurrentActivityTracker.kt
|
superwall
| 642,585,064
| false
|
{"Kotlin": 1190760}
|
package com.superwall.sdk.misc
import android.app.Activity
import android.app.Application
import android.os.Bundle
class CurrentActivityTracker :
Application.ActivityLifecycleCallbacks,
ActivityProvider {
private var currentActivity: Activity? = null
override fun onActivityCreated(
activity: Activity,
savedInstanceState: Bundle?,
) {
println("!! onActivityCreated: $activity")
}
override fun onActivityStarted(activity: Activity) {
println("!! onActivityStarted: $activity")
currentActivity = activity
}
override fun onActivityResumed(activity: Activity) {
println("!! onActivityResumed: $activity")
currentActivity = activity
}
override fun onActivityPaused(activity: Activity) {}
override fun onActivityStopped(activity: Activity) {}
override fun onActivitySaveInstanceState(
activity: Activity,
outState: Bundle,
) {}
override fun onActivityDestroyed(activity: Activity) {
println("!! onActivityDestroyed: $activity")
if (currentActivity == activity) {
currentActivity = null
}
}
override fun getCurrentActivity(): Activity? {
println("!! getCurrentActivity: $currentActivity")
return currentActivity
}
}
| 6
|
Kotlin
|
3
| 9
|
2582de8d48af7c0ad080e30949d920e8a34d9219
| 1,316
|
Superwall-Android
|
MIT License
|
sphinx/service/features/media-player/feature-service-media-player-android/src/main/java/chat/sphinx/feature_service_media_player_android/di/MediaServiceModule.kt
|
stakwork
| 340,103,148
| false
|
{"Kotlin": 4019370, "Java": 403469, "JavaScript": 4745, "HTML": 4706, "Shell": 2453}
|
package chat.sphinx.feature_service_media_player_android.di
import android.app.Application
import chat.sphinx.concept_repository_feed.FeedRepository
import chat.sphinx.concept_service_media.MediaPlayerServiceController
import chat.sphinx.feature_service_media_player_android.MediaPlayerServiceControllerImpl
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import io.matthewnelson.concept_coroutines.CoroutineDispatchers
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
internal object MediaServiceModule {
@Singleton
@Provides
fun provideMediaServiceControllerImpl(
app: Application,
dispatchers: CoroutineDispatchers,
feedRepository: FeedRepository,
): MediaPlayerServiceControllerImpl =
MediaPlayerServiceControllerImpl(
app,
dispatchers,
feedRepository,
)
@Provides
fun provideMediaServiceController(
mediaServiceControllerImpl: MediaPlayerServiceControllerImpl
): MediaPlayerServiceController =
mediaServiceControllerImpl
}
| 90
|
Kotlin
|
11
| 18
|
a28cbb8174ef7874d156f31e22023b014cba6029
| 1,153
|
sphinx-kotlin
|
MIT License
|
core_android/src/main/java/mohamedalaa/mautils/core_android/extensions/_Log.kt
|
MohamedAlaaEldin636
| 178,618,838
| false
| null |
/*
* Copyright (c) 2019 Mohamed Alaa
*
* 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 mohamedalaa.mautils.core_android.extensions
import android.util.Log
import mohamedalaa.mautils.core_kotlin.extensions.lastIndexOfOrNull
import mohamedalaa.mautils.core_kotlin.extensions.safeNext
/**
* - Same as [Log.v] but with tag "V" and msg prefixed by class simple name and line of occurrence isa.
*
* @see logInfo
*/
fun logVerbose(msg: String) = privateLog(
LogLevel.VERBOSE,
msg
)
/**
* - Same as [Log.i] but with tag "I" and msg prefixed by class simple name and line of occurrence isa.
*
* @see logVerbose
* @see logWarn
*/
fun logInfo(msg: String) = privateLog(
LogLevel.INFO,
msg
)
/**
* - Same as [Log.w] but with tag "W" and msg prefixed by class simple name and line of occurrence isa.
*
* @see logInfo
* @see logError
*/
fun logWarn(msg: String) = privateLog(
LogLevel.WARN,
msg
)
/**
* - Same as [Log.e] but with tag "E" and msg prefixed by class simple name and line of occurrence isa.
*
* @see logWarn
* @see logWTF
*/
fun logError(msg: String) = privateLog(
LogLevel.ERROR,
msg
)
/**
* - Same as [Log.wtf] but with tag "WTF" and msg prefixed by class simple name and line of occurrence isa.
*
* @see logError
*/
fun logWTF(msg: String) = privateLog(
LogLevel.ASSERT,
msg
)
private fun privateLog(logLevel: LogLevel, msg: String) {
val iterator = Thread.currentThread().stackTrace.iterator()
while (iterator.hasNext()) {
val methodName = iterator.next().methodName
if (methodName == ::privateLog.name) {
iterator.safeNext()
val a = iterator.safeNext()
val innerMsg = a.classSimpleName() + " : at line ${a?.lineNumber} : $msg"
when (logLevel) {
LogLevel.VERBOSE -> Log.v("V", innerMsg)
LogLevel.DEBUG -> Log.d("D", innerMsg)
LogLevel.INFO -> Log.i("I", innerMsg)
LogLevel.WARN -> Log.w("W", innerMsg)
LogLevel.ERROR -> Log.e("E", innerMsg)
LogLevel.ASSERT -> Log.wtf("WTF", innerMsg)
}
return
}
}
}
private fun StackTraceElement?.classSimpleName() = this?.className?.classSimpleName() ?: "Unknown Class Name"
private enum class LogLevel {
VERBOSE, DEBUG, INFO, WARN, ERROR, ASSERT
}
private fun String.classSimpleName(): String {
return lastIndexOfOrNull(".")?.run {
if (this == lastIndex) "" else substring(inc())
} ?: this
}
| 0
|
Kotlin
|
0
| 0
|
16d6a8fdbf0d851c74485bdc1a609afaf3bb76f9
| 3,049
|
MAUtils
|
Apache License 2.0
|
app/src/main/java/com/stanford/edu/HistoryActivity.kt
|
qwang70
| 258,441,849
| false
| null |
package com.stanford.edu
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.stanford.edu.MyApplication.Companion.tipInfoList
class HistoryActivity : AppCompatActivity() {
private lateinit var recyclerView: RecyclerView
private lateinit var viewAdapter: RecyclerView.Adapter<*>
private lateinit var viewManager: RecyclerView.LayoutManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.history_activity)
viewManager = LinearLayoutManager(this)
viewAdapter = TipInfoAdapter(tipInfoList)
recyclerView = findViewById<RecyclerView>(R.id.my_recycler_view).apply {
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
setHasFixedSize(true)
// use a linear layout manager
layoutManager = viewManager
// specify an viewAdapter (see also next example)
adapter = viewAdapter
}
}
}
| 0
|
Kotlin
|
0
| 0
|
eae96df7bacb0fdf4fdd1cece7dfe9c9a736d81f
| 1,212
|
Tippy
|
Apache License 2.0
|
app/src/main/java/app/razar/vincent_sample/App.kt
|
razar-dev
| 379,371,419
| false
| null |
package app.razar.vincent_sample
import android.app.Application
import app.razar.vincent.Style
import app.razar.vincent.StylePack
import app.razar.vincent.initVincent
class App: Application() {
override fun onCreate() {
super.onCreate()
val setting = getSharedPreferences("app.razar.vincent_sample_preferences", MODE_PRIVATE)
initVincent(
//Default style pack (MainActivity, SettingsActivity)
StylePack(null, listOf(
Style(R.style.Theme_VincentLight),
Style(R.style.Theme_VincentDark, true)
)),
//Override style pack for MainActivity2
StylePack(MainActivity2::class, listOf(
Style(R.style.Theme_Vincent2Light),
Style(R.style.Theme_Vincent2Dark, true)
)),
defaultStyle = setting.getString("style", "0")?.toInt() ?: 0
)
}
}
| 0
|
Kotlin
|
0
| 0
|
cd516f1fe6e92a2653395cd3f08c249d7392c8dc
| 913
|
Vincent
|
Apache License 2.0
|
sample/sample-app/src/test/kotlin/com/farcsal/sample/testengine/clock/TestClock.kt
|
fzoli
| 541,286,565
| false
|
{"Kotlin": 369907, "ANTLR": 1659}
|
/*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.farcsal.sample.testengine.clock
import java.time.Clock
import java.time.Instant
import java.time.ZoneId
class TestClock(private val zoneId: ZoneId = ZoneId.of("UTC")) : Clock() {
private var instant: Instant = Instant.EPOCH
override fun getZone(): ZoneId {
return zoneId
}
override fun withZone(zoneId: ZoneId): Clock {
return TestClock(zoneId)
}
override fun instant(): Instant {
return instant
}
fun setInstant(instant: Instant) {
this.instant = instant
}
}
| 0
|
Kotlin
|
0
| 1
|
a3ead5eaf24c7189f2507e7d8aba25ff76e53ef9
| 1,138
|
dql-kotlin
|
Apache License 2.0
|
src/main/kotlin/me/duncte123/io/Main.kt
|
dunste123
| 768,797,973
| false
|
{"Kotlin": 13960, "Dockerfile": 368}
|
package me.duncte123.io
import net.dv8tion.jda.api.JDABuilder
val commandManager = CommandManager()
fun main() {
commandManager.registerUserCommands()
JDABuilder.createLight(System.getenv("BOT_TOKEN"))
.addEventListeners(Listener())
.build()
}
| 0
|
Kotlin
|
1
| 0
|
d5ead22bb3cfeffd6256e5c96761723ea046695b
| 272
|
io
|
MIT License
|
src/main/kotlin/org/partiql/scribe/ScribeCompiler.kt
|
partiql
| 716,254,976
| false
|
{"Kotlin": 322500}
|
package org.partiql.scribe
import org.partiql.ast.AstNode
import org.partiql.ast.Statement
import org.partiql.ast.Type
import org.partiql.ast.util.AstRewriter
import org.partiql.errors.Problem
import org.partiql.errors.ProblemCallback
import org.partiql.errors.ProblemSeverity
import org.partiql.parser.PartiQLParser
import org.partiql.plan.PartiQLPlan
import org.partiql.planner.PartiQLPlanner
import org.partiql.types.function.FunctionSignature
/**
* ScribeCompiler is a full text-to-text compiler pipeline for the PartiQL Scribe project.
*
* @property parser
* @property planner
*/
public class ScribeCompiler internal constructor(
private val parser: PartiQLParser,
private val planner: PartiQLPlanner,
private val functions: List<FunctionSignature.Scalar>
) {
// backend
private val scribe: Scribe = Scribe()
/**
* Entry-point to scribe via text.
*
* @param T
* @param statement
* @param target
* @param session
* @return
*/
@Throws(ScribeException::class)
public fun <T> compile(
statement: String,
target: ScribeTarget<T>,
session: PartiQLPlanner.Session,
): Scribe.Result<T> {
try {
var ast = parse(statement)
// TODO: REMOVE ME
// PartiQL came from Ion SQL which uses the INT name for the unbounded integer.
// In SQL, the INT name must have some finite precision and most systems use a 32-bit integer.
// Scribe is built to interface with other systems, so we must change all occurrences of the INT
// type name with INT4. In short, all systems do INT = INT4 but PartiQL has INT4 != INT.
// >>>> ISSUE — https://github.com/partiql/partiql-lang-kotlin/issues/1471
ast = replaceIntWithInt4(ast)
val plan = plan(ast, session)
return scribe.compile(plan, target)
} catch (e: ScribeException) {
throw e
} catch (cause: Throwable) {
throw ScribeException(cause.message, cause)
}
}
private fun parse(source: String): Statement {
val result = parser.parse(source)
return result.root
}
private class PlanProblemCallback: ProblemCallback {
val problems = mutableListOf<Problem>()
override fun invoke(p1: Problem) {
problems.add(p1)
}
}
private fun plan(statement: Statement, session: PartiQLPlanner.Session): PartiQLPlan {
val callback = PlanProblemCallback()
val result = planner.plan(statement, session, onProblem = callback)
val errors = callback.problems.filter { it.details.severity == ProblemSeverity.ERROR }
if (errors.isNotEmpty()) {
throw RuntimeException("Planner encountered errors: ${errors.joinToString()}")
}
return result.plan
}
companion object {
@JvmStatic
public fun builder(): ScribeCompilerBuilder = ScribeCompilerBuilder()
}
/**
* Rewrite all occurrences of INT with INT4.
*/
private fun replaceIntWithInt4(ast: Statement): Statement {
val rewriter = object : AstRewriter<Unit>() {
override fun visitTypeInt(node: Type.Int, ctx: Unit): AstNode = Type.Int4()
}
return rewriter.visitStatement(ast, Unit) as Statement
}
}
| 6
|
Kotlin
|
0
| 4
|
b295356e7112bbf364f4bdb0727d24c7bdda8ff3
| 3,361
|
partiql-scribe
|
Apache License 2.0
|
library/sync/src/main/java/ir/kaaveh/sync/initializer/SyncInitializer.kt
|
Kaaveh
| 576,928,671
| false
| null |
package ir.kaaveh.sync.initializer
import android.content.Context
import androidx.startup.Initializer
import androidx.work.ExistingWorkPolicy
import androidx.work.WorkManager
import androidx.work.WorkManagerInitializer
import ir.kaaveh.sync.Sync
import ir.kaaveh.sync.SyncWorkName
import ir.kaaveh.sync.worker.SyncWorker
class SyncInitializer : Initializer<Sync> {
override fun create(context: Context): Sync {
WorkManager.getInstance(context).apply {
// Run sync on app startup and ensure only one sync worker runs at any time
enqueueUniqueWork(
SyncWorkName,
ExistingWorkPolicy.KEEP,
SyncWorker.startUpSyncWork()
)
}
return Sync
}
override fun dependencies(): List<Class<out Initializer<*>>> =
listOf(WorkManagerInitializer::class.java)
}
| 1
|
Kotlin
|
14
| 98
|
d0504db4e522a95b8732ed04a0de35eef7def700
| 872
|
ComposeNews
|
Apache License 2.0
|
AndroidFirebaseApp/app/src/main/java/br/inatel/alexander/androidfirebaseapp/productdetail/ProductDetailViewModel.kt
|
inatel-codes
| 497,574,642
| false
|
{"Kotlin": 61929, "CMake": 1779, "C++": 356}
|
package br.inatel.alexander.androidfirebaseapp.productdetail
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import br.inatel.alexander.androidfirebaseapp.model.Product
import br.inatel.alexander.androidfirebaseapp.persistence.ProductRepository
private const val TAG = "ProductDetailViewModel"
class ProductDetailViewModel(private val code: String?): ViewModel() {
lateinit var product: MutableLiveData<Product>
init {
if (code != null) {
getProduct(code)
} else {
product = MutableLiveData<Product>()
product.value = Product()
}
}
private fun getProduct(productCode: String) {
Log.i(TAG, "Preparing to request a product by its code")
product = ProductRepository.getProductByCode(productCode)
Log.i(TAG, "Product requested by code")
}
fun saveProduct() {
Log.i(TAG, "Saving product " + (product.value?.name ?: "NOT FOUND"))
if (product.value != null && product.value!!.code != null && product.value!!.code!!.isNotBlank()) {
ProductRepository.saveProduct(product.value!!)
}
}
fun deleteProduct() {
Log.i(TAG, "Deleting product " + (product.value?.name ?: "NOT FOUND"))
if (product.value?.id != null) {
ProductRepository.deleteProduct(product.value!!.id!!)
product.value = null
}
}
override fun onCleared() {
Log.i(TAG, "onCleared")
super.onCleared()
}
}
| 0
|
Kotlin
|
0
| 0
|
4006bc620359b879338830ea938f084b1f63ed46
| 1,546
|
DM125
|
MIT License
|
src/main/kotlin/com/forgerock/sapi/gateway/framework/configuration/ExternalSystemDependenciesConfig.kt
|
SecureApiGateway
| 795,036,493
| false
|
{"Kotlin": 116164, "Makefile": 1375, "Dockerfile": 379}
|
package com.forgerock.sapi.gateway.framework.configuration
/**
* This class is initialized by Jackson from the config file specified in Config.kt
*/
data class ExternalSystemDependenciesConfig(
val variables: List<String>,
val trustedDirectory: ProductionTrustedDirectoryConfig,
val apiUnderTest: ApiConfig
)
fun doVariableSubstitution(systemDependenciesConfig: ExternalSystemDependenciesConfig, variables: Map<String, String>){
systemDependenciesConfig.trustedDirectory.name =
substituteVariables(systemDependenciesConfig.trustedDirectory.name, variables)
systemDependenciesConfig.trustedDirectory.jwks_uri =
substituteVariables(systemDependenciesConfig.trustedDirectory.jwks_uri, variables)
systemDependenciesConfig.trustedDirectory.openidWellKnown =
substituteVariables(systemDependenciesConfig.trustedDirectory.openidWellKnown, variables)
systemDependenciesConfig.trustedDirectory.ssaUrl =
substituteVariables(systemDependenciesConfig.trustedDirectory.ssaUrl, variables)
systemDependenciesConfig.trustedDirectory.scopesToAccessSsa =
substituteVariables(systemDependenciesConfig.trustedDirectory.scopesToAccessSsa, variables)
systemDependenciesConfig.trustedDirectory.apiClients.forEach {
it.orgId = substituteVariables(it.orgId, variables)
it.softwareId = substituteVariables(it.softwareId, variables)
it.publicSigningKeyID = substituteVariables(it.publicSigningKeyID, variables)
it.publicSigningPemPath = substituteVariables(it.publicSigningPemPath, variables)
it.privateSigningPemPath = substituteVariables(it.privateSigningPemPath, variables)
it.privateTransportPemPath = substituteVariables(it.privateTransportPemPath, variables)
it.publicTransportKeyID = substituteVariables(it.publicTransportKeyID, variables)
it.publicTransportPemPath = substituteVariables(it.publicTransportPemPath, variables)
}
systemDependenciesConfig.apiUnderTest.name =
substituteVariables(systemDependenciesConfig.apiUnderTest.name, variables)
systemDependenciesConfig.apiUnderTest.serverDomain =
substituteVariables(systemDependenciesConfig.apiUnderTest.serverDomain, variables)
systemDependenciesConfig.apiUnderTest.oidcWellKnownUrl =
substituteVariables(systemDependenciesConfig.apiUnderTest.oidcWellKnownUrl, variables)
systemDependenciesConfig.apiUnderTest.rsDiscoveryUrl =
substituteVariables(systemDependenciesConfig.apiUnderTest.rsDiscoveryUrl, variables)
systemDependenciesConfig.apiUnderTest.devTrustedDirectory.oidcWellKnownUrl =
substituteVariables(systemDependenciesConfig.apiUnderTest.devTrustedDirectory.oidcWellKnownUrl, variables)
systemDependenciesConfig.apiUnderTest.devTrustedDirectory.getKeysUrl =
substituteVariables(systemDependenciesConfig.apiUnderTest.devTrustedDirectory.getKeysUrl, variables)
systemDependenciesConfig.apiUnderTest.devTrustedDirectory.getTransportPemsUrl =
substituteVariables(systemDependenciesConfig.apiUnderTest.devTrustedDirectory.getTransportPemsUrl, variables)
systemDependenciesConfig.apiUnderTest.devTrustedDirectory.getSigningPemsUrl =
substituteVariables(systemDependenciesConfig.apiUnderTest.devTrustedDirectory.getSigningPemsUrl, variables)
systemDependenciesConfig.apiUnderTest.devTrustedDirectory.getSsaUrl =
substituteVariables(systemDependenciesConfig.apiUnderTest.devTrustedDirectory.getSsaUrl, variables)
}
fun substituteVariables(templateValue: String, variables: Map<String, String>): String{
var substitutedString = templateValue
for(variable in variables){
substitutedString = substituteVariable(substitutedString, "{{${variable.key}}}", variable.value)
}
return substitutedString
}
fun substituteVariable(templateValue: String, variableName: String, variableValue: String): String{
return templateValue.replace(variableName, variableValue)
}
| 1
|
Kotlin
|
0
| 0
|
446a008372ac1fcc95424f9c45e979ce75e54cc9
| 3,981
|
secure-api-gateway-functional-test-framework
|
Apache License 2.0
|
multiplatform-compose/src/commonMain/kotlin/com/rouge41/kmm/compose/material/Text.kt
|
cl3m
| 327,994,833
| false
| null |
package com.rouge41.kmm.compose.material
import com.rouge41.kmm.compose.runtime.Composable
import com.rouge41.kmm.compose.ui.Modifier
import com.rouge41.kmm.compose.ui.graphics.Color
@Composable
expect fun Text(
text: String,
modifier: Modifier = Modifier,
color: Color = Color.Unspecified)
| 2
|
Kotlin
|
24
| 458
|
4bf075118ccc5f80d03e4ed28118299e1b749182
| 316
|
multiplatform-compose
|
Apache License 2.0
|
app/src/main/java/com/lyscraft/apparel/compose/theme/Font.kt
|
brahman10
| 843,088,920
| false
|
{"Kotlin": 47388}
|
package com.lyscraft.apparel.compose.theme
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import com.lyscraft.apparel.R
val Montserrat = FontFamily(
//normal
Font(R.font.montserrat_thin, FontWeight.Thin),
Font(R.font.montserrat_extra_light, FontWeight.ExtraLight),
Font(R.font.montserrat_light, FontWeight.Light),
Font(R.font.montserrat_regular, FontWeight.Normal),
Font(R.font.montserrat_medium, FontWeight.Medium),
Font(R.font.montserrat_semi_bold, FontWeight.SemiBold),
Font(R.font.montserrat_bold, FontWeight.Bold),
Font(R.font.montserrat_extra_bold, FontWeight.ExtraBold),
Font(R.font.montserrat_black, FontWeight.Black),
//italic
Font(R.font.montserrat_thin, FontWeight.Thin),
Font(R.font.montserrat_extra_light, FontWeight.ExtraLight),
Font(R.font.montserrat_light, FontWeight.Light),
Font(R.font.montserrat_regular, FontWeight.Normal),
Font(R.font.montserrat_medium, FontWeight.Medium),
Font(R.font.montserrat_semi_bold, FontWeight.SemiBold),
Font(R.font.montserrat_bold, FontWeight.Bold),
Font(R.font.montserrat_extra_bold, FontWeight.ExtraBold),
Font(R.font.montserrat_black, FontWeight.Black),
)
| 0
|
Kotlin
|
0
| 0
|
fdfbc5a48a48933d667f97aefba8348f11bf56d8
| 1,280
|
MovieAppCompose
|
MIT License
|
feature-staking-impl/src/main/java/io/novafoundation/nova/feature_staking_impl/presentation/staking/rewardDestination/confirm/parcel/ConfirmRewardDestinationPayload.kt
|
novasamatech
| 415,834,480
| false
|
{"Kotlin": 11121812, "Rust": 25308, "Java": 17664, "JavaScript": 425}
|
package io.novafoundation.nova.feature_staking_impl.presentation.staking.rewardDestination.confirm.parcel
import android.os.Parcelable
import io.novafoundation.nova.feature_wallet_api.presentation.mixin.fee.FeeParcelModel
import kotlinx.android.parcel.Parcelize
@Parcelize
class ConfirmRewardDestinationPayload(
val fee: FeeParcelModel,
val rewardDestination: RewardDestinationParcelModel,
) : Parcelable
| 12
|
Kotlin
|
30
| 50
|
127f8739ca86dc74d006f018237daed0de5095a1
| 415
|
nova-wallet-android
|
Apache License 2.0
|
core/util/src/commonMain/kotlin/com/thomaskioko/tvmaniac/util/DateFormatter.kt
|
c0de-wizard
| 361,393,353
| false
| null |
package com.thomaskioko.tvmaniac.util
const val DATE_PATTERN = "EEE, MMM d, yyyy"
interface DateFormatter {
/**
* Returns the current time in milliseconds
*
* @return timestamp
*/
fun getTimestampMilliseconds(): Long
/**
* Formats date to provided pattern
*
* @param datePattern
* @param dateString
*/
fun formatDateString(
datePattern: String = DATE_PATTERN,
dateString: String,
): String
}
| 9
|
Kotlin
|
13
| 98
|
8bc3853d84c58520dffe26ddb260a2e7b6482ae9
| 479
|
tv-maniac
|
Apache License 2.0
|
tipoftheday/src/main/kotlin/com/deflatedpickle/rawky/tipoftheday/TipOfTheDay.kt
|
DeflatedPickle
| 286,057,841
| false
| null |
/* Copyright (c) 2020 DeflatedPickle under the MIT license */
package com.deflatedpickle.rawky.tipoftheday
import com.deflatedpickle.haruhi.Haruhi
import com.deflatedpickle.haruhi.api.plugin.Plugin
import com.deflatedpickle.haruhi.api.plugin.PluginType
import com.deflatedpickle.haruhi.event.EventWindowShown
import com.deflatedpickle.rawky.tipoftheday.event.EventAddTip
import org.jdesktop.swingx.JXTipOfTheDay
import org.jdesktop.swingx.tips.DefaultTipOfTheDayModel
import org.jdesktop.swingx.tips.TipOfTheDayModel
@Plugin(
value = "tip_of_the_day",
author = "DeflatedPickle",
version = "1.0.0",
description =
"""
<br>
Provides a dialog to show tips other plugins have registered
""",
type = PluginType.API,
)
@Suppress("unused")
object TipOfTheDay {
private val tips = mutableListOf<TipOfTheDayModel.Tip>()
init {
EventWindowShown.addListener {
if (it != Haruhi.window) return@addListener
EventAddTip.trigger(this.tips)
if (this.tips.size > 0) {
val model = DefaultTipOfTheDayModel(this.tips)
val tipOfTheDay = JXTipOfTheDay(model)
tipOfTheDay.showDialog(it)
}
}
}
}
| 1
|
Kotlin
|
0
| 0
|
67bff386b444a4ac443fb1b0e262ea57557a5f3b
| 1,244
|
sniffle
|
MIT License
|
Kotlin/src/main/kotlin/fr97/medium/Encryption.kt
|
FR97
| 273,481,555
| false
| null |
package fr97.medium
import java.util.*
import kotlin.io.*
import kotlin.math.sqrt
fun encryption(s: String): String {
val withoutSpaces = s.filterNot { it == ' ' }
val lengthSqrt = sqrt(withoutSpaces.length.toDouble()).toInt()
val col = if(withoutSpaces.length > lengthSqrt*lengthSqrt) lengthSqrt+1 else lengthSqrt
val matrix = withoutSpaces
.chunked(col)
.map { it.chunked(1) }
return matrix.getOrElse(0) { emptyList() }
.mapIndexed { i, _ -> matrix.map { c -> c.getOrElse(i){""} } }
.joinToString(" ") { it.joinToString("") }
}
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val s = scan.nextLine()
val result = encryption(s)
println(result)
}
| 0
|
Kotlin
|
0
| 0
|
1b13faaa1e7976c55b7400f901c6a84a2e2c52fc
| 738
|
hackerrank
|
MIT License
|
app/src/main/java/com/megical/easyaccess/example/MainActivity.kt
|
megical
| 369,156,591
| false
|
{"Kotlin": 23831}
|
package com.megical.easyaccess.example
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.megical.easyaccess.example.ui.main.ExampleFragment
import timber.log.Timber
import timber.log.Timber.DebugTree
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Timber.plant(DebugTree())
setContentView(R.layout.main_activity)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, ExampleFragment.newInstance())
.commitNow()
}
}
}
| 0
|
Kotlin
|
1
| 0
|
4e5434df7e4ab6cc2697cae2b6294da7494c510b
| 678
|
megical-easyaccess-example-android
|
MIT License
|
backend/todolist/src/main/kotlin/com/steiner/workbench/todolist/service/TaskProjectService.kt
|
nesteiner
| 693,014,583
| false
|
{"Kotlin": 366481, "Dart": 247737, "C++": 24228, "CMake": 19460, "HTML": 1843, "C": 1425}
|
package com.steiner.workbench.todolist.service
import com.steiner.workbench.common.DEFAULT_AVATAR_ID
import com.steiner.workbench.common.exception.BadRequestException
import com.steiner.workbench.common.util.Page
import com.steiner.workbench.login.table.Users
import com.steiner.workbench.todolist.model.TaskProject
import com.steiner.workbench.todolist.request.PostTaskProjectRequest
import com.steiner.workbench.todolist.request.UpdateTaskProjectRequest
import com.steiner.workbench.todolist.table.TaskProjects
import com.steiner.workbench.todolist.util.mustExistIn
import com.steiner.workbench.common.util.now
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.SqlExpressionBuilder.inList
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import kotlin.math.ceil
@Service
@Transactional
class TaskProjectService {
@Autowired
lateinit var taskgroupService: TaskGroupService
@Autowired
lateinit var tagService: TagService
fun insertOne(request: PostTaskProjectRequest): TaskProject {
mustExistIn(request.userid, Users)
val iftaskgroup = TaskProjects
.slice(TaskProjects.id)
.select(TaskProjects.name eq request.name)
.firstOrNull()
if (iftaskgroup != null) {
throw BadRequestException("duplicate name of taskproject")
}
TaskProjects.update({ TaskProjects.userid eq request.userid }) {
with (SqlExpressionBuilder) {
it.update(index, index + 1)
}
}
val nowInstant = now()
val id = TaskProjects.insert {
it[name] = request.name
it[index] = 1
it[avatarid] = request.avatarid ?: DEFAULT_AVATAR_ID
it[userid] = request.userid
it[createTime] = nowInstant
it[updateTime] = nowInstant
if (request.profile != null) {
it[profile] = request.profile
}
} get TaskProjects.id
return findOne(id.value)!!
}
fun deleteOne(id: Int) {
tagService.deleteAll(id)
taskgroupService.deleteAll(id)
TaskProjects.deleteWhere {
TaskProjects.id eq id
}
}
fun deleteAll(userid: Int) {
val projectids = TaskProjects.slice(TaskProjects.id).select(TaskProjects.userid eq userid).map {
it[TaskProjects.id]
}
projectids.forEach {
tagService.deleteAll(it.value)
taskgroupService.deleteAll(it.value)
}
TaskProjects.deleteWhere {
TaskProjects.id.inList(projectids)
}
}
fun updateOne(request: UpdateTaskProjectRequest): TaskProject {
mustExistIn(request.id, TaskProjects)
TaskProjects.update({ TaskProjects.id eq request.id }) {
if (request.name != null) {
it[name] = request.name
}
if (request.avatarid != null) {
it[avatarid] = request.avatarid
}
it[updateTime] = now()
if (request.profile != null) {
it[profile] = request.profile
}
}
return findOne(request.id)!!
}
fun findOne(id: Int): TaskProject? {
return TaskProjects.select(TaskProjects.id eq id)
.firstOrNull()
?.let {
TaskProject(
id = id,
name = it[TaskProjects.name],
index = it[TaskProjects.index],
avatarid = it[TaskProjects.avatarid].value,
profile = it[TaskProjects.profile],
userid = it[TaskProjects.userid].value,
createTime = it[TaskProjects.createTime],
updateTime = it[TaskProjects.updateTime]
)
}
}
fun findAll(userid: Int): List<TaskProject> {
return TaskProjects.select(TaskProjects.userid eq userid)
.orderBy(TaskProjects.index)
.map {
val projectid = it[TaskProjects.id].value
TaskProject(
id = projectid,
name = it[TaskProjects.name],
index = it[TaskProjects.index],
avatarid = it[TaskProjects.avatarid].value,
profile = it[TaskProjects.profile],
userid = userid,
createTime = it[TaskProjects.createTime],
updateTime = it[TaskProjects.updateTime]
)
}
}
fun findAll(userid: Int, page: Int, size: Int): Page<TaskProject> {
val content = TaskProjects.select(TaskProjects.userid eq userid)
.limit(size, offset = page * size.toLong())
.map {
val projectid = it[TaskProjects.id].value
TaskProject(
id = projectid,
name = it[TaskProjects.name],
index = it[TaskProjects.index],
avatarid = it[TaskProjects.avatarid].value,
profile = it[TaskProjects.profile],
userid = userid,
createTime = it[TaskProjects.createTime],
updateTime = it[TaskProjects.updateTime]
)
}
val totalPages = ceil(TaskProjects.selectAll().count() / size.toDouble()).toInt()
return Page(content, totalPages)
}
}
| 1
|
Kotlin
|
0
| 0
|
e0fe7a0f9aca965bc74736f1364153a695597bfe
| 5,914
|
Workbench
|
MIT License
|
app/src/main/kotlin/ru/maksonic/beresta/ui/MainActivity.kt
|
maksonic
| 580,058,579
| false
|
{"Kotlin": 1622432}
|
package ru.maksonic.beresta.ui
import android.content.res.Configuration
import android.graphics.Color
import android.os.Bundle
import androidx.activity.SystemBarStyle
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalConfiguration
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.view.WindowCompat
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.lifecycleScope
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.rememberNavController
import org.koin.android.ext.android.inject
import org.koin.androidx.viewmodel.ext.android.viewModel
import ru.maksonic.beresta.common.core.ScreenCaptureManager
import ru.maksonic.beresta.common.ui_kit.bar.system.SystemStatusBarHeight
import ru.maksonic.beresta.common.ui_theme.AppThemeUi
import ru.maksonic.beresta.common.ui_theme.BaseTheme
import ru.maksonic.beresta.common.ui_theme.Theme
import ru.maksonic.beresta.common.ui_theme.colors.background
import ru.maksonic.beresta.common.ui_theme.provide.dp4
import ru.maksonic.beresta.core.MainActivitySandbox
import ru.maksonic.beresta.core.Msg
import ru.maksonic.beresta.navigation.graph_builder.GraphBuilder
import ru.maksonic.beresta.navigation.router.core.AbstractNavigator
import ru.maksonic.beresta.navigation.router.core.Destination
class MainActivity : FragmentActivity() {
private val sandbox: MainActivitySandbox by viewModel()
private val navigator: AbstractNavigator by inject()
private val graphBuilder: GraphBuilder by inject()
private val screenCaptureManager: ScreenCaptureManager by inject()
override fun onCreate(savedInstanceState: Bundle?) {
WindowCompat.setDecorFitsSystemWindows(window, false)
installSplashScreen()
screenCaptureManager.init(window, lifecycleScope)
super.onCreate(savedInstanceState)
setContent {
navigator.init(rememberNavController())
val model by sandbox.model.collectAsStateWithLifecycle(lifecycle)
val isSystemInDarkTheme = isSystemInDarkTheme()
val isDarkMode = when (model.currentTheme) {
AppThemeUi.SYSTEM -> isSystemInDarkTheme
AppThemeUi.DAY -> false
AppThemeUi.NIGHT -> true
AppThemeUi.DARK -> true
}
LaunchedEffect(isSystemInDarkTheme) {
sandbox.send(Msg.Inner.UpdatedThemeDarkModeValue(isDarkMode))
}
LaunchedEffect(model.currentTheme) {
sandbox.send(Msg.Inner.UpdatedThemeDarkModeValue(isDarkMode))
}
BaseTheme(
theme = model.currentTheme,
darkMode = model.darkMode,
palette = model.paletteContainer,
languages = model.languageProvider,
animationVelocity = model.animationVelocity
) {
LaunchedEffect(model.darkMode.value) {
val navigationBarStyle = with(Color.TRANSPARENT) {
if (model.darkMode.value) SystemBarStyle.dark(this)
else SystemBarStyle.light(this, this)
}
enableEdgeToEdge(
statusBarStyle = SystemBarStyle.auto(
lightScrim = Color.TRANSPARENT,
darkScrim = Color.TRANSPARENT,
detectDarkMode = { model.darkMode.value }
),
navigationBarStyle = navigationBarStyle
)
}
Scaffold(containerColor = background) { paddings ->
val screenOrientation = LocalConfiguration.current.orientation
val navigationVelocity = Theme.animVelocity.navigation
val velocity = Theme.animVelocity.navigation.fade
val landscapePadding =
if (screenOrientation == Configuration.ORIENTATION_LANDSCAPE)
Modifier.padding(end = SystemStatusBarHeight.plus(dp4)) else Modifier
NavHost(
navController = navigator.navController,
startDestination = Destination.route,
enterTransition = { fadeIn(tween(velocity)) },
exitTransition = { fadeOut(tween(velocity)) },
modifier = landscapePadding
) {
graphBuilder.buildGraph(graphBuilder = this, navigationVelocity)
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
227b0a5f6c27b0f731b1f6e81b1fe2deeaa720aa
| 5,202
|
Beresta
|
MIT License
|
src/test/kotlin/org/occidere/ticketseer/service/MusicalTicketRepositoryTest.kt
|
occidere
| 306,612,792
| false
| null |
package org.occidere.ticketseer.service
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.occidere.ticketseer.configuration.ElasticsearchConfiguration
import org.occidere.ticketseer.enums.SiteType
import org.occidere.ticketseer.vo.MusicalTicket
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories
import org.springframework.test.context.ContextConfiguration
/**
* @author occidere
* @Blog: https://occidere.blog.me
* @Github: https://github.com/occidere
* @since 2020-10-23
*/
@SpringBootTest
@EnableElasticsearchRepositories
@ContextConfiguration(classes = [
ElasticsearchConfiguration::class,
MusicalTicketRepository::class
])
class MusicalTicketRepositoryTest {
@Autowired
private val musicalTicketRepository: MusicalTicketRepository? = null
@Test
fun findAllByTicketTypeAndSvcYnTest() {
// BUILD
// OPERATE
val musicalTickets = musicalTicketRepository!!.findAllByTicketType()
// CHECK
println("musical = $musicalTickets")
Assertions.assertTrue(musicalTickets.isNotEmpty())
}
@Test
fun saveTest() {
// BUILD
val musicalTicket = MusicalTicket(
id = "20008287",
title = "뮤지컬 〈맨오브라만차〉",
place = "샤롯데씨어터",
pageUrl = "http://ticket.interpark.com/Ticket/Goods/GoodsInfo.asp?GroupCode=20008287",
startDate = "2020-12-18",
endDate = "2021-03-01",
siteType = SiteType.INTERPARK
)
// OPERATE
val saved = musicalTicketRepository!!.save(musicalTicket)
// CHECK
val found = musicalTicketRepository.findById(musicalTicket.id).get()
println("Saved = ${saved.toJsonString()}")
println("Found = ${found.toJsonString()}")
Assertions.assertEquals(saved.toJsonString(), found.toJsonString())
}
}
| 2
|
Kotlin
|
1
| 5
|
b8f87e4dc0ae9bef3be0dc0a72742039b86fa11a
| 2,072
|
ticketseer
|
Apache License 2.0
|
app/src/main/java/com/bulletapps/candypricer/data/repository/CandyPricerRepository.kt
|
jvsena42
| 485,055,339
| false
|
{"Kotlin": 265086}
|
package com.bulletapps.candypricer.data.repository
import com.bulletapps.candypricer.config.Resource
import com.bulletapps.candypricer.data.parameters.*
import com.bulletapps.candypricer.data.response.LoginResponse
import com.bulletapps.candypricer.data.response.UserResponse
import com.bulletapps.candypricer.domain.model.ProductModel
import com.bulletapps.candypricer.domain.model.SupplyModel
import com.bulletapps.candypricer.domain.model.UnitModel
import com.bulletapps.candypricer.domain.model.UserModel
interface CandyPricerRepository {
suspend fun createUser(parameters: CreateUserParameters): Resource<LoginResponse>
suspend fun getUser(isRefresh: Boolean): Result<UserModel>
suspend fun getUsers(): Result<List<UserModel>>
suspend fun updateExpirationDate(id:Int, expirationDate: String): Resource<Unit>
suspend fun deleteUser(): Resource<Unit>
suspend fun login(parameters: LoginParameters): Resource<LoginResponse>
suspend fun logout(): Result<Unit>
suspend fun createProduct(parameters: CreateProductParameters): Resource<Unit>
suspend fun getProducts(): Result<List<ProductModel>>
suspend fun updateProduct(id: Int, parameters: UpdateProductParameters): Resource<Unit>
suspend fun deleteProduct(id: Int): Resource<Unit>
suspend fun createSupply(parameters: CreateSupplyParameters): Resource<Unit>
suspend fun getSupplies(): Result<List<SupplyModel>>
suspend fun deleteSupply(id: Int): Resource<Unit>
suspend fun updateSupply(parameters: UpdateSupplyParameters): Resource<Unit>
suspend fun createUnit(parameters: CreateUnitParameters): Resource<Unit>
suspend fun getUnits(isRefresh: Boolean = false): Result<List<UnitModel>>
suspend fun deleteUnits(): Result<Unit>
}
| 18
|
Kotlin
|
0
| 2
|
c89da3d248d32f976ad7f0d918815822787ae33a
| 1,770
|
baking_calculator
|
MIT License
|
app/src/main/java/com/gram/pictory/model/UserModel.kt
|
notmyfault02
| 178,123,874
| false
| null |
package com.gram.pictory.model
//data class UserModel (
// var username: String,
// var id: String,
// var birth: String,
// var myfile: String,
// var active: Boolean,
// var profileIMG: String,
// var imageName: ArrayList<String>,
// var postCount: String,
// var followingCount: String,
// var followerCount: String
//)
data class UserModel (
val posts: ArrayList<Posts>,
val user: User
)
| 0
|
Kotlin
|
0
| 1
|
503ee703d906ee61c90ac737f3cfad86d662c20d
| 432
|
Pictory_Master
|
MIT License
|
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Lift.kt
|
amarcolini
| 557,562,421
| false
|
{"Kotlin": 94873, "Java": 41907}
|
package org.firstinspires.ftc.teamcode
import com.amarcolini.joos.command.*
import com.amarcolini.joos.control.PIDCoefficients
import com.amarcolini.joos.control.PIDFController
import com.amarcolini.joos.dashboard.JoosConfig
import com.amarcolini.joos.profile.MotionProfileGenerator
import com.amarcolini.joos.profile.MotionState
import com.amarcolini.joos.util.epsilonEquals
import com.qualcomm.hardware.rev.RevTouchSensor
import com.qualcomm.robotcore.hardware.DcMotor
import com.qualcomm.robotcore.hardware.DcMotorEx
import com.qualcomm.robotcore.hardware.DcMotorSimple
import com.qualcomm.robotcore.hardware.HardwareMap
import kotlin.math.*
@JoosConfig
class Lift(hMap: HardwareMap) : AbstractComponent() {
private val ticksPerInch = 1.0
private val leftMotor = hMap.get(DcMotorEx::class.java, "left_lift")
private var leftOffset: Int = 0
private val rightMotor = hMap.get(DcMotorEx::class.java, "right_lift")
private var rightOffset: Int = 0
var positionControlEnabled = false
companion object {
var initialized = false
private set
// val coeffs = PIDCoefficients(0.006, 0.0, 0.0004)
val coeffs = PIDCoefficients(0.004)
// var kVup = 0.0007
// var kVdown = 0.0007
// var kAup = 0.0
// var kAdown = 0.0
var fallAccel = -4000.0
var slowTime = 0.4
var fallPower = 0.001
@JvmField var lowJunction = 450.0
@JvmField var mediumJunction = 700.0
@JvmField var highJunction = 1200.0
}
val positionController: PIDFController = PIDFController(coeffs)
init {
leftMotor.direction = DcMotorSimple.Direction.REVERSE
rightMotor.zeroPowerBehavior = DcMotor.ZeroPowerBehavior.BRAKE
leftMotor.zeroPowerBehavior = DcMotor.ZeroPowerBehavior.BRAKE
leftMotor.mode = DcMotor.RunMode.RUN_WITHOUT_ENCODER
rightMotor.mode = DcMotor.RunMode.RUN_WITHOUT_ENCODER
positionController.tolerance = 200.0
}
private val emergencySensor = hMap.get(RevTouchSensor::class.java, "emergency_toucher")
var currentVelocity: Double? = null
override fun update() {
if (positionControlEnabled) {
val position = getPosition()
val velocity = currentVelocity
val output = when {
velocity == null -> 0.21
velocity >= 0.0 -> velocity * 0.0006 + 0.21
velocity < 0.0 -> fallPower
else -> 0.21
} + positionController.update(position)
setPower(max(output, 0.0))
// telem.addData("lift target", positionController.targetPosition)
// .addData("lift actual", position)
// .addData("lift targetVel", currentVelocity ?: 0.0)
// .addData("lift actualVel", getVelocity())
// .addData("lift output", output)
}
}
fun setPower(power: Double) {
leftMotor.power = power
rightMotor.power = power
}
fun resetEncoders() {
leftOffset = -leftMotor.currentPosition
rightOffset = -rightMotor.currentPosition
}
fun getPosition() =
0.5 * (leftMotor.currentPosition + leftOffset + rightMotor.currentPosition + rightOffset)
fun getVelocity() = 0.5 * (leftMotor.velocity + rightMotor.velocity)
fun init(): Command = FunctionalCommand(
init = {
positionControlEnabled = false
leftMotor.zeroPowerBehavior = DcMotor.ZeroPowerBehavior.FLOAT
rightMotor.zeroPowerBehavior = DcMotor.ZeroPowerBehavior.FLOAT
setPower(fallPower)
},
execute = {
telem.addLine("resetting lift!!")
telem.addData("emergency sensor pressed", emergencySensor.isPressed)
telem.addData("motor power", leftMotor.power)
},
isFinished = { emergencySensor.isPressed },
end = {
setPower(-0.1)
initialized = true
},
isInterruptable = false,
// requirements = setOf(this)
) then WaitCommand(0.2).onEnd {
setPower(0.0)
resetEncoders()
}
fun goToPosition(position: Double, maxVel: Double = 1200.0, accel: Double = 1000.0): Command =
Command.select(this) {
val actual = getPosition()
if (position epsilonEquals actual) return@select Command.emptyCommand()
val currentVel = currentVelocity ?: getVelocity()
if (position > actual) {
val motionProfile = MotionProfileGenerator.generateSimpleMotionProfile(
MotionState(getPosition(), currentVel, accel),
MotionState(position, 0.0, accel),
maxVel,
accel + 1.0
)
TimeCommand { t, _ ->
val targetState = motionProfile[t]
telem.addData("profile duration", motionProfile.duration())
positionController.targetPosition = targetState.x
currentVelocity = targetState.v
(t > motionProfile.duration())
}.onInit {
leftMotor.zeroPowerBehavior = DcMotor.ZeroPowerBehavior.FLOAT
rightMotor.zeroPowerBehavior = DcMotor.ZeroPowerBehavior.FLOAT
positionControlEnabled = true
}.onEnd {
currentVelocity = null
if (emergencySensor.isPressed) {
positionControlEnabled = false
setPower(0.0)
}
}.setInterruptable(true).requires(this)
} else {
val root = sqrt(currentVel.pow(2) + 2 * fallAccel * (position - actual))
val fallTime = listOf(
(-currentVel + root) / fallAccel,
(-currentVel - root) / fallAccel
).filter { it >= 0 }.maxOrNull()
if (fallTime == null || fallTime < slowTime) {
val motionProfile = MotionProfileGenerator.generateSimpleMotionProfile(
MotionState(getPosition(), currentVel, accel),
MotionState(position, 0.0, accel),
200.0,
accel + 1.0
)
TimeCommand { t, _ ->
val targetState = motionProfile[t]
telem.addData("profile duration", motionProfile.duration())
telem.addData("fallTime", fallTime)
positionController.targetPosition = targetState.x
currentVelocity = targetState.v
(t > motionProfile.duration())
}.onInit {
leftMotor.zeroPowerBehavior = DcMotor.ZeroPowerBehavior.FLOAT
rightMotor.zeroPowerBehavior = DcMotor.ZeroPowerBehavior.FLOAT
positionControlEnabled = true
}.onEnd {
currentVelocity = null
if (emergencySensor.isPressed) {
positionControlEnabled = false
setPower(0.0)
}
}.setInterruptable(true).requires(this)
} else TimeCommand { t, _ ->
telem.addData("fall time", fallTime)
setPower(if (t < fallTime - slowTime) 0.0 else 0.1)
(t > fallTime || emergencySensor.isPressed)
}.onInit {
leftMotor.zeroPowerBehavior = DcMotor.ZeroPowerBehavior.FLOAT
rightMotor.zeroPowerBehavior = DcMotor.ZeroPowerBehavior.FLOAT
positionControlEnabled = false
}.onEnd {
currentVelocity = null
if (emergencySensor.isPressed) {
positionControlEnabled = false
setPower(0.0)
} else {
positionControlEnabled = true
positionController.targetPosition = position
}
}.setInterruptable(true).requires(this)
}
}
fun goToHeight(height: Double): Command = goToPosition(height * ticksPerInch)
}
| 0
|
Kotlin
|
0
| 0
|
5b6595ba7098c6d924b8a0f05812d5f225f5e21c
| 8,382
|
18421-PP
|
BSD 3-Clause Clear License
|
app-testdb/src/jsMain/kotlin/ExampleView.kt
|
UstadMobile
| 344,538,858
| false
| null |
import db2.ExampleEntity2
interface ExampleView {
var list: List<ExampleEntity2>?
var entity: ExampleEntity2
}
| 0
|
Kotlin
|
0
| 89
|
58f93d9057ece78cc3f8be3d4d235c0204a15f11
| 119
|
door
|
Apache License 2.0
|
lithic-kotlin-core/src/test/kotlin/com/lithic/api/models/TokenizationDecisioningRetrieveSecretParamsTest.kt
|
lithic-com
| 658,974,440
| false
|
{"Kotlin": 6900850, "Shell": 3630, "Dockerfile": 399}
|
// File generated from our OpenAPI spec by Stainless.
package com.lithic.api.models
import com.lithic.api.models.*
import org.junit.jupiter.api.Test
class TokenizationDecisioningRetrieveSecretParamsTest {
@Test
fun createTokenizationDecisioningRetrieveSecretParams() {
TokenizationDecisioningRetrieveSecretParams.builder().build()
}
}
| 0
|
Kotlin
|
0
| 2
|
7fd02f6dcbd597a96e4ab4ad136de7f01a12c576
| 359
|
lithic-kotlin
|
Apache License 2.0
|
common/src/commonMain/kotlin/com/artemchep/keyguard/common/usecase/CipherPlaceholder.kt
|
AChep
| 669,697,660
| false
|
{"Kotlin": 5516822, "HTML": 45876}
|
package com.artemchep.keyguard.common.usecase
import com.artemchep.keyguard.common.io.IO
import com.artemchep.keyguard.common.model.DSecret
interface CipherPlaceholder : (DSecret.Uri, String) -> IO<Boolean>
| 66
|
Kotlin
|
31
| 995
|
557bf42372ebb19007e3a8871e3f7cb8a7e50739
| 209
|
keyguard-app
|
Linux Kernel Variant of OpenIB.org license
|
src/me/anno/ui/input/NumberInput.kt
|
won21kr
| 351,713,352
| true
|
{"Kotlin": 1983578, "Java": 301507, "C": 75596, "GLSL": 9436}
|
package me.anno.ui.input
import me.anno.gpu.Cursor
import me.anno.input.MouseButton
import me.anno.objects.animation.AnimatedProperty
import me.anno.objects.animation.Type
import me.anno.ui.base.Visibility
import me.anno.ui.base.groups.PanelListY
import me.anno.ui.input.components.NumberInputComponent
import me.anno.ui.input.components.TitlePanel
import me.anno.ui.style.Style
abstract class NumberInput(
style: Style,
val title: String,
val type: Type = Type.FLOAT,
val owningProperty: AnimatedProperty<*>?,
val indexInProperty: Int
) : PanelListY(style) {
fun noTitle(): NumberInput {
titleView.hide()
inputPanel.show()
InputVisibility.show(title, null)
return this
}
var hasValue = false
val titleView = TitlePanel(title, this, style)
val inputPanel = object : NumberInputComponent(
owningProperty, indexInProperty, this@NumberInput, style
) {
override val needsSuggestions: Boolean get() = false
override var visibility: Visibility
get() = InputVisibility[title]
set(_) {}
}
override fun onDraw(x0: Int, y0: Int, x1: Int, y1: Int) {
val focused1 = titleView.isInFocus || inputPanel.isInFocus
if (focused1) isSelectedListener?.invoke()
/*if(RemsStudio.hideUnusedProperties){
val focused2 = focused1 || (owningProperty != null && owningProperty == selectedProperty)
inputPanel.visibility = if (focused2) Visibility.VISIBLE else Visibility.GONE
}*/
super.onDraw(x0, y0, x1, y1)
when (this) {
is IntInput -> updateValueMaybe()
is FloatInput -> updateValueMaybe()
else -> throw RuntimeException()
}
}
fun setPlaceholder(placeholder: String) {
inputPanel.placeholder = placeholder
}
init {
this += titleView
titleView.enableHoverColor = true
titleView.focusTextColor = titleView.textColor
titleView.setSimpleClickListener { InputVisibility.toggle(title, this) }
this += inputPanel
inputPanel.setCursorToEnd()
inputPanel.placeholder = title
inputPanel.hide()
}
var isSelectedListener: (() -> Unit)? = null
fun setIsSelectedListener(listener: () -> Unit): NumberInput {
isSelectedListener = listener
return this
}
override fun onMouseDown(x: Float, y: Float, button: MouseButton) {
super.onMouseDown(x, y, button)
mouseIsDown = true
}
var mouseIsDown = false
override fun onMouseMoved(x: Float, y: Float, dx: Float, dy: Float) {
super.onMouseMoved(x, y, dx, dy)
if (mouseIsDown) {
changeValue(dx, dy)
}
}
abstract fun changeValue(dx: Float, dy: Float)
override fun onMouseUp(x: Float, y: Float, button: MouseButton) {
super.onMouseUp(x, y, button)
mouseIsDown = false
}
override fun getCursor(): Long = Cursor.drag
}
| 0
| null |
0
| 0
|
b85295f59ddfa9fc613a384d439fd1b30b06a5a4
| 3,002
|
RemsStudio
|
Apache License 2.0
|
demo/app/src/main/java/dev/goobar/advancedandroiddemo/home/DemoNavigationDestinations.kt
|
goobar-dev
| 655,460,041
| false
| null |
package dev.goobar.advancedandroiddemo.home
import dev.goobar.advancedandroiddemo.data.AndroidVersionInfo
object DemoNavigationDestinations {
object VersionsList : NavigationDestination
object VersionDetails : ArgumentDestination<AndroidVersionInfo>
object Topics : NavigationDestination
object Notes : NavigationDestination
object AddNote : NavigationDestination
object TrendingRepos : NavigationDestination
}
| 0
|
Kotlin
|
0
| 0
|
e88c2601dbc255e14bf40ae9b7ae82bac68fbdef
| 436
|
android-403-advanced-android-kotlin
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.