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/main/java/com/battagliandrea/beerappandroid/ui/items/beer/OnBeerClickListener.kt | battagliandrea | 253,013,900 | false | null | package com.battagliandrea.beerappandroid.ui.items.beer
import android.view.View
interface OnBeerClickListener {
fun onItemClick(beerId: Long)
} | 0 | Kotlin | 0 | 0 | e2fca8b8994f4d4c7c224414e10a761933bf9e5c | 151 | BeerAppAndroid | Apache License 2.0 |
src/main/kotlin/ru/inforion/lab403/common/logging/dsl/PublisherConfig.kt | inforion | 175,940,719 | false | null | package ru.inforion.lab403.common.logging.dsl
import ru.inforion.lab403.common.logging.ALL
import ru.inforion.lab403.common.logging.LogLevel
import ru.inforion.lab403.common.logging.formatters.Formatter
import ru.inforion.lab403.common.logging.logger.Record
import ru.inforion.lab403.common.logging.permit
import ru.inforion.lab403.common.logging.publishers.AbstractPublisher
class PublisherConfig(val name: String, val level: LogLevel = ALL) : AbstractConfig<AbstractPublisher> {
/**
* Function called when publish record
*/
private var onPublish: AbstractPublisher.(message: String, record: Record) -> Unit = { _, _ -> }
/**
* Function called when flush publisher
*/
private var onFlush: AbstractPublisher.() -> Unit = {
}
private var formatterConfig: AbstractConfig<Formatter>? = null
override fun generate() = object : AbstractPublisher(name) {
private val formatter = formatterConfig?.generate()
override fun publish(message: String, record: Record) {
if (level permit record.level) {
val formatted = formatter?.format(message, record) ?: message
onPublish(formatted, record)
}
}
override fun flush() = onFlush()
}
/**
* Set the formatter of publisher, default - no formatting
*
* @param function formatter configuration
*/
fun formatter(function: FormatterConfig.() -> Unit) {
formatterConfig = FormatterConfig().also { function(it) }
}
/**
* Set the formatter of publisher, default - no formatting
*
* @param formatter formatter to set
*/
fun formatter(formatter: Formatter) {
formatterConfig = AbstractConfig { formatter }
}
/**
* Set the [AbstractPublisher.publish] method of publisher, default - nothing to be done when publish
*
* NOTE: All formatting should done in formatter (formatter called first then publish)
*
* @param function publish action
*/
fun publish(function: AbstractPublisher.(message: String, record: Record) -> Unit) = apply {
onPublish = function
}
/**
* Set the [AbstractPublisher.flush] method of publisher, default - nothing to be done when flush
*
* @param function flush action
*/
fun flush(function: AbstractPublisher.() -> Unit) = apply { onFlush = function }
} | 1 | Kotlin | 2 | 7 | 7cc7570b7ec3ace213dea13d1debbc505812f969 | 2,410 | kotlin-logging | MIT License |
plugins/evaluation-plugin/src/com/intellij/cce/EvaluationPluginBundle.kt | JetBrains | 2,489,216 | false | null | package com.intellij.cce
import com.intellij.DynamicBundle
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
@NonNls
private const val BUNDLE = "messages.EvaluationPluginBundle"
object EvaluationPluginBundle : DynamicBundle(BUNDLE) {
@Nls
fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, *params)
@JvmStatic
fun messagePointer(@PropertyKey(resourceBundle = BUNDLE) key: String,
vararg params: Any): java.util.function.Supplier<String> = getLazyMessage(key, *params)
} | 233 | null | 4912 | 15,461 | 9fdd68f908db0b6bb6e08dc33fafb26e2e4712af | 632 | intellij-community | Apache License 2.0 |
user-service/src/main/kotlin/socialapp/ktuserservice/service/impl/AddressServiceImpl.kt | youngAndMad | 737,339,214 | false | {"YAML": 24, "Maven POM": 11, "Text": 1, "Ignore List": 11, "Markdown": 1, "Dockerfile": 10, "Java": 150, "XML": 1, "SQL": 3, "Dotenv": 2, "Go Checksums": 2, "Makefile": 1, "Go Module": 2, "Go": 27, "FreeMarker": 1, "JSON": 1, "Kotlin": 49} | package socialapp.ktuserservice.service.impl
import org.springframework.stereotype.Service
import socialapp.ktuserservice.common.mapper.AddressMapper
import socialapp.ktuserservice.model.dto.AddressDto
import socialapp.ktuserservice.model.entity.Address
import socialapp.ktuserservice.repository.AddressRepository
import socialapp.ktuserservice.service.AddressService
@Service
class AddressServiceImpl(
private var addressRepository: AddressRepository,
private var addressMapper: AddressMapper
) : AddressService {
override fun save(addressDto: AddressDto): Address =
addressRepository.save(addressMapper.toModel(addressDto));
override fun update(addressDto: AddressDto,address: Address) {
addressMapper.update(address, addressDto);
addressRepository.save(address);
}
} | 0 | Java | 0 | 0 | 25e704be8ff30f5eb832922004d55d483bfbef7c | 818 | social-network | MIT License |
examples/kotlin/thirdpartydev/forwarding/src/main/kotlin/com/wgtwo/examples/thirdpartydev/forwarding/DisableCallForwarding.kt | working-group-two | 227,809,491 | false | null | package com.wgtwo.examples.thirdpartydev.forwarding
import com.wgtwo.api.v0.callforward.CallForwardingProto
import com.wgtwo.api.v0.callforward.CallForwardingServiceGrpc
import com.wgtwo.api.common.Environment
import com.wgtwo.api.v0.common.PhoneNumberProto
import com.wgtwo.api.util.auth.BearerToken
import com.wgtwo.api.util.auth.Channels
private val channel = Channels.createChannel(Environment.PRODUCTION)
private val credentials = BearerToken { "MY_ACCESS_TOKEN" } // Add your credentials
private val stub = CallForwardingServiceGrpc.newBlockingStub(channel).withCallCredentials(credentials)
fun main() {
val message = with(CallForwardingProto.DisableCallForwardingRequest.newBuilder()) {
this.subscriber = with(PhoneNumberProto.PhoneNumber.newBuilder()) {
this.e164 = "+4672xxxxxxx"
build()
}
build()
}
val result = stub.disable(message)
if (result.status == CallForwardingProto.CallForwardingResponse.Status.ACCEPTED) {
println("Successfully disabled call forwarding")
} else {
println("""
Failure to disable call forwarding:
status=${result.status}
description=${result.errorMessage}"
""".trimIndent())
}
}
| 10 | null | 4 | 1 | 6f86e68c71f24276af6890241c05df7aceb17fa8 | 1,251 | docs.wgtwo.com | Apache License 2.0 |
idea/tests/testData/kotlinAndJavaChecker/javaAgainstKotlin/Interface.kt | JetBrains | 278,369,660 | false | null | interface A {
companion object {
fun create() {}
}
} | 0 | Kotlin | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 68 | intellij-kotlin | Apache License 2.0 |
product-service/src/main/kotlin/br/com/maccommerce/productservice/domain/repository/CategoryRepository.kt | wellingtoncosta | 251,454,379 | false | {"Text": 1, "Markdown": 4, "Batchfile": 3, "Shell": 3, "Maven POM": 1, "Dockerfile": 3, "Ignore List": 3, "INI": 10, "Java": 34, "SQL": 3, "Gradle Kotlin DSL": 4, "Kotlin": 77, "XML": 2} | package br.com.maccommerce.productservice.domain.repository
import br.com.maccommerce.productservice.domain.entity.Category
interface CategoryRepository : CrudRepository<Category>
| 0 | Kotlin | 0 | 1 | f25c2157e5ffe362e405a145e4889b4e9166897d | 182 | maccommerce | MIT License |
2021/day1_SonarSweep/kotlinSolution/Part1.kt | danilmoh | 437,469,045 | false | null | package day1_SonarSweep.kotlinSolution
fun main() {
val path = "2021/day1_SonarSweep/input.txt"
val loader = Loader(path)
val list = loader.data
var prev = Int.MAX_VALUE
var cur = 0
val result = ArrayList<Int>()
list.forEach {
cur = it
if (cur > prev) {
result.add(cur)
}
prev = cur
}
print(result.size)
} | 1 | null | 1 | 1 | 1d09d432342852bfc86542078329a4724bddd818 | 390 | Advent-of-Code | MIT License |
src/core/src/test/kotlin/org/apache/jmeter/threads/openmodel/PoissonArrivalsRampTest.kt | apache | 688,352 | false | {"Java": 9181032, "Kotlin": 583722, "HTML": 93440, "XSLT": 91403, "JavaScript": 36223, "Batchfile": 25552, "Shell": 24265, "CSS": 23066, "Less": 6310, "Groovy": 1083} | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jmeter.threads.openmodel
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.MethodSource
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.Locale
import java.util.Random
class PoissonArrivalsRampTest {
class Case(
val beginRate: Double,
val endRate: Double,
val duration: Double,
val expected: String,
val seed: Long = 0L,
) {
override fun toString() = "beginRate=$beginRate, endRate=$endRate, duration=$duration, seed=$seed"
}
companion object {
@JvmStatic
fun data() = listOf(
Case(beginRate = 1.0, endRate = 1.0, duration = 1.0, "0.731"),
Case(
beginRate = 2.0, endRate = 2.0, duration = 1.0,
"""
0.2405
0.731
""".trimIndent()
),
Case(
beginRate = 0.0, endRate = 4.0, duration = 4.0,
"""
1.9618
2.309
2.4825
2.9677
3.092
3.1935
3.4199
3.9696
""".trimIndent()
),
Case(
beginRate = 5.0, endRate = 1.0, duration = 4.0,
"""
0.0304
0.1193
0.2494
0.908
0.9621
1.5175
1.691
1.9026
2.2017
2.5497
2.5639
2.9239
""".trimIndent()
),
Case(
beginRate = 1.0, endRate = 5.0, duration = 4.0,
"""
0.9621
1.4361
2.0974
2.2017
2.309
2.4825
2.5497
2.9239
3.092
3.7506
3.8807
3.9696
""".trimIndent()
),
Case(
beginRate = 1.0, endRate = 5.0, duration = 4.0, seed = 1L,
expected = """
0.3128
0.8309
1.3309
1.6403
2.358
2.5209
2.9235
3.8721
3.8779
3.893
3.9267
3.935
""".trimIndent()
),
)
}
@ParameterizedTest
@MethodSource("data")
fun test(case: Case) {
val gen = PoissonArrivalsRamp()
gen.prepare(beginRate = case.beginRate, endRate = case.endRate, duration = case.duration, random = Random(case.seed))
val format = DecimalFormat("#.####", DecimalFormatSymbols.getInstance(Locale.ROOT))
assertEquals(
case.expected,
gen.asSequence().joinToString("\n") { format.format(it) },
case.toString()
)
}
}
| 876 | Java | 2095 | 8,357 | 872112bf5d08d2f698f765b3c950b2898ec23e98 | 3,921 | jmeter | Apache License 2.0 |
src/main/kotlin/me/chill/authentication/SpotifyAuthenticationComponent.kt | woojiahao | 152,174,553 | false | {"Maven POM": 1, "Markdown": 7, "Text": 1, "Ignore List": 1, "Kotlin": 130, "Java": 18, "HTML": 1} | package me.chill.authentication
enum class SpotifyAuthenticationComponent { AccessToken, RefreshToken, ExpiryDuration } | 1 | Kotlin | 0 | 1 | 6dbb0aecdbba94153455be32b79f60e156641d21 | 120 | java-spotify-wrapper | MIT License |
airbyte-cdk/java/airbyte-cdk/s3-destinations/src/main/kotlin/io/airbyte/cdk/integrations/destination/s3/parquet/ParquetConstants.kt | tim-werner | 511,419,970 | false | {"Java Properties": 8, "Shell": 57, "Markdown": 1170, "Batchfile": 1, "Makefile": 3, "JavaScript": 31, "CSS": 9, "Python": 4183, "Kotlin": 845, "Java": 723, "INI": 10, "Dockerfile": 27, "HTML": 7, "SQL": 527, "PLpgSQL": 8, "TSQL": 1, "PLSQL": 2} | /*
* Copyright (c) 2024 Airbyte, Inc., all rights reserved.
*/
package io.airbyte.cdk.integrations.destination.s3.parquet
import org.apache.parquet.hadoop.metadata.CompressionCodecName
class ParquetConstants {
companion object {
val DEFAULT_COMPRESSION_CODEC: CompressionCodecName = CompressionCodecName.UNCOMPRESSED
const val DEFAULT_BLOCK_SIZE_MB: Int = 128
const val DEFAULT_MAX_PADDING_SIZE_MB: Int = 8
const val DEFAULT_PAGE_SIZE_KB: Int = 1024
const val DEFAULT_DICTIONARY_PAGE_SIZE_KB: Int = 1024
const val DEFAULT_DICTIONARY_ENCODING: Boolean = true
}
}
| 1 | null | 1 | 1 | b2e7895ed3e1ca7c1600ae1c23578dd1024f20ff | 624 | airbyte | MIT License |
app/src/main/java/ru/ischenko/roman/focustimer/FocusTimerApplication.kt | djamba | 111,814,090 | false | null | package ru.ischenko.roman.focustimer
import dagger.android.AndroidInjector
import dagger.android.support.DaggerApplication
import ru.ischenko.roman.focustimer.data.datasource.local.FocusTimerDatabase
import ru.ischenko.roman.focustimer.di.DaggerAppComponent
import timber.log.Timber
/**
* User: roman
* Date: 07.04.19
* Time: 20:04
*/
class FocusTimerApplication : DaggerApplication() {
lateinit var focusTimerDatabase: FocusTimerDatabase
override fun onCreate() {
super.onCreate()
// TODO: Настроить для релиза
Timber.plant(Timber.DebugTree())
focusTimerDatabase = FocusTimerDatabase.buildDatabase(this)
}
override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
return DaggerAppComponent.builder().create(this)
}
} | 1 | null | 1 | 2 | 48569bb7fbd3be529a8b537e394f2774975c713a | 807 | FocusTimer | MIT License |
app/src/main/java/xyz/thingapps/rssliveslider/activities/ItemDetailActivity.kt | ahndwon | 195,956,450 | false | null | package xyz.thingapps.rssliveslider.activities
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.jakewharton.rxbinding3.view.clicks
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
import kotlinx.android.synthetic.main.activity_item_detail.*
import xyz.thingapps.rssliveslider.R
import xyz.thingapps.rssliveslider.activities.WebViewActivity.Companion.ITEM_URL
import xyz.thingapps.rssliveslider.models.Item
import java.util.concurrent.TimeUnit
class ItemDetailActivity : AppCompatActivity() {
companion object {
const val RSS_ITEM = "rss_item"
const val WINDOW_DURATION = 600L
}
private val disposeBag = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_item_detail)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.title = getString(R.string.feed)
val item: Item? = intent.getParcelableExtra<Item>(RSS_ITEM) ?: return
titleTextView.text = item?.title
itemInfoTextView.text = item?.pubDate
descriptionTextView.text = item?.description
item?.media?.let {
if (it.type.contains("image")) {
Glide.with(itemImageView)
.load(it.url)
.into(itemImageView)
}
}
visitButton.clicks().throttleFirst(WINDOW_DURATION, TimeUnit.MILLISECONDS)
.subscribe({
item?.let {
val intent = Intent(this, WebViewActivity::class.java)
intent.putExtra(ITEM_URL, item.link)
startActivity(intent)
}
}, { e ->
e.printStackTrace()
}).addTo(disposeBag)
shareButton.clicks().throttleFirst(WINDOW_DURATION, TimeUnit.MILLISECONDS)
.subscribe({
item?.let {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "text/plain"
intent.putExtra(Intent.EXTRA_SUBJECT, item.title)
intent.putExtra(Intent.EXTRA_TEXT, "Check this out - ${item.link}")
startActivity(Intent.createChooser(intent, "Share via"))
}
}, { e ->
e.printStackTrace()
}).addTo(disposeBag)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
onBackPressed()
}
}
return super.onOptionsItemSelected(item)
}
override fun onDestroy() {
disposeBag.dispose()
super.onDestroy()
}
}
| 1 | Kotlin | 1 | 16 | 607dcf35897a6452a438afd8ba26c46eee7f137a | 2,916 | RssLiveSlider | Apache License 2.0 |
kotlin/problems/src/solution/TreeProblems.kt | lunabox | 86,097,633 | false | null | package solution
import data.structure.TreeNode
import java.util.*
import java.util.concurrent.ArrayBlockingQueue
import kotlin.collections.ArrayList
import kotlin.collections.HashMap
import kotlin.math.max
import kotlin.math.min
class TreeProblems {
/**
* 由数组创建二叉树
*/
fun createTree(element: List<Int?>): TreeNode? {
if (element.isEmpty()) {
return null
}
return createNode(element, 0)
}
private fun createNode(element: List<Int?>, index: Int): TreeNode? {
if (index >= 0 && index < element.size && element[index] != null) {
val root = TreeNode(element[index]!!)
root.left = createNode(element, index * 2 + 1)
root.right = createNode(element, index * 2 + 2)
return root
}
return null
}
fun printTree(root: TreeNode?) {
val queue = ArrayBlockingQueue<TreeNode?>(20)
queue.add(root)
while (queue.isNotEmpty()) {
val node = queue.poll()
if (node != null) {
println("${node.`val`} ")
if (node.left != null) {
queue.add(node.left)
}
if (node.right != null) {
queue.add(node.right)
}
}
}
}
/**
* https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/
* 给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
*/
fun levelOrderBottom(root: TreeNode?): List<List<Int>> {
val result = ArrayList<List<Int>>()
if (root == null) {
return result
}
val queue = LinkedList<TreeNode>()
queue.add(root)
while (queue.isNotEmpty()) {
val list = ArrayList<Int>()
repeat(queue.size) {
val s = queue.removeFirst()
list.add(s.`val`)
// add child tree node
if (s.left != null) {
queue.addLast(s.left)
}
if (s.right != null) {
queue.addLast(s.right)
}
}
result.add(0, list)
}
return result
}
/**
*
*/
fun averageOfLevels(root: TreeNode?): DoubleArray {
val result = ArrayList<Double>()
if (root == null) {
return result.toDoubleArray()
}
val queue = LinkedList<TreeNode>()
queue.add(root)
while (queue.isNotEmpty()) {
var sum: Long = 0
val count = queue.size
repeat(count) {
val node = queue.removeFirst()
sum += node.`val`
if (node.left != null) {
queue.addLast(node.left)
}
if (node.right != null) {
queue.addLast(node.right)
}
}
result.add(sum / count.toDouble())
}
return result.toDoubleArray()
}
/**
* https://leetcode-cn.com/problems/binary-tree-level-order-traversal/
* 给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)
*/
fun levelOrder(root: TreeNode?): List<List<Int>> {
val result = ArrayList<List<Int>>()
if (root == null) {
return result
}
val queue = LinkedList<TreeNode>()
queue.add(root)
while (queue.isNotEmpty()) {
val list = ArrayList<Int>()
repeat(queue.size) {
val s = queue.removeFirst()
list.add(s.`val`)
// add child tree node
if (s.left != null) {
queue.addLast(s.left)
}
if (s.right != null) {
queue.addLast(s.right)
}
}
result.add(list)
}
return result
}
private var xpar = 0
private var ypar = 0
private var xdep = 0
private var ydep = 0
/**
* https://leetcode-cn.com/problems/cousins-in-binary-tree/
*/
fun isCousins(root: TreeNode?, x: Int, y: Int): Boolean {
if (root == null) {
return false
}
dfs(root.left, 1, x, y, root.`val`)
dfs(root.right, 1, x, y, root.`val`)
return xdep == ydep && xpar != ypar
}
private fun dfs(node: TreeNode?, dep: Int, x: Int, y: Int, par: Int) {
if (node == null) {
return
}
if (node.`val` == x) {
xdep = dep
xpar = par
}
if (node.`val` == y) {
ydep = dep
ypar = par
}
dfs(node.left, dep + 1, x, y, node.`val`)
dfs(node.right, dep + 1, x, y, node.`val`)
}
/**
* https://leetcode-cn.com/problems/convert-sorted-array-to-binary-search-tree/
*/
fun sortedArrayToBST(nums: IntArray): TreeNode? {
return null
}
/**
* https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
* 给定一个二叉树,返回它的 前序 遍历,使用迭代法
*/
fun preorderTraversal(root: TreeNode?): List<Int> {
val list = ArrayList<Int>()
if (root == null) {
return list
}
val stack = LinkedList<TreeNode>()
stack.addFirst(root)
while (stack.isNotEmpty()) {
val node = stack.pollFirst()
list.add(node.`val`)
if (node.right != null) {
stack.addFirst(node.right)
}
if (node.left != null) {
stack.addFirst(node.left)
}
}
return list
}
/**
* https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
* 迭代法,中序遍历
*/
fun inorderTraversal(root: TreeNode?): List<Int> {
if (root == null) {
return emptyList()
}
val list = ArrayList<Int>()
val stack = LinkedList<TreeNode>()
var p: TreeNode? = root
while (p != null || stack.isNotEmpty()) {
while (p != null) {
stack.addFirst(p)
p = p.left
}
val n = stack.pollFirst()
list.add(n.`val`)
p = n.right
}
return list
}
/**
* https://leetcode-cn.com/problems/binary-tree-postorder-traversal/
* 迭代法的后续遍历
*/
fun postorderTraversal(root: TreeNode?): List<Int> {
if (root == null) {
return emptyList()
}
val result = ArrayList<Int>()
val stack = LinkedList<TreeNode>()
stack.addFirst(root)
while (stack.isNotEmpty()) {
val node = stack.pollFirst()
result.add(0, node.`val`)
node.left?.let {
stack.addFirst(it)
}
node.right?.let {
stack.addFirst(it)
}
}
return result
}
/**
* https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes/
*/
fun minDiffInBST(root: TreeNode?): Int {
var last = Int.MAX_VALUE
var minValue = Int.MAX_VALUE
val stack = LinkedList<TreeNode>()
var p: TreeNode? = root
while (p != null || stack.isNotEmpty()) {
while (p != null) {
stack.addFirst(p)
p = p.left
}
val n = stack.pollFirst()
if (last != Int.MAX_VALUE) {
minValue = min(minValue, n.`val` - last)
}
last = n.`val`
p = n.right
}
return minValue
}
var preNode: TreeNode? = null
var minValue = Int.MAX_VALUE
/**
* 递归实现
*/
fun minDiffInBSTStack(root: TreeNode?): Int {
dfs(root)
return minValue
}
private fun dfs(root: TreeNode?) {
root?.let {
dfs(it.left)
if (preNode != null) {
minValue = min(minValue, it.`val` - preNode!!.`val`)
}
preNode = root
dfs(it.right)
}
}
var last = Long.MIN_VALUE
/**
* https://leetcode-cn.com/problems/validate-binary-search-tree/
*/
fun isValidBST(root: TreeNode?): Boolean {
if (root == null) {
return true
}
if (isValidBST(root.left)) {
if (root.`val` > last) {
last = root.`val`.toLong()
return isValidBST(root.right)
}
}
return false
}
/**
* https://leetcode-cn.com/problems/find-mode-in-binary-search-tree/
* 给定一个有相同值的二叉搜索树(BST),找出 BST 中的所有众数(出现频率最高的元素)
*/
fun findMode(root: TreeNode?): IntArray {
val map = HashMap<Int, Int>()
val result = ArrayList<Int>()
val stack = LinkedList<TreeNode>()
var p = root
while (p != null || stack.isNotEmpty()) {
while (p != null) {
stack.addFirst(p)
p = p.left
}
val node = stack.pollFirst()
map[node.`val`] = if (node.`val` in map.keys) map[node.`val`]!! + 1 else 1
p = node.right
}
val maxCount = map.values.max()
map.forEach { (t, u) ->
if (u == maxCount) {
result.add(t)
}
}
return result.toIntArray()
}
/**
* https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/
*/
fun kthSmallest(root: TreeNode?, k: Int): Int {
val stack = LinkedList<TreeNode>()
var p = root
var count = 0
while (p != null || stack.isNotEmpty()) {
while (p != null) {
stack.addFirst(p)
p = p.left
}
val node = stack.pollFirst()
if (++count == k) {
return node.`val`
}
p = node.right
}
return 0
}
/**
* https://leetcode-cn.com/problems/second-minimum-node-in-a-binary-tree/
*/
fun findSecondMinimumValue(root: TreeNode?): Int {
return search(root, root!!.`val`)
}
private fun search(root: TreeNode?, value: Int): Int {
if (root == null) {
return -1
}
if (root.`val` > value) {
return root.`val`
}
val left = search(root.left, value)
val right = search(root.right, value)
if (left > value && right > value) {
return min(left, right)
}
return max(left, right)
}
} | 1 | null | 1 | 1 | cbb2e3ad8f2d05d7cc54a865265561a0e391a9b9 | 10,518 | leetcode | Apache License 2.0 |
idea-plugin/src/main/kotlin/com/chutneytesting/idea/completion/PathExpression.kt | owerfelli | 791,217,559 | true | {"Markdown": 64, "Batchfile": 2, "Shell": 2, "Gradle Kotlin DSL": 6, "INI": 5, "Java": 984, "HTML": 64, "JavaScript": 6, "Kotlin": 241, "SQL": 4, "Java Properties": 1, "Dockerfile": 3, "CSS": 1, "TypeScript": 250} | package com.chutneytesting.idea.completion
import java.util.*
import java.util.stream.Collectors
class PathExpression internal constructor(val path: String) {
val currentPath: String
get() = splitPath()[0]
private fun splitPath(): Array<String> {
return path.split("(?<!\\\\)\\.").toTypedArray()
}
fun afterFirst(): PathExpression {
val parts = splitPath()
val afterFirst = Arrays.stream(parts)
.skip(1)
.collect(Collectors.joining(SEPARATOR))
return PathExpression(afterFirst)
}
fun beforeLast(): PathExpression {
val parts = splitPath()
val beforeLast = Arrays.stream(parts)
.limit(if (parts.size == 1) 1 else parts.size - 1.toLong())
.collect(Collectors.joining(SEPARATOR))
return PathExpression(beforeLast)
}
val isEmpty: Boolean
get() = path.isEmpty()
fun last(): String {
val paths = splitPath()
return paths[paths.size - 1]
}
fun secondLast(): String {
val paths = splitPath()
return paths[paths.size - 2]
}
fun hasOnePath(): Boolean {
return splitPath().size == 1
}
val isRoot: Boolean
get() = "$" == path
val isAnyKey: Boolean
get() = ANY_KEY == last()
val isAnyKeys: Boolean
get() = ANY_KEYS == last()
companion object {
private const val ANY_KEY = "*"
private const val ANY_KEYS = "**"
private const val SEPARATOR = "."
}
}
| 0 | null | 0 | 0 | a7b0bf69921fd29f846763ba4e67e271dbfaad13 | 1,533 | chutney | Apache License 2.0 |
play-default-fallback/src/main/kotlin/org/example/df/demos/parents/AOPKotlinParentForKotlin.kt | dowenliu-xyz | 808,693,582 | false | {"Gradle Kotlin DSL": 13, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 2, "Java": 399, "YAML": 4, "INI": 6, "Kotlin": 354, "Java Properties": 1} | package org.example.df.demos.parents
import com.alibaba.csp.sentinel.annotation.SentinelResource
import org.example.df.biz.Greeting.doGreeting
/**
* case: Annotated Overridden Parent
* <br/>
* Aspect DOES NOT take effect, fallback does not take effect. Because method is overridden.
*/
open class AOPKotlinParentForKotlin {
@SentinelResource(value = "demo", defaultFallback = "defaultFallback")
open fun greeting(name: String?): String {
return doGreeting(name)
}
}
| 0 | Java | 0 | 1 | 8b6df6f693a0c7efa25c3a7d634823d7b8ec4915 | 492 | sentinel-plays | Apache License 2.0 |
util/src/main/java/at/rmbt/util/exception/NoConnectionException.kt | rtr-nettest | 195,193,208 | false | null | /*
* 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 at.rmbt.util.exception
/**
* An error that signals while no internet connection is available
*/
open class NoConnectionException : HandledException("Unable to connect with server. Please, check your internet connection.")
/**
* An error that signals that connection timeout exception was received
*/
class ConnectionTimeoutException : NoConnectionException() | 1 | Kotlin | 10 | 6 | 9307935101842439eb1428691675caaa3827729b | 931 | open-rmbt-android | Apache License 2.0 |
compiler/testData/diagnostics/tests/inference/pcla/issues/kt64066.fir.kt | JetBrains | 3,432,266 | false | null | // WITH_STDLIB
// ISSUE: KT-64066
fun box() {
val map = buildMap {
put(1, 1)
for (v in values) {}
}
}
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 127 | kotlin | Apache License 2.0 |
android-test-framework/testSrc/com/android/tools/idea/testing/MergedManifests.kt | JetBrains | 60,701,247 | false | {"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19} | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.testing
import com.android.tools.idea.model.MergedManifestManager
import com.intellij.openapi.command.WriteCommandAction.runWriteCommandAction
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.runInEdtAndWait
import org.jetbrains.android.dom.manifest.Manifest
import org.jetbrains.android.facet.AndroidFacet
/**
* Applies [writeCommandActionBody] to the primary manifest of the given [androidFacet],
* and then forces and blocks on a refresh of the [androidFacet]'s merged manifest.
*/
inline fun updatePrimaryManifest(androidFacet: AndroidFacet, crossinline writeCommandActionBody: Manifest.() -> Unit) {
runWriteCommandAction(androidFacet.module.project) {
Manifest.getMainManifest(androidFacet)!!.writeCommandActionBody()
}
FileDocumentManager.getInstance().saveAllDocuments()
MergedManifestManager.getMergedManifest(androidFacet.module).get()
runInEdtAndWait {
PlatformTestUtil.dispatchAllEventsInIdeEventQueue()
}
} | 5 | Kotlin | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 1,690 | android | Apache License 2.0 |
domain/src/main/java/com.ihorvitruk.telegramclient.domain/interactor/NetworkInteractor.kt | ihorvitruk | 116,034,141 | false | null | package com.ihorvitruk.telegramclient.domain.interactor
import com.ihorvitruk.telegramclient.domain.repository.INetworkRepository
import javax.inject.Inject
class NetworkInteractor @Inject constructor(private val networkRepository: INetworkRepository) {
fun checkNetworkConnection() = networkRepository.checkNetworkConnection()
} | 0 | Java | 10 | 26 | 0e80cc5706ef6921b2594d5de25f9ea8a04f406b | 336 | Telegram-Client | Apache License 2.0 |
domain/src/main/java/com.ihorvitruk.telegramclient.domain/interactor/NetworkInteractor.kt | ihorvitruk | 116,034,141 | false | null | package com.ihorvitruk.telegramclient.domain.interactor
import com.ihorvitruk.telegramclient.domain.repository.INetworkRepository
import javax.inject.Inject
class NetworkInteractor @Inject constructor(private val networkRepository: INetworkRepository) {
fun checkNetworkConnection() = networkRepository.checkNetworkConnection()
} | 0 | Java | 10 | 26 | 0e80cc5706ef6921b2594d5de25f9ea8a04f406b | 336 | Telegram-Client | Apache License 2.0 |
app/src/main/java/com/androidbolts/locationmanager/base/BaseActivity.kt | nawinkhatiwada | 216,338,736 | false | null | package com.androidbolts.locationmanager.base
import android.location.Location
import androidx.appcompat.app.AppCompatActivity
import com.androidbolts.library.LocationListener
import com.androidbolts.library.LocationManager
import com.androidbolts.library.utils.LocationConstants
abstract class BaseActivity : AppCompatActivity(), LocationListener {
private var locationManager: LocationManager? = null
fun initLocationManager(): LocationManager? {
locationManager = LocationManager.Builder(applicationContext)
.showLoading(true)
.setActivity(this)
.setListener(this)
.setRequestTimeOut(LocationConstants.TIME_OUT_LONG)
.build()
return locationManager
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == LocationConstants.LOCATION_PERMISSIONS_REQUEST_CODE) {
locationManager?.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
}
override fun onPermissionGranted(alreadyHadPermission: Boolean) {
//override if needed
}
override fun onPermissionDenied() {
//override if needed
}
override fun onLocationChanged(location: Location?) {
}
} | 1 | Kotlin | 1 | 3 | 8494456aab6331d6ae7df6ed1c46bbb05d20869e | 1,419 | LocationManager | Apache License 2.0 |
base/src/main/java/com/cyberflow/base/model/IMUserInfo.kt | sparkle-technologies | 678,261,271 | false | {"Java": 2622804, "Kotlin": 426072} | package com.cyberflow.base.model
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.serialization.Serializable
// for interact with IM
@Serializable
data class IMUserInfoList(
var user_info_list: List<IMUserInfo>? = null
)
@Serializable
data class IMUserSearchList(var total: Int = 0, var list: List<IMSearchData>? = null)
data class IMMyFriendsList(var total: Int = 0, var list: List<IMSearchData>? = null)
data class IMSearchFriendHead(var name: String = "", var type: Int = 0, var showMore: Boolean = false)
const val TYPE_MY_FRIENDS = 0
const val TYPE_ADD_FRIENDS = 1
@Serializable
@Entity(tableName = "im_user_info_cache")
data class IMUserInfo(
@PrimaryKey var open_uid: String,
var gender: Int = 0, // 1=man 2=women
var nick: String = "",
var avatar: String = "",
var wallet_address: String = "",
var ca_wallet: String = "",
var signature: String = "",
var feed_avatar: String = "",
var feed_card_color: String = "",
)
@Serializable
data class IMSearchData(
var nick: String = "",
var gender: Int = 0, // 1=man 2=women
var avatar: String = "",
var ca_wallet: String = "",
var open_uid: String = "",
var wallet_address: String = ""
) : java.io.Serializable | 1 | null | 1 | 1 | dfb48c9312186d3ccd47702c18f175bd0e620a87 | 1,261 | Sparkle-Android-V2 | MIT License |
falkon-dao/src/main/kotlin/com/jayrave/falkon/dao/insertOrReplace/InsertOrReplaceBuilder.kt | jayrave | 65,279,209 | false | null | package com.jayrave.falkon.dao.insertOrReplace
import com.jayrave.falkon.engine.CompiledStatement
import com.jayrave.falkon.mapper.Column
import com.jayrave.falkon.mapper.Table
interface InsertOrReplaceBuilder<T : Any> {
val table: Table<T, *>
/**
* Sets the values to be inserted or replaced with for columns. Behaviour on calling
* this method multiple times is implementation dependent
*/
fun values(setter: InnerSetter<T>.() -> Any?): Ender
}
interface Ender {
/**
* *Note:* Look at implementation for how this works. The behavior may differ from one
* database to another
*
* @return [InsertOrReplace] for this builder
*/
fun build(): InsertOrReplace
/**
* *Note:* Look at implementation for how this works. The behavior may differ from one
* database to another
*
* @return [CompiledStatement] for this builder
*/
fun compile(): CompiledStatement<Int>
/**
* *Note:* Look at implementation for how this works. The behavior may differ from one
* database to another
*
* Inserts or replaces record represented by this builder
*/
fun insertOrReplace()
}
interface InnerSetter<T : Any> {
/**
* Sets the value a column should have after insert or replace. This method can be called
* multiple times to set values for multiple columns. Behaviour on calling this method
* again for a column that has already been set is implementation dependent
*/
fun <C> set(column: Column<T, C>, value: C)
} | 6 | Kotlin | 2 | 12 | ce42d553c578cd8e509bbfd7effc5d56bf3cdedd | 1,557 | falkon | Apache License 2.0 |
src/main/kotlin/net/cardosi/geneticalgorithm/features/AbstractFeature.kt | gitgabrio | 336,237,856 | true | {"Kotlin": 15536, "Java": 302} | package net.cardosi.geneticalgorithm.features
abstract class AbstractFeature {
abstract fun isOne(): Boolean
override fun toString(): String {
return "${this.javaClass.simpleName}: $featureVal"
}
protected lateinit var featureVal :Any
} | 0 | Kotlin | 0 | 0 | 312cba1703f9c5f8978fc8e171b22d2a1a90d6b9 | 266 | GeneticAlgorithm | Apache License 2.0 |
subprojects/internal/src/commonMain/kotlin/Annotations.kt | kotools | 581,475,148 | false | {"Kotlin": 186769, "Shell": 6198, "Java": 1315} | /*
* Copyright 2023 Kotools S.A.S.U.
* Use of this source code is governed by the MIT license.
*/
package kotools.types.internal
/**
* Specifies the first [version] of Kotools Types where a declaration has
* appeared as an **experimental** feature.
*
* The [version] should be in the following formats: `<major>.<minor>` or
* `<major>.<minor>.<patch>`, where _major_, _minor_ and _patch_ are positive
* integers without leading zeros.
*/
@Retention(AnnotationRetention.SOURCE)
@Target(
AnnotationTarget.CLASS,
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY,
AnnotationTarget.TYPEALIAS
)
public annotation class ExperimentalSince(val version: KotoolsTypesVersion)
/**
* Specifies the first [version] of Kotools Types where a declaration has
* appeared as a **stable** feature.
*
* The [version] should be in the following formats: `<major>.<minor>` or
* `<major>.<minor>.<patch>`, where _major_, _minor_ and _patch_ are positive
* integers without leading zeros.
*/
@Retention(AnnotationRetention.SOURCE)
@Target(
AnnotationTarget.CLASS,
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY,
AnnotationTarget.TYPEALIAS
)
public annotation class Since(val version: KotoolsTypesVersion)
| 55 | Kotlin | 4 | 37 | dd027b9aa111f78d3a2c9e2861d9db8050689cdc | 1,242 | types | MIT License |
src/test/kotlin/unit/org/kollektions/examples/consumers/SumExample.kt | AlexCue987 | 203,469,269 | false | null | package org.kollektions.examples.consumers
import org.kollektions.consumers.consume
import org.kollektions.consumers.sumOfInt
import org.kollektions.consumers.toSumOfBigDecimal
import org.kollektions.consumers.toSumOfLong
import org.kollektions.transformations.mapTo
import java.math.BigDecimal
import kotlin.test.assertEquals
import kotlin.test.Test
class SumExample {
@Test
fun `handles several items`() {
val actual = listOf(1, 2).consume(
sumOfInt(),
mapTo { it:Int -> it.toLong() }.toSumOfLong(),
mapTo { it:Int -> BigDecimal.valueOf(it.toLong()) }.toSumOfBigDecimal())
assertEquals(listOf(3, 3L, BigDecimal.valueOf(3L)), actual)
}
}
| 0 | Kotlin | 1 | 21 | 126470f2126b3211bd70e8f167bd20e0f87088d9 | 706 | konsumers | Apache License 2.0 |
app/src/main/java/com/example/mydomain/geoithub/ui/main/MainViewModelFactory.kt | gsalinaslopez | 330,532,816 | false | null | package com.example.mydomain.geoithub.ui.main
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
class MainViewModelFactory(
private val url: String
): ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return super.create(modelClass)
}
} | 0 | Kotlin | 0 | 2 | bbaa43a97e4f1e9e72f36fcd0eee94e239d36eb3 | 355 | GeoitHub | MIT License |
app/src/main/java/com/example/mydomain/geoithub/ui/main/MainViewModelFactory.kt | gsalinaslopez | 330,532,816 | false | null | package com.example.mydomain.geoithub.ui.main
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
class MainViewModelFactory(
private val url: String
): ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return super.create(modelClass)
}
} | 0 | Kotlin | 0 | 2 | bbaa43a97e4f1e9e72f36fcd0eee94e239d36eb3 | 355 | GeoitHub | MIT License |
src/main/kotlin/no/nav/personbruker/dittnav/brukernotifikasjonbestiller/common/kafka/RecordKeyValueWrapper.kt | navikt | 331,545,066 | false | null | package no.nav.personbruker.dittnav.brukernotifikasjonbestiller.common.kafka
data class RecordKeyValueWrapper <K, V> (
val key: K,
val value: V
)
| 1 | Kotlin | 0 | 0 | 9df0ace75939834947d531a342f9153d9ad44633 | 163 | dittnav-brukernotifikasjonbestiller | MIT License |
app/src/main/java/br/com/connectattoo/adapter/TagBasedTattoosViewHolder.kt | connectattoo | 601,818,127 | false | {"Kotlin": 135467, "Shell": 88, "JavaScript": 67} | package br.com.connectattoo.adapter
import android.graphics.Color
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import br.com.connectattoo.R
import br.com.connectattoo.data.ListOfTattoosBasedOnTagsAndItemMore
import br.com.connectattoo.data.TagHomeScreen
import br.com.connectattoo.databinding.ItemMoreHomeScreenBinding
import br.com.connectattoo.databinding.TagbasedtattoosItemBinding
import com.bumptech.glide.Glide
sealed class TagBasedTattoosViewHolder(binding: ViewBinding) :
RecyclerView.ViewHolder(binding.root) {
class TagViewHolder(
private val binding: TagbasedtattoosItemBinding,
) : TagBasedTattoosViewHolder(binding) {
fun bind(tagBasedTattoos: ListOfTattoosBasedOnTagsAndItemMore.TagBasedOfTattoos) {
binding.run {
cardTagBasedTattoos.setOnClickListener {
}
Glide.with(imageTattoo).load(tagBasedTattoos.imageTattoo).into(imageTattoo)
setStyleTags(this, tagBasedTattoos)
}
}
private fun setStyleTags(
binding: TagbasedtattoosItemBinding,
tagBasedTattoos: ListOfTattoosBasedOnTagsAndItemMore.TagBasedOfTattoos
) {
val colorPurple900 = "#460d7d"
binding.run {
tagBasedTattoos.tagHomeScreens?.forEach { tag ->
setStyle(tag, colorPurple900)
}
}
}
private fun TagbasedtattoosItemBinding.setStyle(
tag: TagHomeScreen,
colorPurple900: String
) {
if (tag.id == 1) {
tag1.visibility = View.VISIBLE
tag1.text = tag.title
if (tag.backgroundDeepPurple) {
tag1.setBackgroundResource(
R.drawable.bg_tag_home_circular_purple100
)
tag1.setTextColor(Color.parseColor(colorPurple900))
tag1.visibility = View.VISIBLE
}
}
if (tag.id == 2) {
tag2.visibility = View.VISIBLE
tag2.text = tag.title
if (tag.backgroundDeepPurple) {
tag2.setBackgroundResource(
R.drawable.bg_tag_home_circular_purple100
)
tag2.setTextColor(Color.parseColor(colorPurple900))
}
}
if (tag.id == 3) {
tag3.visibility = View.VISIBLE
tag3.text = tag.title
if (tag.backgroundDeepPurple) {
tag3.setBackgroundResource(
R.drawable.bg_tag_home_circular_purple100
)
tag3.setTextColor(Color.parseColor(colorPurple900))
}
}
if (tag.id == 4) {
tag4.visibility = View.VISIBLE
tag4.text = tag.title
if (tag.backgroundDeepPurple) {
tag4.setBackgroundResource(
R.drawable.bg_tag_home_circular_purple100
)
tag4.setTextColor(Color.parseColor(colorPurple900))
}
}
}
}
class MoreItemsIcon(
private val binding: ItemMoreHomeScreenBinding
) : TagBasedTattoosViewHolder(binding) {
fun bind(moreItems: ListOfTattoosBasedOnTagsAndItemMore.MoreItems) {
binding.run {
cardMoraItems.setOnClickListener {
}
txtMoreItensList.text = moreItems.title
}
}
}
}
| 1 | Kotlin | 3 | 0 | ddf2a4370ad51c26fd1920a3afb648fc83460ecd | 3,703 | connectattoo.android | MIT License |
katarina-batch/src/main/kotlin/com/hubtwork/job/util/JpaListItemWriter.kt | hubtwork | 329,160,876 | false | null | package com.hubtwork.katarina.batchmatch.batch.util
import org.springframework.batch.item.database.JpaItemWriter
class JpaListItemWriter<T>(
jpaItemWriter: JpaItemWriter<T>
)
: JpaItemWriter<List<T>>()
{
private val writer = jpaItemWriter
override fun write(items: MutableList<out List<T>>) {
// LOGIC
// 리스트 아이템을 모두 Processor 로 부터 전달 받은 후 "중복제거" 후 병합하여 Writing
var allItems = mutableSetOf<T>()
items.forEach { allItems.addAll(it) }
writer.write(allItems.toList())
}
} | 2 | Kotlin | 0 | 0 | 8767c3c49cf278e4cdc5c6cf9ba3a280a48c0bd7 | 531 | Katarina | MIT License |
src/main/kotlin/de/debuglevel/evasysmiddleware/survey/Survey.kt | debuglevel | 369,594,700 | false | null | package de.debuglevel.evasysmiddleware.survey
import de.debuglevel.evasysmiddleware.period.Period
import java.time.LocalDate
data class Survey(
private val id: Int,
private val state: Int,
private val title: String,
private val type: String,
private val formId: Int,
private val studentId: Int,
private val verId: Int,
private val openState: Int,
private val formCount: Int,
private val pswdCount: Int,
private val lastDataCollectionDate: LocalDate,
private val pageLinkOffset: Int,
private val maskTan: String,
private val maskState: Int,
private val period: Period,
) | 0 | Kotlin | 0 | 0 | a077025f68dc4d672fa0dc132af8ac1640ab326f | 631 | evasys-middleware | The Unlicense |
app/src/main/java/com/cube/foodtoseeyou/entity/Recipe.kt | kodeflap | 465,057,014 | false | {"Kotlin": 30575} | package com.cube.foodtoseeyou.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.io.Serializable
@Entity(tableName = "Recipes")
data class Recipe(
@PrimaryKey(autoGenerate = true)
var id : Int,
@ColumnInfo(name = "dishName")
var dishName:String
):Serializable | 0 | Kotlin | 0 | 0 | a63ab51c002cef6dbed8162c1d03898099ee3de6 | 338 | Food_to_see_you | MIT License |
cottontaildb-dbms/src/main/kotlin/org/vitrivr/cottontail/storage/serializers/values/FloatVectorValueValueSerializer.kt | vitrivr | 160,775,368 | false | {"Kotlin": 2769182, "TypeScript": 98011, "Java": 97672, "HTML": 38965, "ANTLR": 23679, "CSS": 8582, "SCSS": 1690, "JavaScript": 1441, "Dockerfile": 548} | package org.vitrivr.cottontail.storage.serializers.values
import jetbrains.exodus.ArrayByteIterable
import jetbrains.exodus.ByteIterable
import org.vitrivr.cottontail.core.types.Types
import org.vitrivr.cottontail.core.values.FloatVectorValue
import org.xerial.snappy.Snappy
/**
* A [ValueSerializer] for [FloatVectorValue] serialization and deserialization.
*
* @author <NAME>
* @version 2.0.0
*/
class FloatVectorValueValueSerializer(size: Int): ValueSerializer<FloatVectorValue> {
init {
require(size > 0) { "Cannot initialize vector value binding with size value of $size." }
}
override val type: Types<FloatVectorValue> = Types.FloatVector(size)
override fun fromEntry(entry: ByteIterable): FloatVectorValue = FloatVectorValue(Snappy.uncompressFloatArray(entry.bytesUnsafe))
override fun toEntry(value: FloatVectorValue): ByteIterable {
val compressed = Snappy.compress(value.data)
return ArrayByteIterable(compressed, compressed.size)
}
} | 23 | Kotlin | 20 | 38 | baaf9a8799ed9a7c6b5113587fdca674d3f11497 | 1,001 | cottontaildb | MIT License |
core/src/main/java/com/gordonfromblumberg/calculator/CalculatorApp.kt | Gordon-from-Blumberg | 673,508,452 | false | null | package com.gordonfromblumberg.calculator
import com.badlogic.gdx.Game
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.assets.AssetManager
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.scenes.scene2d.ui.Skin
class CalculatorApp : Game() {
companion object {
var DEBUG = false
lateinit var INSTANCE: CalculatorApp
val ASSETS = AssetManager()
}
init {
INSTANCE = this
}
override fun create() {
Gdx.graphics.isContinuousRendering = false
ASSETS.load("ui/uiskin.atlas", TextureAtlas::class.java)
ASSETS.load("ui/uiskin.json", Skin::class.java)
// ASSETS.load("image/texture_pack.atlas", TextureAtlas::class.java)
ASSETS.finishLoading()
setScreen(CalculatorScreen())
}
} | 0 | Kotlin | 0 | 0 | be78d188eb03f438f5fa7b4c2a7549cb0e058d6f | 806 | calculator | MIT License |
lib/src/commonMain/kotlin/br/com/androidvip/snappier/domain/communication/CommunicationReceiver.kt | Lennoard | 782,262,217 | false | {"Kotlin": 106575, "TypeScript": 5377, "Ruby": 2165, "Swift": 594, "HTML": 593} | package br.com.androidvip.snappier.domain.communication
fun interface CommunicationReceiver {
/**
* Called when a component sends data to other components.
*
* @param data Communication data. Some platforms impose limit on this object's size.
* @param targetComponentIds Specific components IDs to which the [data] is intended.
* Can be `null`, denoting no particular component.
*/
fun receiveCommunication(data: Map<String, Any?>, targetComponentIds: List<String>?)
}
| 0 | Kotlin | 0 | 0 | 6f4e9bfe9a88abe961816c55cc8992642265e1ba | 508 | Snappier | MIT License |
simplified-ui-accounts/src/main/java/org/nypl/simplified/ui/accounts/ekirjasto/passkey/Authenticator.kt | NatLibFi | 730,988,035 | false | {"Kotlin": 3592315, "JavaScript": 853788, "Java": 403841, "CSS": 65407, "HTML": 49894, "Shell": 18611, "Ruby": 7554} | package org.nypl.simplified.ui.accounts.ekirjasto.passkey
import android.app.Activity
import androidx.credentials.CreatePublicKeyCredentialRequest
import androidx.credentials.CredentialManager
import androidx.credentials.GetCredentialRequest
import androidx.credentials.GetCredentialResponse
import androidx.credentials.GetPublicKeyCredentialOption
import androidx.credentials.PublicKeyCredential
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import org.nypl.simplified.ui.accounts.ekirjasto.passkey.datamodels.authenticate.AuthenticateParameters
import org.nypl.simplified.ui.accounts.ekirjasto.passkey.datamodels.authenticate.AuthenticateResult
import org.nypl.simplified.ui.accounts.ekirjasto.passkey.datamodels.authenticate.PublicKeyCredentialRequestOptions
import org.nypl.simplified.ui.accounts.ekirjasto.passkey.datamodels.register.RegisterChallengeRequestResponse
import org.nypl.simplified.ui.accounts.ekirjasto.passkey.datamodels.register.RegisterParameters
import org.nypl.simplified.ui.accounts.ekirjasto.passkey.datamodels.register.RegisterResult
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* Wrapper for android credential manager
*/
class Authenticator(
val application: Activity,
val credentialManager: CredentialManager
) {
val objectMapper = jacksonObjectMapper()
val logger: Logger = LoggerFactory.getLogger(Authenticator::class.java)
suspend fun authenticate(parameters: AuthenticateParameters): AuthenticateResult {
val options = PublicKeyCredentialRequestOptions.from(parameters)
val credOption = GetPublicKeyCredentialOption(objectMapper.writeValueAsString(options))
val request = GetCredentialRequest.Builder()
.addCredentialOption(credOption)
.build()
val result: GetCredentialResponse?
result = credentialManager.getCredential(application, request)
result.let {
when (val cred = it.credential) {
is PublicKeyCredential -> {
return AuthenticateResult.parseJson(cred)
}
else -> throw Exception("Invalid credential type: ${cred.javaClass.name}")
}
}
}
suspend fun register(parameters: RegisterParameters): RegisterResult {
lateinit var responseJson: JsonNode
val createPublicKeyCredentialRequest = CreatePublicKeyCredentialRequest(
requestJson = objectMapper.writeValueAsString(parameters)
)
val result = credentialManager.createCredential(
context = application,
request = createPublicKeyCredentialRequest,
)
val response: String =
result.data.getString("androidx.credentials.BUNDLE_KEY_REGISTRATION_RESPONSE_JSON", null)
responseJson = this.objectMapper.readValue(response)
this.logger.debug("Passkey Register Authenticator Response: {}", responseJson.toPrettyString())
return RegisterResult(
id = responseJson["id"].asText(),
rawId = responseJson["rawId"].asText(),
response = this.objectMapper.readValue<RegisterChallengeRequestResponse>(responseJson["response"].toString()),
type = responseJson["type"].asText()
)
}
}
| 2 | Kotlin | 0 | 0 | d6cef6591189a588c87ee744b27d86c5a23f6c45 | 3,181 | ekirjasto-android-core | Apache License 2.0 |
src/main/kotlin/cn/har01d/notebook/entity/Category.kt | power721 | 455,496,984 | false | {"Vue": 164653, "Kotlin": 149601, "TypeScript": 45280, "HTML": 39446, "JavaScript": 21584, "CSS": 5882, "Shell": 1465} | package cn.har01d.notebook.entity
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.JpaRepository
import java.time.Instant
import javax.persistence.*
@Entity
class Category(
@Column(nullable = false, unique = true) var name: String,
@Column(nullable = false) var description: String = "",
@Column(unique = true) var slug: String? = null,
@Column(nullable = false) val createdTime: Instant = Instant.now(),
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Int? = null
)
interface CategoryRepository : JpaRepository<Category, Int> {
fun existsBySlug(slug: String): Boolean
fun findBySlug(slug: String): Category?
fun existsByName(name: String): Boolean
fun findByName(name: String): Category?
fun findByNameContains(text: String, pageable: Pageable): Page<Category>
}
| 0 | Vue | 0 | 0 | e8abef8d38b3a98b7bb47988f5f97038878bfc97 | 933 | notebook | MIT License |
app/src/lite/java/com/bewell/storage/MeasureDao.kt | TheArtyomMDev | 421,437,651 | false | {"Kotlin": 95076, "Java": 1161} | package com.bewell.storage
import androidx.room.*
import com.bewell.data.Measure
@Dao
interface MeasureDao {
@get:Query("SELECT * FROM measures")
val all: List<Any?>?
@Query("SELECT * FROM measures WHERE id = :id")
fun getById(id: Long): Measure?
@Insert
fun insert(measure: Measure?)
@Update
fun update(measure: Measure?)
@Delete
fun delete(measure: Measure?)
} | 1 | Kotlin | 2 | 1 | 6482901050b7aebc9a28984797417c9f20b8f7c0 | 399 | BeWell | Apache License 2.0 |
openrndr/src/main/kotlin/util/ConcentrationGradient.kt | ericyd | 250,675,664 | false | {"Kotlin": 905784, "Rust": 540056, "JavaScript": 98751, "GLSL": 31121, "Processing": 6318, "HTML": 1074, "Shell": 873, "Makefile": 435} | package util
import org.openrndr.math.Vector2
import org.openrndr.math.clamp
import org.openrndr.shape.Rectangle
import kotlin.math.sqrt
// Disclaimer: I don't know if this is useful or not
/**
* A Double that is expected (but not guaranteed) to be in the range [0.0, 1.0]
*/
typealias PercentageDouble = Double
interface ConcentrationGradient {
/**
* Translate a point in Cartesian space into a percentage,
* based on the definition of the ConcentrationGradient and
* where the point is in relation to its bounding rectangle.
* @param boundingRect the bounding rectangle for `point`
* @param point the point to assess
* @return a percentage between 0.0 and 1.0 (inclusive) representing the concentration of the gradient at the given point.
*/
fun assess(boundingRect: Rectangle, point: Vector2, clamp: Boolean = false): PercentageDouble
/**
* Convert the point to a "unit point", where both x and y are in range [0.0, 1.0]
*/
fun normalizePoint(boundingRect: Rectangle, point: Vector2): Vector2 =
Vector2(
(point.x - boundingRect.x) / boundingRect.width,
(point.y - boundingRect.y) / boundingRect.height
)
}
/**
* Creates a 2D gradient f(x,y) where values are interpolated over a circle defined in relation to a unit square.
* Unit square: (corner at (0,0), width = 1, height = 1)
* @param center center of the radial gradient
* @param minRadius the distance from the center at which the gradient f(x,y) = 0.0
* @param maxRadius the distance from the center at which the gradient f(x,y) = 1.0
* @param reverse reverses the gradient so center has concentration 1.0 and radius has concentration 0.0
*/
class RadialConcentrationGradient(
private val center: Vector2 = Vector2.ZERO,
private val minRadius: Double = 0.0,
private val maxRadius: Double = sqrt(2.0),
private val reverse: Boolean = false
) : ConcentrationGradient {
override fun assess(boundingRect: Rectangle, point: Vector2, clamp: Boolean): PercentageDouble {
val normalizedPoint = normalizePoint(boundingRect, point)
// still figuring out if this is the right math, so keeping the original which doesn't use minRadius
var assessed = (normalizedPoint.distanceTo(center) - minRadius) / (maxRadius - minRadius)
if (clamp) {
assessed = clamp(assessed, 0.0, 1.0)
}
// debugging...
// println("===============================================")
// println("point: $point")
// println("boundingRect: $boundingRect")
// println("normalizedPoint: $normalizedPoint")
// println("center: $center")
// println("normalizedPoint.distanceTo(center): ${normalizedPoint.distanceTo(center)}")
// println(normalizedPoint.distanceTo(center) - minRadius)
return if (reverse) {
// 1.0 - normalizedPoint.distanceTo(center) / maxRadius
1.0 - assessed
} else {
// normalizedPoint.distanceTo(center) / maxRadius
assessed
}
}
companion object {
val default = RadialConcentrationGradient()
}
}
/**
* Creates a 2D gradient f(x,y) where values at the corners of the unit square determine the concentration in space.
* Calculates gradient using bilinear interpolation of four points, assumed to be on the unit square
* @param upperLeft f(0,0)
* @param upperRight f(1,0)
* @param lowerLeft f(0,1)
* @param lowerRight f(1,1)
*/
class BilinearConcentrationGradient(
private val upperLeft: Double = 0.0,
private val upperRight: Double = 0.0,
private val lowerLeft: Double = 0.0,
private val lowerRight: Double = 0.0
) : ConcentrationGradient {
override fun assess(boundingRect: Rectangle, point: Vector2, clamp: Boolean): PercentageDouble {
val normalizedPoint = normalizePoint(boundingRect, point)
return bilinearInterp(upperLeft, upperRight, lowerLeft, lowerRight, normalizedPoint)
}
companion object {
/**
* gradient goes from high (top left) to low (bottom right)
*/
val default = BilinearConcentrationGradient(1.0, 0.5, 0.5, 0.0)
/**
* possibly confusingly named... gradient goes from high (bottom) to low (top)
*/
val fadeUp = BilinearConcentrationGradient(0.0, 0.0, 1.0, 1.0)
/**
* possibly confusingly named... gradient goes from high (top) to low (bottom)
*/
val fadeDown = BilinearConcentrationGradient(1.0, 1.0, 0.0, 0.0)
}
}
| 2 | Kotlin | 0 | 58 | 57c17efb12df78fa5f4b5ab73adc6352a543cbbc | 4,336 | generative-art | MIT License |
src/main/kotlin/icu/windea/pls/cwt/psi/CwtParserDefinition.kt | DragonKnightOfBreeze | 328,104,626 | false | null | package icu.windea.pls.cwt.psi
import com.intellij.lang.*
import com.intellij.openapi.project.*
import com.intellij.psi.*
import com.intellij.psi.TokenType.*
import com.intellij.psi.tree.*
import icu.windea.pls.cwt.*
import icu.windea.pls.cwt.psi.CwtElementTypes.*
class CwtParserDefinition : ParserDefinition {
companion object {
val WHITE_SPACES = TokenSet.create(WHITE_SPACE)
val COMMENTS = TokenSet.create(COMMENT)
val STRINGS = TokenSet.create(STRING_TOKEN)
val FILE = IFileElementType("CWT_FILE", CwtLanguage)
}
override fun getWhitespaceTokens() = WHITE_SPACES
override fun getCommentTokens() = COMMENTS
override fun getStringLiteralElements() = STRINGS
override fun getFileNodeType() = FILE
override fun createFile(viewProvider: FileViewProvider) = CwtFile(viewProvider)
override fun createElement(node: ASTNode?) = Factory.createElement(node)
override fun createParser(project: Project?) = CwtParser()
override fun createLexer(project: Project?) = CwtLexerAdapter()
} | 1 | Kotlin | 1 | 7 | 037b9b4ba467ed49ea221b99efb0a26cd630bb67 | 1,012 | Paradox-Language-Support | MIT License |
sher-gil/src/main/java/com/kinnerapriyap/sugar/mediapreview/MediaPreviewAdapter.kt | kinnerapriyap | 266,549,787 | false | null | package com.kinnerapriyap.sugar.mediapreview
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.kinnerapriyap.sugar.databinding.ViewMediaObjectPreviewBinding
import com.kinnerapriyap.sugar.mediagallery.cell.MediaCellDisplayModel
import com.kinnerapriyap.sugar.mediagallery.cell.bindMediaUri
class MediaPreviewAdapter(
private val onMediaObjectPreviewClicked: ((MediaCellDisplayModel) -> Unit)
) : RecyclerView.Adapter<MediaPreviewAdapter.MediaPreviewObjectHolder>() {
var selectedMedia: List<MediaCellDisplayModel> = listOf()
set(value) {
field = value
notifyDataSetChanged()
}
override fun getItemCount(): Int = selectedMedia.size
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): MediaPreviewObjectHolder {
val binding = ViewMediaObjectPreviewBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return MediaPreviewObjectHolder(binding)
}
override fun onBindViewHolder(holder: MediaPreviewObjectHolder, position: Int) {
holder.bind(selectedMedia[position], onMediaObjectPreviewClicked)
}
inner class MediaPreviewObjectHolder(
private val binding: ViewMediaObjectPreviewBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bind(
displayModel: MediaCellDisplayModel,
onMediaObjectPreviewClicked: ((MediaCellDisplayModel) -> Unit)
) {
binding.imageView.bindMediaUri(displayModel.mediaUri)
binding.previewCheckBox.isChecked = displayModel.isChecked
binding.previewCheckBox.setOnClickListener {
onMediaObjectPreviewClicked.invoke(displayModel)
}
}
}
}
| 18 | Kotlin | 1 | 5 | cd5959a618a767d551f642f3244ef4afa2f6b9da | 1,857 | sher-gil | Apache License 2.0 |
src/commonMain/kotlin/ehn/techiop/hcert/kotlin/chain/impl/SchemaValidationAdapter.kt | ehn-dcc-development | 356,229,028 | false | null | package ehn.techiop.hcert.kotlin.chain.impl
import ehn.techiop.hcert.kotlin.data.CborObject
import ehn.techiop.hcert.kotlin.data.GreenCertificate
//As of 1.3.0 our codebase handles all version equally well
//we need to work around Duplicate JVM class name bug → we can skip expect definitions altogether
abstract class SchemaLoader<T>(vararg validVersions: String = KNOWN_VERSIONS) {
companion object {
internal val KNOWN_VERSIONS = arrayOf(
"1.0.0",
"1.0.1",
"1.1.0",
"1.2.0",
"1.2.1",
"1.3.0",
"1.3.1",
"1.3.2"
)
}
internal val validators = validVersions.mapIndexed { i, version ->
validVersions[i] to loadSchema(version)
}.toMap()
internal abstract fun loadSchema(version: String): T
internal abstract fun loadFallbackSchema(): T
}
expect class SchemaValidationAdapter(cbor: CborObject, validVersions: Array<String> = SchemaLoader.KNOWN_VERSIONS) {
fun hasValidator(versionString: String): Boolean
fun validateBasic(versionString: String): Collection<SchemaError>
fun toJson(): GreenCertificate
fun validateWithFallback(): Collection<SchemaError>
}
data class SchemaError(val error: String)
| 5 | Kotlin | 24 | 22 | e4ab29a52bda50e407028cc9489ad066404d3a29 | 1,268 | hcert-kotlin | Apache License 2.0 |
src/main/kotlin/com/nuecho/mutagen/cli/models/configuration/Switch.kt | nuecho | 154,838,618 | false | null | /*
* Copyright (C) 2018 Nu Echo Inc
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nuecho.mutagen.cli.models.configuration
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import com.genesyslab.platform.applicationblocks.com.CfgObject
import com.genesyslab.platform.applicationblocks.com.ICfgObject
import com.genesyslab.platform.applicationblocks.com.objects.CfgSwitch
import com.nuecho.mutagen.cli.core.InitializingBean
import com.nuecho.mutagen.cli.getFolderReference
import com.nuecho.mutagen.cli.getReference
import com.nuecho.mutagen.cli.models.configuration.ConfigurationObjects.checkUnchangeableProperties
import com.nuecho.mutagen.cli.models.configuration.ConfigurationObjects.setFolder
import com.nuecho.mutagen.cli.models.configuration.ConfigurationObjects.setProperty
import com.nuecho.mutagen.cli.models.configuration.ConfigurationObjects.toCfgLinkType
import com.nuecho.mutagen.cli.models.configuration.ConfigurationObjects.toCfgObjectState
import com.nuecho.mutagen.cli.models.configuration.ConfigurationObjects.toKeyValueCollection
import com.nuecho.mutagen.cli.models.configuration.reference.ApplicationReference
import com.nuecho.mutagen.cli.models.configuration.reference.ConfigurationObjectReference
import com.nuecho.mutagen.cli.models.configuration.reference.FolderReference
import com.nuecho.mutagen.cli.models.configuration.reference.PhysicalSwitchReference
import com.nuecho.mutagen.cli.models.configuration.reference.SwitchReference
import com.nuecho.mutagen.cli.models.configuration.reference.TenantReference
import com.nuecho.mutagen.cli.models.configuration.reference.referenceSetBuilder
import com.nuecho.mutagen.cli.services.ConfService
import com.nuecho.mutagen.cli.toShortName
/**
* Unused fields address and contactPersonDBID are not defined.
*/
data class Switch(
val tenant: TenantReference,
val name: String,
val physicalSwitch: PhysicalSwitchReference? = null,
@get:JsonProperty("tServer")
val tServer: ApplicationReference? = null,
val linkType: String? = null,
val switchAccessCodes: List<SwitchAccessCode>? = null,
val dnRange: String? = null,
val state: String? = null,
@JsonSerialize(using = CategorizedPropertiesSerializer::class)
@JsonDeserialize(using = CategorizedPropertiesDeserializer::class)
override val userProperties: CategorizedProperties? = null,
override val folder: FolderReference? = null
) : ConfigurationObject, InitializingBean {
@get:JsonIgnore
override val reference = SwitchReference(name, tenant)
constructor(switch: CfgSwitch) : this(
tenant = switch.tenant.getReference(),
name = switch.name,
physicalSwitch = switch.physSwitch?.getReference(),
tServer = switch.tServer?.getReference(),
linkType = switch.linkType?.toShortName(),
switchAccessCodes = switch.switchAccessCodes?.map { SwitchAccessCode(it) },
dnRange = switch.dnRange,
state = switch.state?.toShortName(),
userProperties = switch.userProperties?.asCategorizedProperties(),
folder = switch.getFolderReference()
)
override fun createCfgObject(service: ConfService) =
updateCfgObject(service, CfgSwitch(service)).also {
setProperty("tenantDBID", service.getObjectDbid(tenant), it)
setProperty("name", name, it)
setProperty("physSwitchDBID", service.getObjectDbid(physicalSwitch), it)
setFolder(folder, it, service)
}
override fun updateCfgObject(service: ConfService, cfgObject: ICfgObject) =
(cfgObject as CfgSwitch).also { switch ->
setProperty("TServerDBID", service.getObjectDbid(tServer), switch)
setProperty("linkType", toCfgLinkType(linkType), switch)
setProperty(
"switchAccessCodes",
switchAccessCodes?.map { accessCode -> accessCode.toCfgSwitchAccessCode(service, switch) },
switch
)
setProperty("DNRange", dnRange, switch)
setProperty("state", toCfgObjectState(state), switch)
setProperty("userProperties", toKeyValueCollection(userProperties), switch)
}
override fun cloneBare() = Switch(
tenant = tenant,
name = name,
physicalSwitch = physicalSwitch
)
override fun checkMandatoryProperties(configuration: Configuration, service: ConfService): Set<String> =
if (physicalSwitch == null) setOf(PHYSICAL_SWITCH) else emptySet()
override fun checkUnchangeableProperties(cfgObject: CfgObject) =
checkUnchangeableProperties(this, cfgObject).also { unchangeableProperties ->
(cfgObject as CfgSwitch).also {
physicalSwitch?.run {
if (this != it.physSwitch?.getReference()) unchangeableProperties.add(PHYSICAL_SWITCH)
}
}
}
override fun afterPropertiesSet() {
switchAccessCodes?.forEach { it.updateTenantReferences(tenant) }
}
override fun getReferences(): Set<ConfigurationObjectReference<*>> =
referenceSetBuilder()
.add(tenant)
.add(physicalSwitch)
.add(tServer)
.add(switchAccessCodes?.mapNotNull { it.switch })
.add(folder)
.toSet()
}
| 0 | Kotlin | 2 | 4 | c508200bc6e1b2e4d16ec4426047c40ae44deb47 | 6,001 | mutagen | Apache License 2.0 |
app/src/main/java/com/yelai/wearable/ui/course/CourseFragment.kt | xlhlivy | 160,482,414 | false | null | package com.yelai.wearable.ui.course
import android.os.Bundle
import android.support.v4.app.Fragment
import cn.droidlover.xdroidmvp.mvp.KLazyFragment
import com.flyco.tablayout.listener.CustomTabEntity
import com.yelai.wearable.R
import com.yelai.wearable.entity.TabEntity
import com.yelai.wearable.present.PViod
import kotlinx.android.synthetic.main.course_fragment.*
import org.jetbrains.anko.sdk25.coroutines.onClick
import java.util.ArrayList
/**
* Created by hr on 18/9/16.
*/
class CourseFragment : KLazyFragment<PViod>() {
private val mFragments = ArrayList<Fragment>()
private val mTitles = arrayOf("我的课程", "兴趣课", "训练")
private val mIconUnselectIds = intArrayOf(R.drawable.day_tab_icon_sport_normal, R.drawable.day_tab_icon_action_normal, R.drawable.day_tab_icon_status_normal)
private val mIconSelectIds = intArrayOf(R.drawable.day_tab_icon_sport_press, R.drawable.day_tab_icon_action_press, R.drawable.day_tab_icon_status_press)
private val mTabEntities = ArrayList<CustomTabEntity>()
override fun initData(savedInstanceState: Bundle?) {
mTabEntities.clear()
mFragments.clear()
for (i in mTitles.indices) {
mTabEntities.add(TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]))
}
mFragments.add(MineCourseFragment.newInstance())
mFragments.add(InterestCourseFragment.newInstance())
mFragments.add(TrainingCourseFragment.newInstance())
ctlLayout.setTabData(mTabEntities,childFragmentManager,R.id.ctlContent,mFragments)
tvAddCourse.onClick {
SearchActivity.launch([email protected])
}
}
override fun getLayoutId(): Int {
return R.layout.course_fragment
}
override fun newP(): PViod? {
return null
}
companion object {
fun newInstance(): CourseFragment {
val fragment = CourseFragment()
return fragment
}
}
}
| 1 | null | 1 | 1 | d2cef9124533751d577f9dc518359fc9a7317a9e | 1,968 | AiSportStudent | MIT License |
app/src/main/java/com/robert/banyai/wup/data/repository/CardRepository.kt | robertbanyai72 | 272,161,765 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 83, "XML": 31, "Java": 1} | package com.robert.banyai.wup.data.repository
import com.robert.banyai.wup.domain.Resource
import com.robert.banyai.wup.domain.event.GetCardEvent
import com.robert.banyai.wup.domain.event.GetCardsEvent
import com.robert.banyai.wup.domain.model.Card
import com.robert.banyai.wup.domain.model.CardList
import io.reactivex.rxjava3.core.Single
interface CardRepository {
fun fetchCards(getCardsEvent: GetCardsEvent): Single<Resource<CardList>>
fun getCard(getCardEvent: GetCardEvent): Single<Resource<Card>>
} | 1 | null | 1 | 1 | 511bf026fac90226889fa09be2e55ae886b2665c | 515 | w.up_app | Apache License 2.0 |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/connectcampaigns/CfnCampaignAnswerMachineDetectionConfigPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 70198112} | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.connectcampaigns
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.Boolean
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.connectcampaigns.CfnCampaign
/**
* Contains information about answering machine detection.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.connectcampaigns.*;
* AnswerMachineDetectionConfigProperty answerMachineDetectionConfigProperty =
* AnswerMachineDetectionConfigProperty.builder()
* .enableAnswerMachineDetection(false)
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-connectcampaigns-campaign-answermachinedetectionconfig.html)
*/
@CdkDslMarker
public class CfnCampaignAnswerMachineDetectionConfigPropertyDsl {
private val cdkBuilder: CfnCampaign.AnswerMachineDetectionConfigProperty.Builder =
CfnCampaign.AnswerMachineDetectionConfigProperty.builder()
/** @param enableAnswerMachineDetection Whether answering machine detection is enabled. */
public fun enableAnswerMachineDetection(enableAnswerMachineDetection: Boolean) {
cdkBuilder.enableAnswerMachineDetection(enableAnswerMachineDetection)
}
/** @param enableAnswerMachineDetection Whether answering machine detection is enabled. */
public fun enableAnswerMachineDetection(enableAnswerMachineDetection: IResolvable) {
cdkBuilder.enableAnswerMachineDetection(enableAnswerMachineDetection)
}
public fun build(): CfnCampaign.AnswerMachineDetectionConfigProperty = cdkBuilder.build()
}
| 0 | Kotlin | 0 | 3 | 256ad92aebe2bcf9a4160089a02c76809dbbedba | 1,956 | awscdk-dsl-kotlin | Apache License 2.0 |
ATMConsultoria/app/src/main/java/br/com/valchan/atmconsultoria/DetalhesContatoActivity.kt | ValchanOficial | 145,775,478 | false | null | package br.com.valchan.atmconsultoria
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
class DetalhesContatoActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detalhes_contato)
}
}
| 0 | Kotlin | 0 | 0 | f6c88289931832e7c4251bd15f70fb1934e95324 | 335 | estudo-kotlin | MIT License |
core/src/main/kotlin/pro/guopi/tidy/Promise.kt | guopi | 429,850,652 | false | null | package pro.guopi.tidy
import pro.guopi.tidy.Tidy.Companion.main
import pro.guopi.tidy.promise.ErrorPromise
import pro.guopi.tidy.promise.StdPromise
import pro.guopi.tidy.promise.SuccessPromise
interface PromiseSubscriber<in T> : ErrorSubscriber {
@MustCallInMainPlane
fun onSuccess(value: T)
}
interface Promise<out T> {
@MustCallInMainPlane
fun subscribe(subscriber: PromiseSubscriber<T>)
companion object {
@JvmStatic
fun <T> create(action: (PromiseSubscriber<T>) -> Unit): Promise<T> {
val promise = StdPromise<T>()
main.start {
action(promise)
}
return promise
}
@JvmStatic
fun <T> success(value: T): Promise<T> {
return SuccessPromise(value)
}
@JvmStatic
fun <T> error(error: Throwable): Promise<T> {
return ErrorPromise(error)
}
}
} | 0 | Kotlin | 0 | 0 | 446623a9fadc047b8fd9122c161b2870beab9fbd | 930 | tidyjava | Apache License 2.0 |
app/src/main/java/co/hellocode/micro/ProfileActivity.kt | bellebethcooper | 145,940,807 | false | null | package co.hellocode.micro
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.AppBarLayout
import android.support.design.widget.Snackbar
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import co.hellocode.micro.NewPost.NewPostActivity
import co.hellocode.micro.Utils.NEW_POST_REQUEST_CODE
import co.hellocode.micro.Utils.PREFS_FILENAME
import co.hellocode.micro.Utils.TOKEN
import com.android.volley.AuthFailureError
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.TimeoutError
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.squareup.picasso.Picasso
import jp.wasabeef.picasso.transformations.CropCircleTransformation
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_profile_collapsing.*
import kotlinx.android.synthetic.main.baselayout_timeline.*
import org.json.JSONArray
import org.json.JSONObject
import java.util.ArrayList
import java.util.HashMap
class ProfileActivity : AppCompatActivity() {
var url = "https://micro.blog/posts/"
var title = ""
private lateinit var linearLayoutManager: LinearLayoutManager
open lateinit var adapter: TimelineRecyclerAdapter
open var posts = ArrayList<Post>()
private lateinit var refresh: SwipeRefreshLayout
var following = false
lateinit var username: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(contentView())
setSupportActionBar(toolbar)
supportActionBar?.title = title
this.linearLayoutManager = LinearLayoutManager(this)
profile_recyclerView.layoutManager = this.linearLayoutManager
this.adapter = TimelineRecyclerAdapter(this.posts)
profile_recyclerView.adapter = this.adapter
Log.i("BaseTimeline", "recycler: $profile_recyclerView")
collapsing_toolbar.setCollapsedTitleTextColor(resources.getColor(R.color.colorWhite))
refresh = profile_refresher
refresh.setOnRefreshListener { refresh() }
initialLoad()
}
fun initialLoad() {
this.username = intent.getStringExtra("username")
this.url = this.url + this.username
this.refresh.isRefreshing = true
refresh()
}
private fun refresh() {
Log.i("BaseTimeline", "refresh")
getTimeline()
}
fun contentView(): Int {
return R.layout.activity_profile_collapsing
}
fun prefs() : SharedPreferences {
return getSharedPreferences(PREFS_FILENAME, Context.MODE_PRIVATE)
}
private fun getTimeline() {
Log.i("BaseTimeline", "getTimeline")
val rq = object : JsonObjectRequest(
this.url,
null,
Response.Listener<JSONObject> { response ->
// Log.i("MainActivity", "resp: $response")
val items = response["items"] as JSONArray
createPosts(items)
getRequestComplete(response)
this.adapter.notifyDataSetChanged()
this.refresh.isRefreshing = false
},
Response.ErrorListener { error ->
Log.i("MainActivity", "err: $error msg: ${error.message}")
this.refresh.isRefreshing = false
if (error is TimeoutError) {
Snackbar.make(this.profile_recyclerView, "Request timed out; trying again", Snackbar.LENGTH_SHORT)
this.getTimeline()
}
}) {
@Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val headers = HashMap<String, String>()
val prefs = prefs()
val token: String? = prefs.getString(TOKEN, null)
headers["Authorization"] = "Bearer $token"
return headers
}
}
val queue = Volley.newRequestQueue(this)
queue.add(rq)
}
fun createPosts(items: JSONArray) {
this.posts.clear()
for (i in 0 until items.length()) {
val item = items[i] as JSONObject
this.posts.add(Post(item))
}
}
fun getRequestComplete(response: JSONObject) {
val author = response.getJSONObject("author")
val microBlog = response.getJSONObject("_microblog")
setProfileData(author, microBlog)
collapsing_profile_follow_button.setOnClickListener { followButtonTapped(this.username) }
setToolbarTitle(this.username)
setFABListener()
}
fun setProfileData(author: JSONObject, microBlogData: JSONObject) {
collapsing_profile_name_view.text = author.getString("name")
val website = author.getString("url")
if (website.length > 0) {
collapsing_profile_website.text = website
} else {
collapsing_profile_website.visibility = View.GONE
}
val avatarURL = author.getString("avatar")
Picasso.get().load(avatarURL).transform(CropCircleTransformation()).into(collapsing_profile_avatar)
collapsing_profile_username.text = microBlogData.getString("username")
val bio = microBlogData.getString("bio")
if (bio.length > 0) {
collapsing_profile_bio.text = bio
} else {
collapsing_profile_bio.visibility = View.GONE
}
val isYou = microBlogData.getBoolean("is_you")
if (isYou) {
collapsing_profile_follow_button.visibility = View.GONE
} else {
following = microBlogData.getBoolean("is_following")
collapsing_profile_follow_button.text = if (this.following == true) "Unfollow" else "Follow"
}
}
fun setFABListener() {
profile_fab.setOnClickListener {
val intent = Intent(this, NewPostActivity::class.java)
Log.i("ProfileAct", "author: $username")
intent.putExtra("@string/reply_intent_extra_author", this.username)
startActivityForResult(intent, NEW_POST_REQUEST_CODE)
}
}
private fun setToolbarTitle(username: String) {
collapsing_profile_appbar.addOnOffsetChangedListener(object : AppBarLayout.OnOffsetChangedListener {
var isShown = false
var scrollRange = -1
override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) {
if (scrollRange == -1) {
scrollRange = appBarLayout.totalScrollRange
}
Log.i("ProfileAct", "scroll range: $scrollRange offset: $verticalOffset")
if (scrollRange + verticalOffset == 0) {
collapsing_profile_view.visibility = View.INVISIBLE
collapsing_toolbar.title = username
isShown = true
} else {
collapsing_profile_view.visibility = View.VISIBLE
collapsing_toolbar.title = " "
isShown = false
}
}
})
}
private fun followButtonTapped(username: String) {
val followURL = if (this.following) {
"https://micro.blog/users/unfollow"
} else {
"https://micro.blog/users/follow"
}
val rq = object : StringRequest(
Request.Method.POST,
followURL,
Response.Listener<String> { response ->
if (this.following) {
// this.following is already true, so we just unfollowed
collapsing_profile_follow_button.text = "Follow"
this.following = false
} else {
// this.following is false, so we just followed
collapsing_profile_follow_button.text = "Unfollow"
this.following = true
}
},
Response.ErrorListener { error ->
Log.i("ProfileAct", "err following or unfollowing: $error msg: ${error.message}")
}) {
@Throws(AuthFailureError::class)
override fun getHeaders(): Map<String, String> {
val headers = HashMap<String, String>()
val prefs = prefs()
val token: String? = prefs.getString(TOKEN, null)
headers["Authorization"] = "Bearer $token"
return headers
}
@Throws(AuthFailureError::class)
override fun getParams(): Map<String, String> {
Log.i("MainActivity", "getParams")
val params = HashMap<String, String>()
params["username"] = username
return params
}
}
val queue = Volley.newRequestQueue(this)
queue.add(rq)
}
}
| 24 | null | 3 | 12 | d360b703e7663dfcf3133b78210b7e77b25456b8 | 9,336 | pico | MIT License |
domene/src/main/kotlin/no/nav/tiltakspenger/saksbehandling/domene/stønadsdager/StønadsdagerEx.kt | navikt | 487,246,438 | false | {"Kotlin": 946725, "Shell": 1318, "Dockerfile": 495, "HTML": 45} | package no.nav.tiltakspenger.saksbehandling.domene.stønadsdager
import no.nav.tiltakspenger.saksbehandling.domene.tiltak.Tiltak
import java.time.LocalDateTime
fun Tiltak.tilStønadsdagerRegisterSaksopplysning(): StønadsdagerSaksopplysning.Register =
// B: Hvorfor kan deltagelsen være null fra tiltaksappen? Får vi null-verdier fra Arena eller Komet?
if (antallDagerPerUke != null) {
StønadsdagerSaksopplysning.Register(
tiltakNavn = gjennomføring.typeNavn,
// Vi får per nå antall dager per uke, men ønsker å ha antall dager per meldeperiode.
// Ettersom vi kan få desimaler fra komet gjør vi denne om til en int etter sammenleggingen.
antallDager = (antallDagerPerUke * 2).toIntPrecise(),
periode = deltakelsesperiode,
kilde = kilde,
tidsstempel = LocalDateTime.now(),
)
} else if (deltakelseProsent != null) {
StønadsdagerSaksopplysning.Register(
tiltakNavn = gjennomføring.typeNavn,
// B: Så på tidligere kode som gjorde dette, kan deltakelseprosent være noe annet enn 100?
antallDager = if (deltakelseProsent == 100f) 5 else throw IllegalStateException("Forventet 100% deltakelse. Vi støtter ikke lavere prosenter enn dette i MVP."),
periode = deltakelsesperiode,
kilde = kilde,
tidsstempel = LocalDateTime.now(),
)
} else {
throw IllegalStateException("Antall dager per uke og deltakelseprosent bør ikke være null samtidig. Da må vi i så fall legge til støtte for det etter MVP.")
}
private fun Float.toIntPrecise() =
if (this % 1 == 0f) this.toInt() else throw IllegalStateException("Forventet et heltall, men var $this")
| 9 | Kotlin | 0 | 1 | c23890a313eac464b2eae8d6e6f143b47a4b693e | 1,751 | tiltakspenger-vedtak | MIT License |
app/src/main/java/com/yveschiong/macrofit/presenters/AddFoodPresenter.kt | yveschiong | 135,364,946 | false | {"Kotlin": 130902} | package com.yveschiong.macrofit.presenters
import com.yveschiong.macrofit.constants.ResponseCode
import com.yveschiong.macrofit.contracts.AddFoodViewContract
import com.yveschiong.macrofit.models.Food
import com.yveschiong.macrofit.models.NutritionFact
import com.yveschiong.macrofit.repositories.NutritionFactsRepository
import javax.inject.Inject
class AddFoodPresenter<V : AddFoodViewContract.View> @Inject constructor(
private val nutritionFactsRepository: NutritionFactsRepository
) : RootPresenter<V>(), AddFoodViewContract.Presenter<V> {
override fun fetchNutritionFacts() {
nutritionFactsRepository.getNutritionFacts()
.call { view?.showNutritionFacts(it) }
}
override fun selectNutritionFact(nutritionFact: NutritionFact) {
view?.setUnitText(nutritionFact.unit)
}
override fun validateWeight(input: String): Boolean {
// Check if the input is not empty and if the value is greater than 0
when {
input.isEmpty() -> view?.tryShowWeightErrorMessage(ResponseCode.FIELD_IS_REQUIRED)
(input.toFloatOrNull() ?: 0.0f) <= 0.0f -> view?.tryShowWeightErrorMessage(ResponseCode.FIELD_IS_INVALID)
else -> {
view?.tryShowWeightErrorMessage(ResponseCode.OK)
return true
}
}
return false
}
override fun parseWeightText(text: String?): Float {
return text?.toFloatOrNull() ?: 0.0f
}
override fun setWeight(nutritionFact: NutritionFact, weightAmount: Float) {
// Calculate the scale first and then apply it to every other amount
val scale = weightAmount / nutritionFact.amount
view?.setCardData(nutritionFact.name, weightAmount, nutritionFact.unit,
nutritionFact.calories * scale, nutritionFact.protein * scale,
nutritionFact.carbs * scale, nutritionFact.fat * scale)
}
override fun createFood(timeAdded: Long, nutritionFact: NutritionFact, weightAmount: Float): Food {
// Calculate the scale first and then apply it to every other amount
val scale = weightAmount / nutritionFact.amount
return Food(timeAdded, nutritionFact.name, weightAmount, nutritionFact.unit,
nutritionFact.calories * scale, nutritionFact.protein * scale,
nutritionFact.carbs * scale, nutritionFact.fat * scale, nutritionFact.id)
}
}
| 0 | Kotlin | 0 | 0 | 57a923fe85f7a69d3da87d4835cd453522f3d009 | 2,401 | macro-fit | MIT License |
app/src/main/java/com/yveschiong/macrofit/presenters/AddFoodPresenter.kt | yveschiong | 135,364,946 | false | {"Kotlin": 130902} | package com.yveschiong.macrofit.presenters
import com.yveschiong.macrofit.constants.ResponseCode
import com.yveschiong.macrofit.contracts.AddFoodViewContract
import com.yveschiong.macrofit.models.Food
import com.yveschiong.macrofit.models.NutritionFact
import com.yveschiong.macrofit.repositories.NutritionFactsRepository
import javax.inject.Inject
class AddFoodPresenter<V : AddFoodViewContract.View> @Inject constructor(
private val nutritionFactsRepository: NutritionFactsRepository
) : RootPresenter<V>(), AddFoodViewContract.Presenter<V> {
override fun fetchNutritionFacts() {
nutritionFactsRepository.getNutritionFacts()
.call { view?.showNutritionFacts(it) }
}
override fun selectNutritionFact(nutritionFact: NutritionFact) {
view?.setUnitText(nutritionFact.unit)
}
override fun validateWeight(input: String): Boolean {
// Check if the input is not empty and if the value is greater than 0
when {
input.isEmpty() -> view?.tryShowWeightErrorMessage(ResponseCode.FIELD_IS_REQUIRED)
(input.toFloatOrNull() ?: 0.0f) <= 0.0f -> view?.tryShowWeightErrorMessage(ResponseCode.FIELD_IS_INVALID)
else -> {
view?.tryShowWeightErrorMessage(ResponseCode.OK)
return true
}
}
return false
}
override fun parseWeightText(text: String?): Float {
return text?.toFloatOrNull() ?: 0.0f
}
override fun setWeight(nutritionFact: NutritionFact, weightAmount: Float) {
// Calculate the scale first and then apply it to every other amount
val scale = weightAmount / nutritionFact.amount
view?.setCardData(nutritionFact.name, weightAmount, nutritionFact.unit,
nutritionFact.calories * scale, nutritionFact.protein * scale,
nutritionFact.carbs * scale, nutritionFact.fat * scale)
}
override fun createFood(timeAdded: Long, nutritionFact: NutritionFact, weightAmount: Float): Food {
// Calculate the scale first and then apply it to every other amount
val scale = weightAmount / nutritionFact.amount
return Food(timeAdded, nutritionFact.name, weightAmount, nutritionFact.unit,
nutritionFact.calories * scale, nutritionFact.protein * scale,
nutritionFact.carbs * scale, nutritionFact.fat * scale, nutritionFact.id)
}
}
| 0 | Kotlin | 0 | 0 | 57a923fe85f7a69d3da87d4835cd453522f3d009 | 2,401 | macro-fit | MIT License |
DailyMovie/app/src/main/java/com/example/dailymovie/fragments/HomeF.kt | jesus33lcc | 794,693,138 | false | {"Kotlin": 55973, "Java": 5856} | package com.example.dailymovie.fragments
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 androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.example.dailymovie.R
import com.example.dailymovie.adapters.NowPlayingAdapter
import com.example.dailymovie.databinding.FragmentHomeBinding
import com.example.dailymovie.models.MovieOfTheDay
import com.example.dailymovie.utils.Constantes
class HomeF : Fragment() {
private lateinit var homeViewModel: HomeViewModel
private var _binding: FragmentHomeBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentHomeBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
homeViewModel = ViewModelProvider(this).get(HomeViewModel::class.java)
binding.recyclerViewNowPlaying.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
binding.recyclerViewPopular.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
binding.recyclerViewTopRated.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
binding.recyclerViewUpcoming.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
homeViewModel.nowPlayingMovies.observe(viewLifecycleOwner, Observer { movies ->
binding.recyclerViewNowPlaying.adapter = NowPlayingAdapter(movies)
})
homeViewModel.popularMovies.observe(viewLifecycleOwner, Observer { movies ->
binding.recyclerViewPopular.adapter = NowPlayingAdapter(movies)
})
homeViewModel.topRatedMovies.observe(viewLifecycleOwner, Observer { movies ->
binding.recyclerViewTopRated.adapter = NowPlayingAdapter(movies)
})
homeViewModel.upcomingMovies.observe(viewLifecycleOwner, Observer { movies ->
binding.recyclerViewUpcoming.adapter = NowPlayingAdapter(movies)
})
homeViewModel.movieOfTheDay.observe(viewLifecycleOwner, Observer { movie ->
movie?.let {
Log.d("HomeF", "Movie of the day: ${it.title}")
displayMovieOfTheDay(it)
} ?: Log.d("HomeF", "Movie of the day is null")
})
homeViewModel.fetchNowPlayingMovies(Constantes.API_KEY)
homeViewModel.fetchPopularMovies(Constantes.API_KEY)
homeViewModel.fetchTopRatedMovies(Constantes.API_KEY)
homeViewModel.fetchUpcomingMovies(Constantes.API_KEY)
homeViewModel.fetchMovieOfTheDay()
}
private fun displayMovieOfTheDay(movie: MovieOfTheDay) {
binding.movieTitle.text = movie.title
binding.movieRating.text = "Rating: ${movie.rating}"
binding.movieReview.text = movie.review
binding.movieDate.text = "Fecha: ${movie.date}"
binding.movieAuthor.text = "Autor: ${movie.author}"
Glide.with(this)
.load(Constantes.IMAGE_URL + movie.posterPath)
.into(binding.moviePoster)
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | 0 | Kotlin | 0 | 0 | 135bcf1bf35433c827ab1b0bcd09150bb8c3dc58 | 3,603 | DailyMovie | MIT License |
app/src/main/java/com/droidafricana/moveery/di/modules/ViewModelsModule.kt | Fbada006 | 240,091,360 | false | null | package com.droidafricana.moveery.di.modules
import androidx.lifecycle.ViewModel
import com.droidafricana.moveery.di.keys.ViewModelKey
import com.droidafricana.moveery.ui.details.movies.MovieDetailsViewModel
import com.droidafricana.moveery.ui.details.shows.ShowDetailsViewModel
import com.droidafricana.moveery.ui.details.similardetails.similarmovie.SimilarMovieDetailsViewModel
import com.droidafricana.moveery.ui.details.similardetails.similarshow.SimilarShowsViewModel
import com.droidafricana.moveery.ui.favourites.movie.FavMoviesViewModel
import com.droidafricana.moveery.ui.favourites.shows.FavShowsViewModel
import com.droidafricana.moveery.ui.landing.movies.MoviesLandingViewModel
import com.droidafricana.moveery.ui.landing.shows.ShowsLandingViewModel
import com.droidafricana.moveery.ui.search.movies.MovieSearchViewModel
import com.droidafricana.moveery.ui.search.shows.ShowsSearchViewModel
import dagger.Binds
import dagger.Module
import dagger.multibindings.IntoMap
/**Handles creation of the different types of [ViewModel]*/
@Module
abstract class ViewModelsModule {
/**Create the [MoviesLandingViewModel]*/
@Binds
@IntoMap
@ViewModelKey(MoviesLandingViewModel::class)
abstract fun bindMoviesLandingViewModel(viewModel: MoviesLandingViewModel): ViewModel
/**Create the [MovieSearchViewModel]*/
@Binds
@IntoMap
@ViewModelKey(MovieSearchViewModel::class)
abstract fun bindMoviesSearchViewModel(viewModel: MovieSearchViewModel): ViewModel
/**Create the [MovieDetailsViewModel]*/
@Binds
@IntoMap
@ViewModelKey(MovieDetailsViewModel::class)
abstract fun bindMoviesDetailsViewModel(viewModel: MovieDetailsViewModel): ViewModel
/**Create the [ShowsLandingViewModel]*/
@Binds
@IntoMap
@ViewModelKey(ShowsLandingViewModel::class)
abstract fun bindShowsLandingViewModel(viewModel: ShowsLandingViewModel): ViewModel
/**Create the [ShowsSearchViewModel]*/
@Binds
@IntoMap
@ViewModelKey(ShowsSearchViewModel::class)
abstract fun bindShowsSearchViewModel(viewModel: ShowsSearchViewModel): ViewModel
/**Create the [ShowDetailsViewModel]*/
@Binds
@IntoMap
@ViewModelKey(ShowDetailsViewModel::class)
abstract fun bindShowsDetailsViewModel(viewModel: ShowDetailsViewModel): ViewModel
/**Create the [FavMoviesViewModel]*/
@Binds
@IntoMap
@ViewModelKey(FavMoviesViewModel::class)
abstract fun bindFavMoviesViewModel(viewModel: FavMoviesViewModel): ViewModel
/**Create the [FavShowsViewModel]*/
@Binds
@IntoMap
@ViewModelKey(FavShowsViewModel::class)
abstract fun bindFavShowsViewModel(viewModel: FavShowsViewModel): ViewModel
/**Create the [SimilarMovieDetailsViewModel]*/
@Binds
@IntoMap
@ViewModelKey(SimilarMovieDetailsViewModel::class)
abstract fun bindSimilarMoviesViewModel(viewModel: SimilarMovieDetailsViewModel): ViewModel
/**Create the [SimilarShowsViewModel]*/
@Binds
@IntoMap
@ViewModelKey(SimilarShowsViewModel::class)
abstract fun bindSimilarShowsViewModel(viewModel: SimilarShowsViewModel): ViewModel
} | 0 | Kotlin | 0 | 2 | 92b175690eac0333ecbe0d87c9f07084f6099459 | 3,124 | Moveery | Apache License 2.0 |
server/src/test/kotlin/idh/c3cloud/tis/pilot/StructureMapTest.kt | C3-Cloud-eu | 286,454,731 | true | {"Kotlin": 111267, "JavaScript": 34039, "Java": 24938, "HTML": 1590, "CSS": 1348} | package idh.c3cloud.tis.pilot
import kotlinx.coroutines.runBlocking
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.http.MediaType
import org.springframework.test.context.junit4.SpringRunner
import java.io.File
@RunWith(SpringRunner::class)
@SpringBootTest
class StructureMapTest {
@Autowired
private lateinit var structureMap: StructureMap
@Test
fun mapCda() {
val cdaFile = File(javaClass.classLoader.getResource("CDA-example.xml").path)
val fhirBundle = runBlocking {
structureMap.transform("provider1:cda:0.1", MediaType.TEXT_XML_VALUE, cdaFile.readText())
}
println(fhirBundle)
}
} | 0 | Kotlin | 1 | 3 | 01c6e287b81dbacfb9587eccb7b1c3e5360bc74e | 809 | tis | Apache License 2.0 |
app/src/main/java/chat/rocket/android/push/gcm/GcmPushHelper.kt | mohak1712 | 138,123,986 | true | {"Markdown": 7, "Batchfile": 1, "Shell": 1, "Java Properties": 2, "Java": 285, "Kotlin": 53, "Proguard": 2} | package chat.rocket.android.push.gcm
import bolts.Task
import chat.rocket.android.R
import chat.rocket.android.RocketChatApplication
import chat.rocket.android.RocketChatCache
import chat.rocket.android.api.RaixPushHelper
import chat.rocket.persistence.realm.RealmHelper
import chat.rocket.persistence.realm.models.ddp.RealmUser
import com.google.android.gms.gcm.GoogleCloudMessaging
import com.google.android.gms.iid.InstanceID
import java.io.IOException
object GcmPushHelper {
fun getGcmToken(): String? = getGcmToken(getSenderId())
@Throws(IOException::class)
private fun registerGcmTokenForServer(realmHelper: RealmHelper): Task<Void> {
val gcmToken = getGcmToken(getSenderId())
val currentUser = realmHelper.executeTransactionForRead({ realm -> RealmUser.queryCurrentUser(realm).findFirst() })
val userId = if (currentUser != null) currentUser.getId() else null
val pushId = RocketChatCache.getOrCreatePushId()
return RaixPushHelper(realmHelper)
.pushUpdate(pushId!!, gcmToken, userId)
}
@Throws(IOException::class)
private fun getGcmToken(senderId: String): String {
return InstanceID.getInstance(RocketChatApplication.getInstance())
.getToken(senderId, GoogleCloudMessaging.INSTANCE_ID_SCOPE, null)
}
private fun getSenderId(): String {
return RocketChatApplication.getInstance().getString(R.string.gcm_sender_id)
}
} | 1 | Java | 1 | 1 | b73c228724e47bc74a0973189801390439c520b1 | 1,455 | Rocket.Chat.Android-develop | MIT License |
network/src/main/kotlin/com/ohyooo/network/model/RateLimitResponse.kt | ohyooo | 164,578,051 | false | null | package com.ohyooo.network.model
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
@Parcelize
data class RateLimitResponse(var rate: Rate? = null, var resources: Resources? = null) : BaseResponse(), Parcelable
@Parcelize
data class Rate(var limit: Int?, var remaining: Int?, var reset: Int?) : Parcelable
@Parcelize
data class Resources(var core: Core?, var graphql: Graphql?, var integration_manifest: IntegrationManifest?, var search: Search?, var source_import: SourceImport?) : Parcelable
@Parcelize
data class Core(var limit: Int?, var remaining: Int?, var reset: Int?) : Parcelable
@Parcelize
data class Graphql(var limit: Int?, var remaining: Int?, var reset: Int?) : Parcelable
@Parcelize
data class IntegrationManifest(var limit: Int?, var remaining: Int?, var reset: Int?) : Parcelable
@Parcelize
data class Search(var limit: Int?, var remaining: Int?, var reset: Int?) : Parcelable
@Parcelize
data class SourceImport(var limit: Int?, var remaining: Int?, var reset: Int?) : Parcelable
| 0 | null | 2 | 34 | 5b0a57429fe31479df80fdb3d567ae0c4795992c | 1,024 | MVVMBaseProject | Do What The F*ck You Want To Public License |
common/src/test/kotlin/com/ing/zkflow/common/transactions/ZKTransactionBuilderTest.kt | ing-bank | 550,239,957 | false | {"Kotlin": 1610321, "Shell": 1609} | package com.ing.zkflow.common.transactions
import com.ing.zkflow.testing.shouldHaveSamePublicApiAs
import net.corda.core.transactions.TransactionBuilder
import org.junit.Test
class ZKTransactionBuilderTest {
@Test
fun `Public API of ZKTransactionBuilder equals TransactionBuilder`() {
ZKTransactionBuilder::class.shouldHaveSamePublicApiAs(
TransactionBuilder::class,
listOf(
// "addOutputState",
"lockId", // Not clear what it is used for
"<init>" // constructors may be different
)
)
}
}
| 0 | Kotlin | 4 | 9 | f6e2524af124c1bdb2480f03bf907f6a44fa3c6c | 603 | zkflow | MIT License |
app/src/main/java/com/uit/food_delivery/core/utils/EventStatus.kt | ngoctienUIT | 684,983,399 | false | {"Kotlin": 230794} | package com.uit.food_delivery.core.utils
enum class EventStatus { LOADING, SUCCESS, ERROR } | 0 | Kotlin | 0 | 0 | 165c30192c6605174d9d9d66f1bc45402a6a7fab | 92 | FoodDelivery | MIT License |
Kotlin-Samples/src/main/kotlin/chapter3/Recipe5.kt | PacktPublishing | 126,314,798 | false | null | package chapter3
/**
* Chapter: Expressive functions and adjustable interfaces
* Recipe: Function composition
*/
fun main(vararg args: String) {
fun length(word: String) = word.length
fun isEven(x:Int): Boolean = x.rem(2) == 0
val isCharCountEven: (word: String) -> Boolean = ::length and ::isEven
print(isCharCountEven("pneumonoultramicroscopicsilicovolcanoconiosis"))
}
infix fun <P1, R, R2> ((P1) -> R).and(function: (R) -> R2): (P1) -> R2 = {
function(this(it))
} | 0 | Kotlin | 24 | 26 | a9118396250ded6f4466c20fd0dc62ea6a598ed1 | 492 | Kotlin-Standard-Library-Cookbook | MIT License |
compiler/src/main/kotlin/eu/nitok/jitsu/compiler/ast/TypeNode.kt | nbrugger-tgm | 683,089,096 | false | {"Kotlin": 135785, "TypeScript": 4002} | package eu.nitok.jitsu.compiler.ast
import eu.nitok.jitsu.compiler.model.BitSize
import eu.nitok.jitsu.compiler.parser.Range
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable;
@Serializable
sealed interface TypeNode : AstNode {
@Serializable
class IntTypeNode(val bitSize: BitSize, override val location: Range) : TypeNode, AstNodeImpl() {
override fun toString(): String {
return "i${bitSize.bits}"
}
override val children: List<AstNode>
get() = listOf()
}
@Serializable
class UIntTypeNode(val bitSize: BitSize, override val location: Range) : TypeNode, AstNodeImpl() {
override fun toString(): String {
return "u${bitSize.bits}"
}
override val children: List<AstNode>
get() = listOf()
}
@Serializable
class FloatTypeNode(val bitSize: BitSize, override val location: Range) : TypeNode, AstNodeImpl() {
override fun toString(): String {
return "f${bitSize.bits}"
}
override val children: List<AstNode>
get() = listOf()
}
@Serializable
class FunctionTypeSignatureNode(
val returnType: TypeNode?,
var parameters: List<StatementNode.FunctionDeclarationNode.ParameterNode>,
override val location: Range
) : TypeNode, AstNodeImpl() {
override val children: List<AstNode>
get() = parameters + listOfNotNull(returnType)
override fun toString(): String {
return "(${
parameters.joinToString(", ") { it.type?.toString() ?: "<invalid>" }
}) -> $returnType"
}
}
@Serializable
class ArrayTypeNode(
@SerialName("type_definition") val type: TypeNode,
val fixedSize: ExpressionNode?,
override val location: Range
) : TypeNode, AstNodeImpl() {
override val children: List<AstNode>
get() = listOfNotNull(type, fixedSize)
override fun toString(): String {
return "$type[${fixedSize?.toString() ?: ""}]"
}
}
/**
* This node is used when a type is referenced by name
* ```
* type MyType = OtherType
* var x: Element[]
* ```
* * In this example, `OtherType` and `Element` are NamedTypeNodes
*
* It might seem counter intuitive but this type is not [NamedTypeNode] by intent! Since it is only a "reference"
* to one! Given the example above `MyType` would be a [NamedTypeNode]
*/
@Serializable
class NameTypeNode(
val name: IdentifierNode,
val genericTypes: List<TypeNode>,
override val location: Range
) : TypeNode, AstNodeImpl() {
override fun toString(): String {
return "$name${if (genericTypes.isNotEmpty()) "<${genericTypes.joinToString(", ")}>" else ""}"
}
override val children: List<AstNode>
get() = genericTypes + name
}
@Serializable
data class UnionTypeNode(val types: List<TypeNode>) : TypeNode, AstNodeImpl() {
override val children: List<AstNode>
get() = types
init {
require(types.isNotEmpty()) {
"union types cannot be empty"
}
}
override val location: Range = types.first().location.rangeTo(types.last().location)
override fun toString(): String {
return types.joinToString(" | ")
}
}
@Serializable
class StructuralInterfaceTypeNode(
val fields: List<StructuralFieldNode>,
override val location: Range
) : TypeNode, AstNodeImpl() {
override val children: List<AstNode>
get() = fields
override fun toString(): String {
return "{${fields.joinToString(", ") { it.toString() }}}"
}
@Serializable
class StructuralFieldNode(
val name: IdentifierNode,
val type: TypeNode?
) : AstNodeImpl() {
override val location: Range = name.location.rangeTo(type?.location ?: name.location)
override fun toString(): String {
return "${name.value}: $type"
}
override val children: List<AstNode>
get() = listOfNotNull(name, type)
}
}
@Serializable
class ValueTypeNode(val value: ExpressionNode, override val location: Range) : TypeNode, AstNodeImpl() {
override fun toString(): String {
return value.toString()
}
override val children: List<AstNode>
get() = listOf(value)
}
@Serializable
class VoidTypeNode(override val location: Range) : TypeNode, AstNodeImpl() {
override val children: List<AstNode>
get() = listOf()
}
} | 0 | Kotlin | 0 | 0 | 89c549b28b5cacf39e75ab0cd5f8296ddd45c017 | 4,808 | jitsu | Apache License 2.0 |
composeApp/src/wasmJsMain/kotlin/augmy/interactive/com/ui/components/ActionBarIcon.kt | Let-s-build-something | 867,003,530 | false | {"Kotlin": 108818, "HTML": 2487, "JavaScript": 1633, "CSS": 690} | package augmy.interactive.com.ui.components
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Dashboard
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import augmy.interactive.shared.ui.theme.LocalTheme
import coil3.compose.AsyncImage
import org.jetbrains.compose.ui.tooling.preview.Preview
/**
* Basic icon with text, which is mainly designed for action bar, but could be used practically anywhere.
*
* The layout is constrained to both width and height.
*
* @param text text to be displayed under the icon
* @param imageVector icon to be displayed
* @param imageUrl url to remote image to be displayed, it is loaded with Coil and Ktor
* @param onClick event upon clicking on the layout
*/
@Composable
fun ActionBarIcon(
modifier: Modifier = Modifier,
text: String? = null,
imageVector: ImageVector? = null,
imageUrl: String? = null,
onClick: () -> Unit = {}
) {
Column(
modifier = Modifier
.padding(4.dp)
.heightIn(max = 64.0.dp, min = 42.dp)
.then(modifier)
.widthIn(min = 42.dp, max = 100.dp)
.clip(LocalTheme.current.shapes.rectangularActionShape)
.clickable {
onClick.invoke()
}
.padding(
vertical = if(text == null) 8.dp else 4.dp,
horizontal = if(text == null) 8.dp else 6.dp
)
.animateContentSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
when {
imageUrl.isNullOrBlank().not() -> {
AsyncImage(
modifier = Modifier
.clip(CircleShape)
.size(24.dp),
model = imageUrl,
contentDescription = text
)
}
imageVector != null -> {
Icon(
modifier = Modifier.size(24.dp),
imageVector = imageVector,
contentDescription = text,
tint = LocalTheme.current.colors.tetrial
)
}
}
AnimatedVisibility(visible = text != null) {
AutoResizeText(
modifier = Modifier
.wrapContentHeight()
.padding(top = 2.dp),
text = text ?: "",
color = LocalTheme.current.colors.tetrial,
fontWeight = FontWeight.Medium,
textAlign = TextAlign.Center,
maxLines = 1,
// some users tune up font size so high we can draw it otherwise
fontSizeRange = FontSizeRange(
min = 9.5.sp,
max = 14.sp
)
)
}
}
}
@Preview
@Composable
private fun Preview() {
ActionBarIcon(
text = "test action",
imageVector = Icons.Outlined.Dashboard
)
} | 0 | Kotlin | 0 | 1 | b352de83416659e791829eb89c464512e397d9ee | 3,959 | website-brand | Apache License 2.0 |
udp-server/src/main/kotlin/io/sparkled/udpserver/impl/subscriber/UdpClientSubscribers.kt | sparkled | 53,776,686 | false | null | package io.sparkled.udpserver.impl.subscriber
import java.net.InetAddress
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Singleton
@Singleton
class UdpClientSubscribers : ConcurrentHashMap<InetAddress, UdpClientSubscription>()
| 28 | Kotlin | 20 | 67 | 4696377313ed62a335b3f4393416c72fd320eb3e | 248 | sparkled | MIT License |
src/main/kotlin/me/zhiyao/bing/constant/ResponseCode.kt | WangZhiYao | 327,259,262 | false | null | package me.zhiyao.bing.constant
/**
*
* @author WangZhiYao
* @date 2021/1/6
*/
object ResponseCode {
const val SUCCESS = 1000
const val DATA_EMPTY = 1001
const val DATE_IS_NULL_OR_BLANK = 1002
const val DATE_FORMAT_INVALID = 1003
const val DATE_OUT_OF_RANGE = 1004
} | 0 | Kotlin | 0 | 0 | 463d192c5aead06bb40f8b86fe2e928a4dc9a0e9 | 297 | BingApi | MIT License |
app/src/main/java/com/elhady/movies/ui/base/BaseViewModel.kt | islamelhady | 301,591,032 | false | {"Kotlin": 397718} | package com.elhady.movies.ui.base
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.elhady.movies.domain.mappers.Mapper
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
abstract class BaseViewModel : ViewModel() {
abstract fun getData()
protected fun <T> tryToExecute(
call: suspend () -> T,
onSuccess: (T) -> Unit,
onError: (Throwable) -> Unit,
dispatcher: CoroutineDispatcher = Dispatchers.IO
) {
viewModelScope.launch(dispatcher) {
try {
call().also(onSuccess)
} catch (th: Throwable) {
onError(th)
}
}
}
protected fun <INPUT, OUTPUT> tryToExecute(
call: suspend () -> List<INPUT>,
onSuccess: (List<OUTPUT>) -> Unit,
mapper: Mapper<INPUT, OUTPUT>,
onError: (Throwable) -> Unit,
dispatcher: CoroutineDispatcher = Dispatchers.IO
) {
viewModelScope.launch(dispatcher) {
try {
mapper.map(call()).also(onSuccess)
} catch (th: Throwable) {
onError(th)
}
}
}
} | 1 | Kotlin | 0 | 0 | 11cca97dbb5e5358310fa75148a33110c6f3483b | 1,237 | movie-night-v2 | Apache License 2.0 |
BaseExtend/src/main/java/com/chen/baseextend/bean/mz/UserInfoBean.kt | chen397254698 | 268,411,455 | false | null | package com.chen.baseextend.bean.mz
import com.chen.basemodule.basem.BaseBean
/**
* Created by chen on 2019/7/12
**/
data class UserInfoBean(
val appId: Int?,
val avatar: String?,
val channelId: Int?,
val deviceId: String?,
val deviceName: String?,
val deviceType: Int?,
val gender: Int?,
val id: String?,
val inviteCode: String?,
val nickname: String?,
val createTime: String? = null,
val updateTime: String? = null,
val username: String?
) : BaseBean() | 1 | Kotlin | 14 | 47 | 85ffc5e307c6171767e14bbfaf992b8d62ec1cc6 | 563 | EasyAndroid | Apache License 2.0 |
src/main/kotlin/com/mnnit/moticlubs/dao/User.kt | CC-MNNIT | 583,707,830 | false | null | package com.mnnit.moticlubs.dao
import com.fasterxml.jackson.annotation.JsonProperty
import org.springframework.data.annotation.Id
data class User(
@Id
@JsonProperty("uid")
val uid: Long = System.currentTimeMillis(),
@JsonProperty("regNo")
val regno: String,
@JsonProperty("name")
val name: String,
@JsonProperty("email")
val email: String,
@JsonProperty("course")
val course: String,
@JsonProperty("phone")
val phone: String,
@JsonProperty("avatar")
val avatar: String,
)
| 0 | Kotlin | 2 | 0 | 46d547a95452f6f904d5cb0fb7c241c42f581951 | 541 | MotiClubs-Service | MIT License |
application/src/main/kotlin/no/nav/poao_tilgang/application/provider/DiskresjonskodeProviderImpl.kt | navikt | 491,417,288 | false | {"Kotlin": 318312, "Dockerfile": 95} | package no.nav.poao_tilgang.application.provider
import no.nav.poao_tilgang.application.client.pdl_pip.Adressebeskyttelse
import no.nav.poao_tilgang.application.client.pdl_pip.Gradering
import no.nav.poao_tilgang.application.client.pdl_pip.PdlPipClient
import no.nav.poao_tilgang.application.utils.SecureLog.secureLog
import no.nav.poao_tilgang.core.domain.Diskresjonskode
import no.nav.poao_tilgang.core.provider.DiskresjonskodeProvider
import org.springframework.stereotype.Service
@Service
class DiskresjonskodeProviderImpl(
private val pdlPipClient: PdlPipClient
) : DiskresjonskodeProvider {
override fun hentDiskresjonskode(norskIdent: String): Diskresjonskode? {
return pdlPipClient.hentBrukerInfo(norskIdent)
?.person
?.adressebeskyttelse?.firstOrNull()?.let { tilDiskresjonskode(it) }
.also {
secureLog.info("PdlPip , hentDiskresjonskode for fnr: $norskIdent, result: $it")
}
}
private fun tilDiskresjonskode(adressebeskyttelse: Adressebeskyttelse): Diskresjonskode {
return when(adressebeskyttelse.gradering) {
Gradering.FORTROLIG -> Diskresjonskode.FORTROLIG
Gradering.STRENGT_FORTROLIG -> Diskresjonskode.STRENGT_FORTROLIG
Gradering.STRENGT_FORTROLIG_UTLAND -> Diskresjonskode.STRENGT_FORTROLIG_UTLAND
}
}
}
| 7 | Kotlin | 4 | 0 | 7d299b4e5668e933419ed919ff2a57e4c6c3bea7 | 1,261 | poao-tilgang | MIT License |
src/pw/gerard/gsmelter/Action.kt | GerardSmit | 102,296,996 | false | {"Kotlin": 20969} | package pw.gerard.gsmelter
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.property.SimpleIntegerProperty
import pw.gerard.gsmelter.data.Output
import pw.gerard.gsmelter.data.Location
class Action(val bar: Output, val location: Location) {
val amount = SimpleIntegerProperty(0)
val done = SimpleBooleanProperty(false)
val active = SimpleBooleanProperty(false)
fun amountProperty(): SimpleIntegerProperty {
return amount
}
fun activeProperty(): SimpleIntegerProperty {
return amount
}
fun doneProperty(): SimpleBooleanProperty {
return done
}
} | 0 | Kotlin | 1 | 1 | fafa7b7e796790e98e4ce1abdec1f38dd818a7af | 631 | gSmelter | MIT License |
buildSrc/src/main/kotlin/Deps.kt | torresmi | 113,931,095 | false | null | package dependencies
object Deps {
object Coroutines : Group("org.jetbrains.kotlinx") {
val core = withArtifact("kotlinx-coroutines-core", Versions.coroutines)
val test = withArtifact("kotlinx-coroutines-test", Versions.coroutines)
}
object Kotest : Group("io.kotest") {
val assertions = withArtifact("kotest-assertions-core", Versions.kotest)
val property = withArtifact("kotest-property", Versions.kotest)
val runner = withArtifact("kotest-runner-junit5", Versions.kotest)
}
object Kotlin : Group("org.jetbrains.kotlin") {
val reflect = withArtifact("kotlin-reflect", Versions.kotlin)
}
}
// Can't use in kts files yet https://github.com/gradle/gradle/issues/9270
object Plugins {
val bintray = dependency("com.jfrog.bintray.gradle:gradle-bintray-plugin", Versions.bintray)
val dokka = dependency("org.jetbrains.dokka:dokka-gradle-plugin", Versions.dokka)
val kotlin = dependency("org.jetbrains.kotlin:kotlin-gradle-plugin", Versions.kotlin)
val maven = dependency("com.github.dcendents:android-maven-gradle-plugin", Versions.maven)
val versions = dependency("com.github.ben-manes:gradle-versions-plugin", Versions.versions)
}
abstract class Group(val group: String) {
fun withArtifact(artifact: String, version: String) = "$group:$artifact:$version"
}
private fun dependency(path: String, version: String) = "$path:$version"
object Versions {
val bintray = "1.8.5"
val coroutines = "1.4.2"
val dokka = "1.4.20"
val jacoco = "0.8.6"
val kotest = "4.4.0"
val kotlin = "1.4.30"
val maven = "1.4.1"
val versions = "0.36.0"
}
| 2 | Kotlin | 0 | 6 | cd09125dabd119a1a7d1e5d7a119734b6dd79956 | 1,659 | kotlin-remotedata | MIT License |
20_axon-avro-protocol/src/main/kotlin/CodeTalksDB.kt | jangalinski | 675,557,469 | false | {"Kotlin": 16615} | package io.github.jangalinski.talks
import io.github.jangalinski.talks.avro.CodeTalksTalk
object CodeTalksDB {
private val talks = listOf(
CodeTalksTalk(
"Introducing Event Sourcing into the Monolith: A Travelogue",
"Our 13-year-old Ruby on Rails app is well-maintained and stable boring. Dealing with many unstable vendors, networks, and co-workers, we’ve struggled to keep track of our processes within the application and maintain an audit trail. We’ve been applying patches to symptoms for too long. When we finally decided to pivot in 2020 and switched a core part of the application to Event Sourcing, we immediately felt the relief of a reliable, traceable process. We also learned our lessons in introducing a pattern like this to an existing app. And now, it’s time to share…"
),
CodeTalksTalk(
"Code to Cloud with the Azure Developer CLI",
"In this talk, Liam will demonstrate how you can take a napkin idea to a production ready system in just a few minutes using the Azure Developer CLI, Infrastructure as Code, GitHub Codespaces and GitHub Copilot. He will show how you can actively reduce the steps you need to take as a developer by using best practices when working on your project and as such speeding up your time to market, improving your DevOps lifecycle and reducing errors along the way. This is also the perfect opportunity to see one of the latest developer friendly CLI tools in action and how you can get hands on yourself."
)
)
fun findByKeyword(keyword: String) = talks.filter {
it.name.contains(keyword) || it.description.contains(keyword)
}
}
| 0 | Kotlin | 0 | 1 | 86d5d98008cc77378cb7e0c4a32531701fd47be2 | 1,630 | talk-kotlin-poet | Apache License 2.0 |
app/src/main/java/com/example/animation/ui/FAButton.kt | mitulvaghamshi | 555,615,565 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.animation.ui
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.*
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.Icon
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Edit
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.animation.R
/**
* Shows the floating action button.
*
* @param extended Whether the tab should be shown in its expanded state.
*/
// AnimatedVisibility is currently an experimental API in Compose Animation.
@Composable
fun FAButton(extended: Boolean, onClick: () -> Unit) {
// Use `FloatingActionButton` rather than `ExtendedFloatingActionButton` for full control on
// how it should animate.
FloatingActionButton(onClick) {
Row(Modifier.padding(horizontal = if (extended) 20.dp else 16.dp)) {
Icon(Icons.Default.Edit, null)
// Toggle the visibility of the content with animation.
AnimatedVisibility(extended) {
Text(
stringResource(R.string.edit),
Modifier.padding(start = 10.dp, top = 3.dp)
)
}
}
}
}
@Preview
@Composable
private fun PreviewFAButton() = Surface {
Column(Modifier.padding(10.dp)) {
FAButton(extended = false) {}
Spacer(modifier = Modifier.height(10.dp))
FAButton(extended = true) {}
}
}
| 0 | Kotlin | 0 | 0 | 082129c285d276adb55e21e40801662a47e19b5c | 2,340 | Animation | MIT License |
core-api/api/src/main/java/love/forte/simbot/thing/StructuralThingBuilder.kt | simple-robot | 554,852,615 | false | null | /*
*
* * Copyright (c) 2021. ForteScarlet All rights reserved.
* * Project simple-robot
* * File MiraiAvatar.kt
* *
* * You can contact the author through the following channels:
* * github https://github.com/ForteScarlet
* * gitee https://gitee.com/ForteScarlet
* * email <EMAIL>
* * QQ 1149159218
*
*/
@file:JvmName("StructuralThingBuilders")
package love.forte.simbot.thing
private typealias DSL = StructuralThingBuilderDSL
private typealias DSL_WN = StructuralThingWithNameBuilderDSL
@DslMarker
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY)
public annotation class StructuralThingBuilderDSL
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY)
public annotation class StructuralThingWithNameBuilderDSL
//// structural thing
@DSL
public fun <T> buildStructuralThing(
valueSupplier: (() -> T)? = null,
block: StructuralThingBuilder<T>.() -> Unit,
): StructuralThing<T> {
return StructuralThingBuilder(valueSupplier).apply(block).build()
}
@DSL
public fun <T> buildStructuralThing(
value: T,
block: StructuralThingBuilder<T>.() -> Unit,
): StructuralThing<T> {
return StructuralThingBuilder { value }.apply(block).build()
}
/**
* [StructuralThing]'s builder.
*
*/
@DSL
public class StructuralThingBuilder<T>(
private var valueSupplier: (() -> T)? = null,
) : ThingBuilder<T, StructuralThing<T>> {
constructor(value: T) : this({ value })
private val children = mutableListOf<StructuralThing<T>>()
val value: T get() = valueSupplier?.invoke() ?: throw IllegalStateException("Value was not init yet.")
@DSL
fun value(v: T) {
valueSupplier = { v }
}
@DSL
fun value(block: () -> T) {
valueSupplier = block
}
@DSL
fun child(child: StructuralThing<T>) {
children.add(child)
}
@DSL
fun child(
valueSupplier: (() -> T)? = null,
block: StructuralThingBuilder<T>.() -> Unit,
) {
children.add(buildStructuralThing(valueSupplier, block))
}
@DSL
fun child(
value: T,
block: (StructuralThingBuilder<T>.() -> Unit)? = null,
) {
block?.let { b -> children.add(buildStructuralThing(value, b)) } ?: children.add(thing(value, emptyList()))
}
override fun build(): StructuralThing<T> = thing(
value = requireNotNull(valueSupplier) { "Required 'value' was not init." }(),
children = children.ifEmpty { emptyList() }
)
}
//// structural thing with name
@DSL_WN
public fun <T> buildStructuralThing(
name: String? = null,
valueSupplier: (() -> T)? = null,
block: StructuralThingWithNameBuilder<T>.() -> Unit,
): StructuralThingWithName<T> {
return StructuralThingWithNameBuilder(name, valueSupplier).apply(block).build()
}
@DSL_WN
public fun <T> buildStructuralThing(
name: String? = null,
value: T,
block: StructuralThingWithNameBuilder<T>.() -> Unit,
): StructuralThingWithName<T> {
return StructuralThingWithNameBuilder(name = name, valueSupplier = { value }).apply(block).build()
}
/**
* [StructuralThing]'s builder.
*
*/
@DSL_WN
public class StructuralThingWithNameBuilder<T>(
@DSL_WN
var name: String? = null,
private var valueSupplier: (() -> T)? = null,
) : ThingBuilder<T, StructuralThingWithName<T>> {
constructor(name: String?, value: T) : this(name, { value })
constructor(value: T) : this(valueSupplier = { value })
private val children = mutableListOf<StructuralThingWithName<T>>()
val value: T get() = valueSupplier?.invoke() ?: throw IllegalStateException("Value was not init yet.")
@DSL_WN
fun value(v: T) {
valueSupplier = { v }
}
@DSL_WN
fun value(block: () -> T) {
valueSupplier = block
}
@DSL_WN
fun child(child: StructuralThingWithName<T>) {
children.add(child)
}
@DSL_WN
fun child(
name: String? = null,
valueSupplier: (() -> T)? = null,
block: StructuralThingWithNameBuilder<T>.() -> Unit,
) {
children.add(buildStructuralThing(name, valueSupplier, block))
}
@DSL_WN
fun child(
name: String? = null,
value: T,
block: (StructuralThingWithNameBuilder<T>.() -> Unit)? = null,
) {
block?.let { b -> children.add(buildStructuralThing(name, value, b)) } ?: children.add(thing(
name = requireNotNull(name) { "Required 'name' was null." },
value = value,
emptyList()))
}
override fun build(): StructuralThingWithName<T> = thing(
name = requireNotNull(name) { "Required 'name' was null." },
value = requireNotNull(valueSupplier) { "Required 'value' was not init." }(),
children = children.ifEmpty { emptyList() }
)
}
| 0 | Kotlin | 0 | 3 | c5d7c9ca8c81b2bddc250090739d7c7d0c110328 | 4,840 | simple-robot-v2 | Apache License 2.0 |
app/src/main/java/com/replica/replicaisland/InputGameInterface.kt | jimandreas | 290,957,495 | false | {"Kotlin": 1118505, "JavaScript": 10582} | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("VARIABLE_WITH_REDUNDANT_INITIALIZER", "SameParameterValue")
package com.replica.replicaisland
import android.view.KeyEvent
import kotlin.math.abs
import kotlin.math.max
class InputGameInterface : BaseObject() {
val jumpButton = InputButton()
val attackButton = InputButton()
val directionalPad = InputXY()
val tilt = InputXY()
private var leftKeyCode = KeyEvent.KEYCODE_DPAD_LEFT
private var rightKeyCode = KeyEvent.KEYCODE_DPAD_RIGHT
private var jumpKeyCode = KeyEvent.KEYCODE_SPACE
private var attackKeyCode = KeyEvent.KEYCODE_SHIFT_LEFT
private val orientationDeadZoneMin = ORIENTATION_DEAD_ZONE_MIN
private val orientationDeadZoneMax = ORIENTATION_DEAD_ZONE_MAX
private val orientationDeadZoneScale = ORIENTATION_DEAD_ZONE_SCALE
private var orientationSensitivity = 1.0f
private var orientationSensitivityFactor = 1.0f
private var movementSensitivity = 1.0f
private var useClickButtonForAttack = true
private var useOrientationForMovement = false
private var useOnScreenControls = false
private var lastRollTime = 0f
override fun reset() {
jumpButton.release()
attackButton.release()
directionalPad.release()
tilt.release()
}
override fun update(timeDelta: Float, parent: BaseObject?) {
val input = sSystemRegistry.inputSystem
val keys = input!!.fetchKeyboard().keys
val orientation = input.fetchOrientationSensor()
// tilt is easy
tilt.clone(orientation)
val touch = input.fetchTouchScreen()
val gameTime = sSystemRegistry.timeSystem!!.gameTime
var sliderOffset = 0f
// update movement inputs
if (useOnScreenControls) {
val sliderTouch = touch.findPointerInRegion(
ButtonConstants.MOVEMENT_SLIDER_REGION_X.toFloat(),
ButtonConstants.MOVEMENT_SLIDER_REGION_Y.toFloat(),
ButtonConstants.MOVEMENT_SLIDER_REGION_WIDTH.toFloat(),
ButtonConstants.MOVEMENT_SLIDER_REGION_HEIGHT.toFloat())
if (sliderTouch != null) {
val halfWidth = ButtonConstants.MOVEMENT_SLIDER_BAR_WIDTH / 2.0f
val center = ButtonConstants.MOVEMENT_SLIDER_X + halfWidth
val offset = sliderTouch.retreiveXaxisMagnitude() - center
val magnitudeRamp = if (abs(offset) > halfWidth) 1.0f else abs(offset) / halfWidth
val magnitude = magnitudeRamp * Utils.sign(offset) * SLIDER_FILTER * movementSensitivity
sliderOffset = magnitudeRamp * Utils.sign(offset)
directionalPad.press(gameTime, magnitude, 0.0f)
} else {
directionalPad.release()
}
} else if (useOrientationForMovement) {
directionalPad.clone(orientation)
directionalPad.setMagnitude(
filterOrientationForMovement(orientation.retreiveXaxisMagnitude()),
filterOrientationForMovement(orientation.retreiveYaxisMagnitude()))
} else {
// keys or trackball
val trackball = input.fetchTrackball()
val left = keys[leftKeyCode]
val right = keys[rightKeyCode]
val leftPressedTime = left!!.lastPressedTime
val rightPressedTime = right!!.lastPressedTime
if (trackball.lastPressedTime > max(leftPressedTime, rightPressedTime)) {
// The trackball never goes "up", so force it to turn off if it wasn't triggered in the last frame.
// What follows is a bunch of code to filter trackball events into something like a dpad event.
// The goals here are:
// - For roll events that occur in quick succession to accumulate.
// - For roll events that occur with more time between them, lessen the impact of older events
// - In the absence of roll events, fade the roll out over time.
if (gameTime - trackball.lastPressedTime < ROLL_TIMEOUT) {
val newX: Float
val newY: Float
val delay = max(ROLL_RESET_DELAY, timeDelta)
if (gameTime - lastRollTime <= delay) {
newX = directionalPad.retreiveXaxisMagnitude() + trackball.retreiveXaxisMagnitude() * ROLL_FILTER * movementSensitivity
newY = directionalPad.retreiveYaxisMagnitude() + trackball.retreiveYaxisMagnitude() * ROLL_FILTER * movementSensitivity
} else {
val oldX = if (directionalPad.retreiveXaxisMagnitude() != 0.0f) directionalPad.retreiveXaxisMagnitude() / 2.0f else 0.0f
val oldY = if (directionalPad.retreiveXaxisMagnitude() != 0.0f) directionalPad.retreiveXaxisMagnitude() / 2.0f else 0.0f
newX = oldX + trackball.retreiveXaxisMagnitude() * ROLL_FILTER * movementSensitivity
newY = oldY + trackball.retreiveXaxisMagnitude() * ROLL_FILTER * movementSensitivity
}
directionalPad.press(gameTime, newX, newY)
lastRollTime = gameTime
trackball.release()
} else {
var x = directionalPad.retreiveXaxisMagnitude()
var y = directionalPad.retreiveYaxisMagnitude()
if (x != 0.0f) {
val sign = Utils.sign(x)
x -= sign * ROLL_DECAY * timeDelta
if (Utils.sign(x) != sign) {
x = 0.0f
}
}
if (y != 0.0f) {
val sign = Utils.sign(y)
y -= sign * ROLL_DECAY * timeDelta
if (Utils.sign(x) != sign) {
y = 0.0f
}
}
if (x == 0f && y == 0f) {
directionalPad.release()
} else {
directionalPad.setMagnitude(x, y)
}
}
} else {
var xMagnitude = 0.0f
val yMagnitude = 0.0f
var pressTime = 0.0f
// left and right are mutually exclusive
if (leftPressedTime > rightPressedTime) {
xMagnitude = -left.magnitude * KEY_FILTER * movementSensitivity
pressTime = leftPressedTime
} else {
xMagnitude = right.magnitude * KEY_FILTER * movementSensitivity
pressTime = rightPressedTime
}
if (xMagnitude != 0.0f) {
directionalPad.press(pressTime, xMagnitude, yMagnitude)
} else {
directionalPad.release()
}
}
}
// update other buttons
val jumpKey = keys[jumpKeyCode]
// when on-screen movement controls are on, the fly and attack buttons are flipped.
var flyButtonRegionX = ButtonConstants.FLY_BUTTON_REGION_X.toFloat()
var stompButtonRegionX = ButtonConstants.STOMP_BUTTON_REGION_X.toFloat()
if (useOnScreenControls) {
val params = sSystemRegistry.contextParameters
flyButtonRegionX = params!!.gameWidth - ButtonConstants.FLY_BUTTON_REGION_WIDTH - ButtonConstants.FLY_BUTTON_REGION_X.toFloat()
stompButtonRegionX = params.gameWidth - ButtonConstants.STOMP_BUTTON_REGION_WIDTH - ButtonConstants.STOMP_BUTTON_REGION_X.toFloat()
}
val jumpTouch = touch.findPointerInRegion(
flyButtonRegionX,
ButtonConstants.FLY_BUTTON_REGION_Y.toFloat(),
ButtonConstants.FLY_BUTTON_REGION_WIDTH.toFloat(),
ButtonConstants.FLY_BUTTON_REGION_HEIGHT.toFloat())
if (jumpKey!!.pressed) {
jumpButton.press(jumpKey.lastPressedTime, jumpKey.magnitude)
} else if (jumpTouch != null) {
if (!jumpButton.pressed) {
jumpButton.press(jumpTouch.lastPressedTime, 1.0f)
}
} else {
jumpButton.release()
}
val attackKey = keys[attackKeyCode]
val clickButton = keys[KeyEvent.KEYCODE_DPAD_CENTER] // special case
val stompTouch = touch.findPointerInRegion(
stompButtonRegionX,
ButtonConstants.STOMP_BUTTON_REGION_Y.toFloat(),
ButtonConstants.STOMP_BUTTON_REGION_WIDTH.toFloat(),
ButtonConstants.STOMP_BUTTON_REGION_HEIGHT.toFloat())
if (useClickButtonForAttack && clickButton!!.pressed) {
attackButton.press(clickButton.lastPressedTime, clickButton.magnitude)
} else if (attackKey!!.pressed) {
attackButton.press(attackKey.lastPressedTime, attackKey.magnitude)
} else if (stompTouch != null) {
// Since touch events come in constantly, we only want to press the attack button
// here if it's not already down. That makes it act like the other buttons (down once then up).
if (!attackButton.pressed) {
attackButton.press(stompTouch.lastPressedTime, 1.0f)
}
} else {
attackButton.release()
}
// This doesn't seem like exactly the right place to write to the HUD, but on the other hand,
// putting this code elsewhere causes dependencies between exact HUD content and physics, which
// we sometimes wish to avoid.
val hud = sSystemRegistry.hudSystem
if (hud != null) {
hud.setButtonState(jumpButton.pressed, attackButton.pressed, directionalPad.pressed)
hud.setMovementSliderOffset(sliderOffset)
}
}
private fun filterOrientationForMovement(magnitude: Float): Float {
val scaledMagnitude = magnitude * orientationSensitivityFactor
return deadZoneFilter(scaledMagnitude, orientationDeadZoneMin, orientationDeadZoneMax, orientationDeadZoneScale)
}
private fun deadZoneFilter(magnitude: Float, minVal: Float, maxVal: Float, scale: Float): Float {
var smoothedMagnatude = magnitude
if (abs(magnitude) < minVal) {
smoothedMagnatude = 0.0f // dead zone
} else if (abs(magnitude) < maxVal) {
smoothedMagnatude *= scale
}
return smoothedMagnatude
}
fun setKeys(left: Int, right: Int, jump: Int, attack: Int) {
leftKeyCode = left
rightKeyCode = right
jumpKeyCode = jump
attackKeyCode = attack
}
fun setUseClickForAttack(click: Boolean) {
useClickButtonForAttack = click
}
fun setUseOrientationForMovement(orientation: Boolean) {
useOrientationForMovement = orientation
}
fun setOrientationMovementSensitivity(sensitivity: Float) {
orientationSensitivity = sensitivity
orientationSensitivityFactor = 2.9f * sensitivity + 0.1f
}
fun setMovementSensitivity(sensitivity: Float) {
movementSensitivity = sensitivity
}
fun setUseOnScreenControls(onscreen: Boolean) {
useOnScreenControls = onscreen
}
companion object {
private const val ORIENTATION_DEAD_ZONE_MIN = 0.03f
private const val ORIENTATION_DEAD_ZONE_MAX = 0.1f
private const val ORIENTATION_DEAD_ZONE_SCALE = 0.75f
private const val ROLL_TIMEOUT = 0.1f
private const val ROLL_RESET_DELAY = 0.075f
// Raw trackball input is filtered by this value. Increasing it will
// make the control more twitchy, while decreasing it will make the control more precise.
private const val ROLL_FILTER = 0.4f
private const val ROLL_DECAY = 8.0f
private const val KEY_FILTER = 0.25f
private const val SLIDER_FILTER = 0.25f
}
init {
reset()
}
} | 0 | Kotlin | 1 | 3 | e229b5b75d4f9821af8a9164a0b37d51c93a44a9 | 12,673 | ReplicaIslandKotlin | Apache License 2.0 |
app/src/main/java/com/replica/replicaisland/InputGameInterface.kt | jimandreas | 290,957,495 | false | {"Kotlin": 1118505, "JavaScript": 10582} | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("VARIABLE_WITH_REDUNDANT_INITIALIZER", "SameParameterValue")
package com.replica.replicaisland
import android.view.KeyEvent
import kotlin.math.abs
import kotlin.math.max
class InputGameInterface : BaseObject() {
val jumpButton = InputButton()
val attackButton = InputButton()
val directionalPad = InputXY()
val tilt = InputXY()
private var leftKeyCode = KeyEvent.KEYCODE_DPAD_LEFT
private var rightKeyCode = KeyEvent.KEYCODE_DPAD_RIGHT
private var jumpKeyCode = KeyEvent.KEYCODE_SPACE
private var attackKeyCode = KeyEvent.KEYCODE_SHIFT_LEFT
private val orientationDeadZoneMin = ORIENTATION_DEAD_ZONE_MIN
private val orientationDeadZoneMax = ORIENTATION_DEAD_ZONE_MAX
private val orientationDeadZoneScale = ORIENTATION_DEAD_ZONE_SCALE
private var orientationSensitivity = 1.0f
private var orientationSensitivityFactor = 1.0f
private var movementSensitivity = 1.0f
private var useClickButtonForAttack = true
private var useOrientationForMovement = false
private var useOnScreenControls = false
private var lastRollTime = 0f
override fun reset() {
jumpButton.release()
attackButton.release()
directionalPad.release()
tilt.release()
}
override fun update(timeDelta: Float, parent: BaseObject?) {
val input = sSystemRegistry.inputSystem
val keys = input!!.fetchKeyboard().keys
val orientation = input.fetchOrientationSensor()
// tilt is easy
tilt.clone(orientation)
val touch = input.fetchTouchScreen()
val gameTime = sSystemRegistry.timeSystem!!.gameTime
var sliderOffset = 0f
// update movement inputs
if (useOnScreenControls) {
val sliderTouch = touch.findPointerInRegion(
ButtonConstants.MOVEMENT_SLIDER_REGION_X.toFloat(),
ButtonConstants.MOVEMENT_SLIDER_REGION_Y.toFloat(),
ButtonConstants.MOVEMENT_SLIDER_REGION_WIDTH.toFloat(),
ButtonConstants.MOVEMENT_SLIDER_REGION_HEIGHT.toFloat())
if (sliderTouch != null) {
val halfWidth = ButtonConstants.MOVEMENT_SLIDER_BAR_WIDTH / 2.0f
val center = ButtonConstants.MOVEMENT_SLIDER_X + halfWidth
val offset = sliderTouch.retreiveXaxisMagnitude() - center
val magnitudeRamp = if (abs(offset) > halfWidth) 1.0f else abs(offset) / halfWidth
val magnitude = magnitudeRamp * Utils.sign(offset) * SLIDER_FILTER * movementSensitivity
sliderOffset = magnitudeRamp * Utils.sign(offset)
directionalPad.press(gameTime, magnitude, 0.0f)
} else {
directionalPad.release()
}
} else if (useOrientationForMovement) {
directionalPad.clone(orientation)
directionalPad.setMagnitude(
filterOrientationForMovement(orientation.retreiveXaxisMagnitude()),
filterOrientationForMovement(orientation.retreiveYaxisMagnitude()))
} else {
// keys or trackball
val trackball = input.fetchTrackball()
val left = keys[leftKeyCode]
val right = keys[rightKeyCode]
val leftPressedTime = left!!.lastPressedTime
val rightPressedTime = right!!.lastPressedTime
if (trackball.lastPressedTime > max(leftPressedTime, rightPressedTime)) {
// The trackball never goes "up", so force it to turn off if it wasn't triggered in the last frame.
// What follows is a bunch of code to filter trackball events into something like a dpad event.
// The goals here are:
// - For roll events that occur in quick succession to accumulate.
// - For roll events that occur with more time between them, lessen the impact of older events
// - In the absence of roll events, fade the roll out over time.
if (gameTime - trackball.lastPressedTime < ROLL_TIMEOUT) {
val newX: Float
val newY: Float
val delay = max(ROLL_RESET_DELAY, timeDelta)
if (gameTime - lastRollTime <= delay) {
newX = directionalPad.retreiveXaxisMagnitude() + trackball.retreiveXaxisMagnitude() * ROLL_FILTER * movementSensitivity
newY = directionalPad.retreiveYaxisMagnitude() + trackball.retreiveYaxisMagnitude() * ROLL_FILTER * movementSensitivity
} else {
val oldX = if (directionalPad.retreiveXaxisMagnitude() != 0.0f) directionalPad.retreiveXaxisMagnitude() / 2.0f else 0.0f
val oldY = if (directionalPad.retreiveXaxisMagnitude() != 0.0f) directionalPad.retreiveXaxisMagnitude() / 2.0f else 0.0f
newX = oldX + trackball.retreiveXaxisMagnitude() * ROLL_FILTER * movementSensitivity
newY = oldY + trackball.retreiveXaxisMagnitude() * ROLL_FILTER * movementSensitivity
}
directionalPad.press(gameTime, newX, newY)
lastRollTime = gameTime
trackball.release()
} else {
var x = directionalPad.retreiveXaxisMagnitude()
var y = directionalPad.retreiveYaxisMagnitude()
if (x != 0.0f) {
val sign = Utils.sign(x)
x -= sign * ROLL_DECAY * timeDelta
if (Utils.sign(x) != sign) {
x = 0.0f
}
}
if (y != 0.0f) {
val sign = Utils.sign(y)
y -= sign * ROLL_DECAY * timeDelta
if (Utils.sign(x) != sign) {
y = 0.0f
}
}
if (x == 0f && y == 0f) {
directionalPad.release()
} else {
directionalPad.setMagnitude(x, y)
}
}
} else {
var xMagnitude = 0.0f
val yMagnitude = 0.0f
var pressTime = 0.0f
// left and right are mutually exclusive
if (leftPressedTime > rightPressedTime) {
xMagnitude = -left.magnitude * KEY_FILTER * movementSensitivity
pressTime = leftPressedTime
} else {
xMagnitude = right.magnitude * KEY_FILTER * movementSensitivity
pressTime = rightPressedTime
}
if (xMagnitude != 0.0f) {
directionalPad.press(pressTime, xMagnitude, yMagnitude)
} else {
directionalPad.release()
}
}
}
// update other buttons
val jumpKey = keys[jumpKeyCode]
// when on-screen movement controls are on, the fly and attack buttons are flipped.
var flyButtonRegionX = ButtonConstants.FLY_BUTTON_REGION_X.toFloat()
var stompButtonRegionX = ButtonConstants.STOMP_BUTTON_REGION_X.toFloat()
if (useOnScreenControls) {
val params = sSystemRegistry.contextParameters
flyButtonRegionX = params!!.gameWidth - ButtonConstants.FLY_BUTTON_REGION_WIDTH - ButtonConstants.FLY_BUTTON_REGION_X.toFloat()
stompButtonRegionX = params.gameWidth - ButtonConstants.STOMP_BUTTON_REGION_WIDTH - ButtonConstants.STOMP_BUTTON_REGION_X.toFloat()
}
val jumpTouch = touch.findPointerInRegion(
flyButtonRegionX,
ButtonConstants.FLY_BUTTON_REGION_Y.toFloat(),
ButtonConstants.FLY_BUTTON_REGION_WIDTH.toFloat(),
ButtonConstants.FLY_BUTTON_REGION_HEIGHT.toFloat())
if (jumpKey!!.pressed) {
jumpButton.press(jumpKey.lastPressedTime, jumpKey.magnitude)
} else if (jumpTouch != null) {
if (!jumpButton.pressed) {
jumpButton.press(jumpTouch.lastPressedTime, 1.0f)
}
} else {
jumpButton.release()
}
val attackKey = keys[attackKeyCode]
val clickButton = keys[KeyEvent.KEYCODE_DPAD_CENTER] // special case
val stompTouch = touch.findPointerInRegion(
stompButtonRegionX,
ButtonConstants.STOMP_BUTTON_REGION_Y.toFloat(),
ButtonConstants.STOMP_BUTTON_REGION_WIDTH.toFloat(),
ButtonConstants.STOMP_BUTTON_REGION_HEIGHT.toFloat())
if (useClickButtonForAttack && clickButton!!.pressed) {
attackButton.press(clickButton.lastPressedTime, clickButton.magnitude)
} else if (attackKey!!.pressed) {
attackButton.press(attackKey.lastPressedTime, attackKey.magnitude)
} else if (stompTouch != null) {
// Since touch events come in constantly, we only want to press the attack button
// here if it's not already down. That makes it act like the other buttons (down once then up).
if (!attackButton.pressed) {
attackButton.press(stompTouch.lastPressedTime, 1.0f)
}
} else {
attackButton.release()
}
// This doesn't seem like exactly the right place to write to the HUD, but on the other hand,
// putting this code elsewhere causes dependencies between exact HUD content and physics, which
// we sometimes wish to avoid.
val hud = sSystemRegistry.hudSystem
if (hud != null) {
hud.setButtonState(jumpButton.pressed, attackButton.pressed, directionalPad.pressed)
hud.setMovementSliderOffset(sliderOffset)
}
}
private fun filterOrientationForMovement(magnitude: Float): Float {
val scaledMagnitude = magnitude * orientationSensitivityFactor
return deadZoneFilter(scaledMagnitude, orientationDeadZoneMin, orientationDeadZoneMax, orientationDeadZoneScale)
}
private fun deadZoneFilter(magnitude: Float, minVal: Float, maxVal: Float, scale: Float): Float {
var smoothedMagnatude = magnitude
if (abs(magnitude) < minVal) {
smoothedMagnatude = 0.0f // dead zone
} else if (abs(magnitude) < maxVal) {
smoothedMagnatude *= scale
}
return smoothedMagnatude
}
fun setKeys(left: Int, right: Int, jump: Int, attack: Int) {
leftKeyCode = left
rightKeyCode = right
jumpKeyCode = jump
attackKeyCode = attack
}
fun setUseClickForAttack(click: Boolean) {
useClickButtonForAttack = click
}
fun setUseOrientationForMovement(orientation: Boolean) {
useOrientationForMovement = orientation
}
fun setOrientationMovementSensitivity(sensitivity: Float) {
orientationSensitivity = sensitivity
orientationSensitivityFactor = 2.9f * sensitivity + 0.1f
}
fun setMovementSensitivity(sensitivity: Float) {
movementSensitivity = sensitivity
}
fun setUseOnScreenControls(onscreen: Boolean) {
useOnScreenControls = onscreen
}
companion object {
private const val ORIENTATION_DEAD_ZONE_MIN = 0.03f
private const val ORIENTATION_DEAD_ZONE_MAX = 0.1f
private const val ORIENTATION_DEAD_ZONE_SCALE = 0.75f
private const val ROLL_TIMEOUT = 0.1f
private const val ROLL_RESET_DELAY = 0.075f
// Raw trackball input is filtered by this value. Increasing it will
// make the control more twitchy, while decreasing it will make the control more precise.
private const val ROLL_FILTER = 0.4f
private const val ROLL_DECAY = 8.0f
private const val KEY_FILTER = 0.25f
private const val SLIDER_FILTER = 0.25f
}
init {
reset()
}
} | 0 | Kotlin | 1 | 3 | e229b5b75d4f9821af8a9164a0b37d51c93a44a9 | 12,673 | ReplicaIslandKotlin | Apache License 2.0 |
functional-monads-probabilistic/src/main/java/com/github/alexandrepiveteau/functional/monads/experimental/probabilistic/Distribution.common.kt | alexandrepiveteau | 147,100,253 | false | null | /*
* MIT License
*
* Copyright (c) 2018 Alexandre Piveteau
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.github.alexandrepiveteau.functional.monads.experimental.probabilistic
fun <O1, O2> Distribution<O1>.map(f: (O1) -> O2): Distribution<O2> =
Distribution { f(this.sample()) }
fun <O1, O2> Distribution<O1>.flatMap(f: (O1) -> Distribution<O2>): Distribution<O2> =
f(this.sample())
fun <O1, O2> Distribution<O1>.zip2(a: Distribution<O2>): Distribution<Pair<O1, O2>> =
flatMap { o1 -> a.map { o2 -> o1 to o2 } }
fun <O1, O2, O3> Distribution<O1>.zip3(a: Distribution<O2>, b: Distribution<O3>): Distribution<Triple<O1, O2, O3>> =
flatMap { o1 -> a.flatMap { o2 -> b.map { o3 -> Triple(o1, o2, o3) } } }
fun <O: Any> Distribution<O>.toSequence(): Sequence<O> =
generateSequence { sample() } | 0 | Kotlin | 0 | 9 | e527823cb1bcda57fa0b66c32d29d3b9d4cee0e2 | 1,881 | functional-kotlin | MIT License |
multiplatform-mvp/src/commonTest/kotlin/com/olekdia/mvp/FacadeTest.kt | Albul | 240,083,754 | false | null | package com.olekdia.mvp
import com.olekdia.mvp.mocks.*
import kotlin.test.*
class FacadeTest : BaseTest() {
@Test
fun `load() new model factory - old model destroyed, new model available`() {
val modelBefore: IMockModel = modelProvider.getOrCreate(IMockModel.COMPONENT_ID)
assertEquals("Real model string", modelBefore.getModelString())
facade.load(modelFactories = arrayOf(IMockModel.COMPONENT_ID to { MockModelFake() }))
assertEquals(1, modelBefore.onDestroyCalled)
val modelAfter: IMockModel = modelProvider.getOrCreate(IMockModel.COMPONENT_ID)
assertNotSame(modelBefore, modelAfter)
assertEquals("Fake model string", modelAfter.getModelString())
}
@Test
fun `load() new components factory - old components destroyed, new components available`() {
val compBefore: MockPlatformManager = platformProvider.getOrCreate(IMockPlatformManager.COMPONENT_ID)
val mockOfMock = MockPlatformManager("Deb")
facade.load(platformFactories = arrayOf(IMockPlatformManager.COMPONENT_ID to { mockOfMock }))
assertEquals(1, compBefore.onDestroyCalled)
val compAfter: MockPlatformManager = platformProvider.getOrCreate(IMockPlatformManager.COMPONENT_ID)
assertNotSame(compBefore, compAfter)
assertEquals("Lin", compBefore.param)
assertEquals("Deb", compAfter.param)
assertSame(mockOfMock, compAfter)
val compAfter2: MockPlatformManager = platformProvider.getOrCreate(IMockPlatformManager.COMPONENT_ID)
assertSame(mockOfMock, compAfter2)
}
@Test
fun `unload() presenter - presenters with any params not available any more`() {
val presenter: IMockPresenter = presenterProvider.getOrCreate(IMockPresenter.COMPONENT_ID)
val presenter1: IMockPresenter = presenterProvider.getOrCreate(IMockPresenter.COMPONENT_ID, "1")
val presenter2: IMockPresenter = presenterProvider.getOrCreate(IMockPresenter.COMPONENT_ID, "2")
facade.unload(presenterIds = arrayOf(IMockPresenter.COMPONENT_ID))
assertFailsWith(NoSuchElementException::class) {
presenterProvider.getOrCreate<IMockPresenter>(IMockPresenter.COMPONENT_ID)
}
assertFailsWith(NoSuchElementException::class) {
presenterProvider.getOrCreate<IMockPresenter>(IMockPresenter.COMPONENT_ID, "1")
}
assertFailsWith(NoSuchElementException::class) {
presenterProvider.getOrCreate<IMockPresenter>(IMockPresenter.COMPONENT_ID, "2")
}
assertEquals(1, presenter.onDestroyCalled)
assertEquals(1, presenter1.onDestroyCalled)
assertEquals(1, presenter2.onDestroyCalled)
}
} | 0 | Kotlin | 0 | 1 | ea135bdc0b7b91a698780b9fd1e5bc896b095109 | 2,715 | multiplatform-mvp | Apache License 2.0 |
DemoApp/app/src/main/java/com/chen/fakevibrato/ui/my/presenter/EditNormalPresenter.kt | XLsn0w | 217,950,780 | false | {"Java": 789969, "Kotlin": 81798} | package com.chen.fakevibrato.ui.my.presenter
import com.chen.fakevibrato.ui.my.contract.EditNormalContract
/**
* @author Created by CHEN on 2019/8/18
* @email <EMAIL>
*/
class EditNormalPresenter : EditNormalContract.Presenter() {
} | 1 | Java | 2 | 1 | e197f85c2c4059eceebdd4edb6583afe42fcdd5b | 237 | Android | MIT License |
shared-test/src/main/java/com/koleff/kare_android/authentication/data/TokenDataStoreFake.kt | MartinKoleff | 741,013,199 | false | {"Kotlin": 1413112} | package com.koleff.kare_android.authentication.data
import com.koleff.kare_android.common.preferences.TokenDataStore
import com.koleff.kare_android.data.model.dto.Tokens
class TokenDataStoreFake: TokenDataStore {
private var tokens: Tokens? = null
var isCleared = false
private set
override fun getTokens(): Tokens? {
return tokens
}
override fun updateTokens(tokens: Tokens) {
this.tokens = tokens
isCleared = false
}
override fun deleteTokens() {
tokens = null
isCleared = true
}
} | 23 | Kotlin | 0 | 4 | 4ad6b9f320ff60e05b453375b9b855bd3e4a3483 | 568 | KareFitnessApp | MIT License |
lang/test/org/partiql/lang/syntax/SqlParserDateTimeTests.kt | slim-patchy | 361,615,421 | true | {"Kotlin": 2300133, "HTML": 99272, "Shell": 8944, "Java": 1352} | package org.partiql.lang.syntax
import com.amazon.ion.IonValue
import junitparams.Parameters
import org.junit.Test
import org.partiql.lang.domains.PartiqlAst
import org.partiql.lang.domains.id
import java.util.*
import org.partiql.lang.errors.ErrorCode
import org.partiql.lang.errors.Property
import org.partiql.lang.util.softAssert
import org.partiql.lang.util.to
import java.time.Instant
import java.time.ZoneOffset
class SqlParserDateTimeTests : SqlParserTestBase() {
private val LOCAL_TIME_ZONE_OFFSET = (ZoneOffset.systemDefault().rules.getOffset(Instant.now()).totalSeconds / 60).toLong()
data class DateTimeTestCase(val source: String, val block: PartiqlAst.Builder.() -> PartiqlAst.PartiqlAstNode)
private data class Date(val year: Int, val month: Int, val day: Int)
private val MONTHS_WITH_31_DAYS = listOf(1, 3, 5, 7, 8, 10, 12)
private val RANDOM_GENERATOR = generateRandomSeed()
private val RANDOM_DATES = List(500) { RANDOM_GENERATOR.nextDate() }
@Test
@Parameters
fun dateLiteralTests(tc: DateTimeTestCase) = assertExpression(tc.source, tc.block)
fun parametersForDateLiteralTests() = listOf(
DateTimeTestCase("DATE '2012-02-29'") {
date(2012, 2, 29)
},
DateTimeTestCase("DATE'1992-11-30'") {
date(1992, 11, 30)
},
DateTimeTestCase("DATE '9999-03-01'") {
date(9999, 3, 1)
},
DateTimeTestCase("DATE '0000-01-01'") {
date(0, 1, 1)
},
DateTimeTestCase("DATE '0000-02-29'") {
date(0, 2, 29)
},
DateTimeTestCase("DATE '0000-02-29'") {
date(0, 2, 29)
},
DateTimeTestCase("SELECT DATE '2021-03-10' FROM foo") {
select(
project = projectList(projectExpr(date(2021, 3, 10))),
from = scan(id("foo"))
)
},
DateTimeTestCase("TIME '02:30:59'") {
litTime(timeValue(2, 30, 59, 0, 9, null))
},
DateTimeTestCase("TIME (3) '12:59:31'") {
litTime(timeValue(12, 59, 31, 0, 3, null))
},
DateTimeTestCase("TIME '23:59:59.9999'") {
litTime(timeValue(23, 59, 59, 999900000, 9, null))
},
DateTimeTestCase("TIME (7) '23:59:59.123456789'") {
litTime(timeValue(23, 59, 59, 123456789, 7, null))
},
DateTimeTestCase("TIME (9) '23:59:59.123456789'") {
litTime(timeValue(23, 59, 59, 123456789, 9, null))
},
DateTimeTestCase("TIME (0) '23:59:59.123456789'") {
litTime(timeValue(23, 59, 59, 123456789, 0, null))
},
DateTimeTestCase("TIME (10) '23:59:59.123456789'") {
litTime(timeValue(23, 59, 59, 123456789, 9, null))
},
DateTimeTestCase("TIME '02:30:59-05:30'") {
litTime(timeValue(2, 30, 59, 0, 9, null))
},
DateTimeTestCase("TIME '02:30:59+05:30'") {
litTime(timeValue(2, 30, 59, 0, 9, null))
},
DateTimeTestCase("TIME '02:30:59-14:39'") {
litTime(timeValue(2, 30, 59, 0, 9, null))
},
DateTimeTestCase("TIME '02:30:59+00:00'") {
litTime(timeValue(2, 30, 59, 0, 9, null))
},
DateTimeTestCase("TIME '02:30:59-00:00'") {
litTime(timeValue(2, 30, 59, 0, 9, null))
},
DateTimeTestCase("TIME (3) '12:59:31+10:30'") {
litTime(timeValue(12, 59, 31, 0, 3, null))
},
DateTimeTestCase("TIME (0) '00:00:00+00:00'") {
litTime(timeValue(0, 0, 0, 0, 0, null))
},
DateTimeTestCase("TIME (0) '00:00:00-00:00'") {
litTime(timeValue(0, 0, 0, 0, 0, null))
},
DateTimeTestCase("TIME '23:59:59.9999-11:59'") {
litTime(timeValue(23, 59, 59, 999900000, 9, null))
},
DateTimeTestCase("TIME (7) '23:59:59.123456789+01:00'") {
litTime(timeValue(23, 59, 59, 123456789, 7, null))
},
DateTimeTestCase("TIME (9) '23:59:59.123456789-14:50'") {
litTime(timeValue(23, 59, 59, 123456789, 9, null))
},
DateTimeTestCase("TIME (0) '23:59:59.123456789-18:00'") {
litTime(timeValue(23, 59, 59, 123456789, 0, null))
},
DateTimeTestCase("TIME (10) '23:59:59.123456789+18:00'") {
litTime(timeValue(23, 59, 59, 123456789, 9, null))
},
DateTimeTestCase("TIME WITH TIME ZONE '02:30:59'") {
litTime(timeValue(2, 30, 59, 0, 9, LOCAL_TIME_ZONE_OFFSET))
},
DateTimeTestCase("TIME (3) WITH TIME ZONE '12:59:31'") {
litTime(timeValue(12, 59, 31, 0, 3, LOCAL_TIME_ZONE_OFFSET))
},
DateTimeTestCase("TIME WITH TIME ZONE '23:59:59.9999'") {
litTime(timeValue(23, 59, 59, 999900000, 9, LOCAL_TIME_ZONE_OFFSET))
},
DateTimeTestCase("TIME (7) WITH TIME ZONE '23:59:59.123456789'") {
litTime(timeValue(23, 59, 59, 123456789, 7, LOCAL_TIME_ZONE_OFFSET))
},
DateTimeTestCase("TIME (9) WITH TIME ZONE '23:59:59.123456789'") {
litTime(timeValue(23, 59, 59, 123456789, 9, LOCAL_TIME_ZONE_OFFSET))
},
DateTimeTestCase("TIME (0) WITH TIME ZONE '23:59:59.123456789'") {
litTime(timeValue(23, 59, 59, 123456789, 0, LOCAL_TIME_ZONE_OFFSET))
},
DateTimeTestCase("TIME (10) WITH TIME ZONE '23:59:59.123456789'") {
litTime(timeValue(23, 59, 59, 123456789, 9, LOCAL_TIME_ZONE_OFFSET))
},
DateTimeTestCase("TIME (0) WITH TIME ZONE '00:00:00+00:00'") {
litTime(timeValue(0, 0, 0, 0, 0, 0))
},
DateTimeTestCase("TIME (0) WITH TIME ZONE '00:00:00-00:00'") {
litTime(timeValue(0, 0, 0, 0, 0, 0))
},
DateTimeTestCase("TIME WITH TIME ZONE '02:30:59-05:30'") {
litTime(timeValue(2, 30, 59, 0, 9, -330))
},
DateTimeTestCase("TIME WITH TIME ZONE '02:30:59+05:30'") {
litTime(timeValue(2, 30, 59, 0, 9, 330))
},
DateTimeTestCase("TIME WITH TIME ZONE '02:30:59-14:39'") {
litTime(timeValue(2, 30, 59, 0, 9, -879))
},
DateTimeTestCase("TIME WITH TIME ZONE '23:59:59.9999-11:59'") {
litTime(timeValue(23, 59, 59, 999900000, 9, -719))
},
DateTimeTestCase("TIME (7) WITH TIME ZONE '23:59:59.123456789+01:00'") {
litTime(timeValue(23, 59, 59, 123456789, 7, 60))
},
DateTimeTestCase("TIME (9) WITH TIME ZONE '23:59:59.123456789-14:50'") {
litTime(timeValue(23, 59, 59, 123456789, 9, -890))
},
DateTimeTestCase("TIME (0) WITH TIME ZONE '23:59:59.123456789-18:00'") {
litTime(timeValue(23, 59, 59, 123456789, 0, -1080))
},
DateTimeTestCase("TIME (10) WITH TIME ZONE '23:59:59.123456789+18:00'") {
litTime(timeValue(23, 59, 59, 123456789, 9, 1080))
}
)
private fun generateRandomSeed() : Random {
val rng = Random()
val seed = rng.nextLong()
println("Randomly generated seed is ${seed}. Use this to reproduce failures in dev environment.")
rng.setSeed(seed)
return rng
}
private fun Random.nextDate() : Date {
val year = nextInt(10000)
val month = nextInt(12) + 1
val day = when (month) {
in MONTHS_WITH_31_DAYS -> nextInt(31)
2 -> when (year % 4) {
0 -> nextInt(29)
else -> nextInt(28)
}
else -> nextInt(30)
} + 1
return Date(year, month, day)
}
@Test
fun testRandomDates() {
RANDOM_DATES.map { date ->
val yearStr = date.year.toString().padStart(4, '0')
val monthStr = date.month.toString().padStart(2, '0')
val dayStr = date.day.toString().padStart(2, '0')
assertExpression("DATE '$yearStr-$monthStr-$dayStr'") {
date(date.year.toLong(), date.month.toLong(), date.day.toLong())
}
}
}
private fun createErrorCaseForTime(source: String, errorCode: ErrorCode, line: Long, col: Long, tokenType: TokenType, tokenValue: IonValue): () -> Unit = {
checkInputThrowingParserException(
source,
errorCode,
mapOf(
Property.LINE_NUMBER to line,
Property.COLUMN_NUMBER to col,
Property.TOKEN_TYPE to tokenType,
Property.TOKEN_VALUE to tokenValue))
}
private fun createErrorCaseForTime(source: String, errorCode: ErrorCode, errorContext: Map<Property, Any>): () -> Unit = {
checkInputThrowingParserException(
source,
errorCode,
errorContext)
}
fun parametersForTimeParserErrorTests() = listOf(
createErrorCaseForTime(
source = "TIME",
line = 1L,
col = 5L,
errorCode = ErrorCode.PARSE_UNEXPECTED_TOKEN,
tokenType = TokenType.EOF,
tokenValue = ion.newSymbol("EOF")
),
createErrorCaseForTime(
source = "TIME 123",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_UNEXPECTED_TOKEN,
tokenType = TokenType.LITERAL,
tokenValue = ion.newInt(123)
),
createErrorCaseForTime(
source = "TIME 'time_string'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("time_string")
),
createErrorCaseForTime(
source = "TIME 123.23",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_UNEXPECTED_TOKEN,
tokenType = TokenType.LITERAL,
tokenValue = ion.singleValue("123.23")
),
createErrorCaseForTime(
source = "TIME `2012-12-12`",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_UNEXPECTED_TOKEN,
tokenType = TokenType.ION_LITERAL,
tokenValue = ion.singleValue("2012-12-12")
),
createErrorCaseForTime(
source = "TIME '2012-12-12'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("2012-12-12")
),
createErrorCaseForTime(
source = "TIME '12'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("12")
),
// This is a valid time string in PostgreSQL
createErrorCaseForTime(
source = "TIME '12:30'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("12:30")
),
// This is a valid time string in PostgreSQL
createErrorCaseForTime(
source = "TIME '34:59'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("34:59")
),
// This is a valid time string in PostgreSQL
createErrorCaseForTime(
source = "TIME '59.12345'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("59.12345")
),
// This is a valid time string in PostgreSQL
createErrorCaseForTime(
source = "TIME '1:30:38'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("1:30:38")
),
// This is a valid time string in PostgreSQL
createErrorCaseForTime(
source = "TIME '1:30:38'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("1:30:38")
),
createErrorCaseForTime(
source = "TIME '12:59:61.0000'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("12:59:61.0000")
),
createErrorCaseForTime(
source = "TIME '12.123:45.123:54.123'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("12.123:45.123:54.123")
),
createErrorCaseForTime(
source = "TIME '-19:45:13'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("-19:45:13")
),
createErrorCaseForTime(
source = "TIME '24:00:00'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("24:00:00")
),
createErrorCaseForTime(
source = "TIME '23:59:59.99999 05:30'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("23:59:59.99999 05:30")
),
createErrorCaseForTime(
source = "TIME '23:59:59+05:30.00'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("23:59:59+05:30.00")
),
// TODO: Investing why the build failed in GH actions for these two tests.
// createErrorCaseForTime(
// source = "TIME '23:59:59+24:00'",
// line = 1L,
// col = 6L,
// errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
// tokenType = TokenType.LITERAL,
// tokenValue = ion.newString("23:59:59+24:00")
// ),
// createErrorCaseForTime(
// source = "TIME '23:59:59-24:00'",
// line = 1L,
// col = 6L,
// errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
// tokenType = TokenType.LITERAL,
// tokenValue = ion.newString("23:59:59-24:00")
// ),
// This is a valid time string in PostgreSQL
createErrorCaseForTime(
source = "TIME '08:59:59.99999 AM'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("08:59:59.99999 AM")
),
// This is a valid time string in PostgreSQL
createErrorCaseForTime(
source = "TIME '08:59:59.99999 PM'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("08:59:59.99999 PM")
),
createErrorCaseForTime(
source = "TIME ( '23:59:59.99999'",
line = 1L,
col = 8L,
errorCode = ErrorCode.PARSE_INVALID_PRECISION_FOR_TIME,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("23:59:59.99999")
),
createErrorCaseForTime(
source = "TIME () '23:59:59.99999'",
line = 1L,
col = 7L,
errorCode = ErrorCode.PARSE_INVALID_PRECISION_FOR_TIME,
tokenType = TokenType.RIGHT_PAREN,
tokenValue = ion.newSymbol(")")
),
createErrorCaseForTime(
source = "TIME [4] '23:59:59.99999'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_UNEXPECTED_TOKEN,
tokenType = TokenType.LEFT_BRACKET,
tokenValue = ion.newSymbol("[")
),
createErrorCaseForTime(
source = "TIME {4} '23:59:59.99999'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_UNEXPECTED_TOKEN,
tokenType = TokenType.LEFT_CURLY,
tokenValue = ion.newSymbol("{")
),
createErrorCaseForTime(
source = "TIME 4 '23:59:59.99999'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_UNEXPECTED_TOKEN,
tokenType = TokenType.LITERAL,
tokenValue = ion.newInt(4)
),
createErrorCaseForTime(
source = "TIME ('4') '23:59:59.99999'",
line = 1L,
col = 7L,
errorCode = ErrorCode.PARSE_INVALID_PRECISION_FOR_TIME,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("4")
),
createErrorCaseForTime(
source = "TIME ('four') '23:59:59.99999'",
line = 1L,
col = 7L,
errorCode = ErrorCode.PARSE_INVALID_PRECISION_FOR_TIME,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("four")
),
createErrorCaseForTime(
source = "TIME WITH TIME ZONE",
line = 1L,
col = 20L,
errorCode = ErrorCode.PARSE_UNEXPECTED_TOKEN,
tokenType = TokenType.EOF,
tokenValue = ion.newSymbol("EOF")
),
createErrorCaseForTime(
source = "TIME WITH TIME ZONE '12:20'",
line = 1L,
col = 21L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("12:20")
),
createErrorCaseForTime(
source = "TIME WITH TIME ZONE '34:59'",
line = 1L,
col = 21L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("34:59")
),
createErrorCaseForTime(
source = "TIME WITH TIME ZONE '59.12345'",
line = 1L,
col = 21L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("59.12345")
),
createErrorCaseForTime(
source = "TIME WITH TIME ZONE '12:20'",
line = 1L,
col = 21L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("12:20")
),
createErrorCaseForTime(
source = "TIME WITH TIMEZONE '23:59:59.99999'",
errorCode = ErrorCode.PARSE_EXPECTED_KEYWORD,
errorContext = mapOf(
Property.LINE_NUMBER to 1L,
Property.COLUMN_NUMBER to 11L,
Property.KEYWORD to "TIME",
Property.TOKEN_TYPE to TokenType.IDENTIFIER,
Property.TOKEN_VALUE to ion.newSymbol("TIMEZONE")
)
),
createErrorCaseForTime(
source = "TIME WITH_TIME_ZONE '23:59:59.99999'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_UNEXPECTED_TOKEN,
tokenType = TokenType.IDENTIFIER,
tokenValue = ion.newSymbol("WITH_TIME_ZONE")
),
createErrorCaseForTime(
source = "TIME WITHTIMEZONE '23:59:59.99999'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_UNEXPECTED_TOKEN,
tokenType = TokenType.IDENTIFIER,
tokenValue = ion.newSymbol("WITHTIMEZONE")
),
// PartiQL doesn't support "WITHOUT TIME ZONE" yet. TIME '<time_string>' is in effect the same as TIME WITHOUT TIME ZONE '<time_string>'
createErrorCaseForTime(
source = "TIME WITHOUT TIME ZONE '23:59:59.99999'",
line = 1L,
col = 6L,
errorCode = ErrorCode.PARSE_UNEXPECTED_TOKEN,
tokenType = TokenType.IDENTIFIER,
tokenValue = ion.newSymbol("WITHOUT")
),
createErrorCaseForTime(
source = "TIME WITH TIME PHONE '23:59:59.99999'",
errorCode = ErrorCode.PARSE_EXPECTED_KEYWORD,
errorContext = mapOf(
Property.LINE_NUMBER to 1L,
Property.COLUMN_NUMBER to 16L,
Property.KEYWORD to "ZONE",
Property.TOKEN_TYPE to TokenType.IDENTIFIER,
Property.TOKEN_VALUE to ion.newSymbol("PHONE")
)
),
createErrorCaseForTime(
source = "TIME WITH (4) TIME ZONE '23:59:59.99999'",
errorCode = ErrorCode.PARSE_EXPECTED_KEYWORD,
errorContext = mapOf(
Property.LINE_NUMBER to 1L,
Property.COLUMN_NUMBER to 11L,
Property.KEYWORD to "TIME",
Property.TOKEN_TYPE to TokenType.LEFT_PAREN,
Property.TOKEN_VALUE to ion.newSymbol("(")
)
),
createErrorCaseForTime(
source = "TIME WITH TIME (4) ZONE '23:59:59.99999'",
errorCode = ErrorCode.PARSE_EXPECTED_KEYWORD,
errorContext = mapOf(
Property.LINE_NUMBER to 1L,
Property.COLUMN_NUMBER to 16L,
Property.KEYWORD to "ZONE",
Property.TOKEN_TYPE to TokenType.LEFT_PAREN,
Property.TOKEN_VALUE to ion.newSymbol("(")
)
),
createErrorCaseForTime(
source = "TIME WITH TIME ZONE (4) '23:59:59.99999'",
line = 1L,
col = 21L,
errorCode = ErrorCode.PARSE_UNEXPECTED_TOKEN,
tokenType = TokenType.LEFT_PAREN,
tokenValue = ion.newSymbol("(")
),
createErrorCaseForTime(
source = "TIME WITH TIME ZONE 'time_string'",
line = 1L,
col = 21L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("time_string")
),
createErrorCaseForTime(
source = "TIME WITH TIME ZONE '23:59:59+18:00.00'",
line = 1L,
col = 21L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("23:59:59+18:00.00")
),
createErrorCaseForTime(
source = "TIME WITH TIME ZONE '23:59:59-18:00.00'",
line = 1L,
col = 21L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("23:59:59-18:00.00")
),
createErrorCaseForTime(
source = "TIME WITH TIME ZONE '23:59:59+18:01'",
line = 1L,
col = 21L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("23:59:59+18:01")
),
// time zone offset out of range
createErrorCaseForTime(
source = "TIME WITH TIME ZONE '23:59:59-18:01'",
line = 1L,
col = 21L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("23:59:59-18:01")
),
// time zone offset out of range
createErrorCaseForTime(
source = "TIME ('4') WITH TIME ZONE '23:59:59-18:01'",
line = 1L,
col = 7L,
errorCode = ErrorCode.PARSE_INVALID_PRECISION_FOR_TIME,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("4")
),
createErrorCaseForTime(
source = "TIME WITH TIME ZONE '23:59:59-18-01'",
line = 1L,
col = 21L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("23:59:59-18-01")
),
// This is valid in PostgreSQL.
createErrorCaseForTime(
source = "TIME WITH TIME ZONE '23:59:59 PST'",
line = 1L,
col = 21L,
errorCode = ErrorCode.PARSE_INVALID_TIME_STRING,
tokenType = TokenType.LITERAL,
tokenValue = ion.newString("23:59:59 PST")
)
)
@Test
@Parameters
fun timeParserErrorTests(block: () -> Unit) = block()
} | 0 | null | 0 | 0 | eee99ae37bd60fd92ac6ae3d8cf0558aef61223f | 25,099 | partiql-lang-kotlin | Apache License 2.0 |
app/src/main/java/com/g2pdev/smartrate/demo/ui/MainView.kt | oscarito9410 | 300,996,771 | true | {"Kotlin": 107803, "Shell": 944} | package com.g2pdev.smartrate.demo.ui
import com.g2pdev.smartrate.logic.model.config.SmartRateConfig
import moxy.MvpView
import moxy.viewstate.strategy.AddToEndSingleStrategy
import moxy.viewstate.strategy.StateStrategyType
@StateStrategyType(AddToEndSingleStrategy::class)
interface MainView : MvpView {
fun showSessionCount(sessionCount: Int)
fun showSessionCountBetweenPrompts(sessionCountBetweenPrompts: Int)
fun setFakeSessionCount(sessionCount: Int)
fun showCountersCleared()
fun showRateDialogShown()
fun showRateDialogWillNotShow()
fun showRated(stars: Float)
fun showNeverClicked()
fun showLaterClicked()
fun showFeedbackCancelClicked()
fun showFeedbackSubmitClicked(text: String)
fun setConfig(config: SmartRateConfig)
}
| 0 | null | 0 | 0 | b5ef98cb1d3270723f582d8a711dea3087b67368 | 786 | android-smart-rate | Apache License 2.0 |
src/test/kotlin/eZmaxApi/models/MultilingualSubnetDescriptionTest.kt | eZmaxinc | 271,950,932 | false | {"Kotlin": 6909939} | /**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package eZmaxApi.models
import io.kotlintest.shouldBe
import io.kotlintest.specs.ShouldSpec
import eZmaxApi.models.MultilingualSubnetDescription
class MultilingualSubnetDescriptionTest : ShouldSpec() {
init {
// uncomment below to create an instance of MultilingualSubnetDescription
//val modelInstance = MultilingualSubnetDescription()
// to test the property `sSubnetDescription1` - The description of the Subnet in French
should("test sSubnetDescription1") {
// uncomment below to test the property
//modelInstance.sSubnetDescription1 shouldBe ("TODO")
}
// to test the property `sSubnetDescription2` - The description of the Subnet in English
should("test sSubnetDescription2") {
// uncomment below to test the property
//modelInstance.sSubnetDescription2 shouldBe ("TODO")
}
}
}
| 0 | Kotlin | 0 | 0 | 961c97a9f13f3df7986ea7ba55052874183047ab | 1,182 | eZmax-SDK-kotlin | MIT License |
2023/src/test/kotlin/sh/weller/aoc/Day06Test.kt | Guruth | 328,467,380 | false | {"Kotlin": 171430, "Rust": 13289, "Elixir": 1833} | package sh.weller.aoc
class Day06Test : SomeDayTest<List<Long>, Long>(6, Day06) {
override fun List<String>.mapData(): List<List<Long>> {
val times = first().split(":").last().split(" ").filterNot { it.isBlank() }.map { it.toLong() }
val distance = last().split(":").last().split(" ").filterNot { it.isBlank() }.map { it.toLong() }
return listOf(times, distance)
}
override val resultTest1: Long = 288
override val resultTest2: Long = 71503
}
| 0 | Kotlin | 0 | 0 | e5505f796420c844a7ac939399692c5351999b43 | 488 | AdventOfCode | MIT License |
app/src/main/java/com/xmod/firebase_1/View/BorcActivity.kt | mahmut-salih-cicek | 482,820,960 | false | null | package com.xmod.firebase_1.View
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.Query
import com.xmod.firebase_1.Model.firebasemodel
import com.xmod.firebase_1.R
class BorcActivity : AppCompatActivity() {
lateinit var auth: FirebaseAuth
lateinit var database : FirebaseFirestore
var postList = ArrayList<firebasemodel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_borc)
auth = FirebaseAuth.getInstance()
database = FirebaseFirestore.getInstance()
// getDataName()
}
fun getDataName(name:String){
database.collection("Post")
/// kullanıcıya ozel datayi goster
.whereEqualTo("KullanıcıEmail",auth.currentUser!!.email)
.whereEqualTo("kullanıcıIsım",name)
// .whereEqualTo("kullanıcıIsım","${UserActivity.localUser}")
/// en son girelen tarih en basta gozukkecek
.orderBy("tarih", Query.Direction.DESCENDING)
.addSnapshotListener { snapshot, error ->
if (error != null){
println("Hata data çekilmedi ")
}else{
if(snapshot != null){
if (snapshot.isEmpty == false){
val documents = snapshot.documents /// mutable listi aldık
postList.clear()
for(k in documents){
var kullanıcıResimURL = k.get("kullanıcıResimURL") as String
var kullanıcıIsım = k.get("kullanıcıIsım") as String
var KullanıcıEmail = k.get("KullanıcıEmail") as String
var kullanıcıFiyat = k.get("kullanıcıFiyat") as String
var kullanıcıTarih = k.get("kullanıcıTarih") as String
var kullanıcıAlınanYer = k.get("kullanıcıAlınanYer") as String
postList.add(firebasemodel(kullanıcıResimURL,kullanıcıIsım,KullanıcıEmail,kullanıcıFiyat,kullanıcıTarih,kullanıcıAlınanYer))
println(kullanıcıIsım)
}
}
}
}
}
}
fun getDataPrice(){
database.collection("Post")
/// kullanıcıya ozel datayi goster
.whereEqualTo("KullanıcıEmail",auth.currentUser!!.email)
// .whereEqualTo("kullanıcıIsım","${UserActivity.localUser}")
/// en son girelen tarih en basta gozukkecek
.orderBy("tarih", Query.Direction.DESCENDING)
.addSnapshotListener { snapshot, error ->
if (error != null){
println("Hata data çekilmedi ")
}else{
if(snapshot != null){
if (snapshot.isEmpty == false){
val documents = snapshot.documents /// mutable listi aldık
postList.clear()
for(k in documents){
var kullanıcıResimURL = k.get("kullanıcıResimURL") as String
var kullanıcıIsım = k.get("kullanıcıIsım") as String
var KullanıcıEmail = k.get("KullanıcıEmail") as String
var kullanıcıFiyat = k.get("kullanıcıFiyat") as String
var kullanıcıTarih = k.get("kullanıcıTarih") as String
var kullanıcıAlınanYer = k.get("kullanıcıAlınanYer") as String
postList.add(firebasemodel(kullanıcıResimURL,kullanıcıIsım,KullanıcıEmail,kullanıcıFiyat,kullanıcıTarih,kullanıcıAlınanYer))
println(kullanıcıIsım)
}
}
}
}
}
}
} | 0 | Kotlin | 0 | 1 | 3bbe2855eec98a456c12bff559f614df718dfcfa | 4,193 | Student-Bill | MIT License |
stream-chat-android-compose/src/main/java/io/getstream/chat/android/compose/util/extensions/ChannelCapabilities.kt | GetStream | 177,873,527 | false | null | /*
* Copyright (c) 2014-2022 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-chat-android/blob/main/LICENSE
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.getstream.chat.android.compose.util.extensions
import io.getstream.chat.android.core.internal.InternalStreamChatApi
import io.getstream.chat.android.models.ChannelCapabilities
/**
* Creates a set of channel capabilities fully populated
* with all values inside [ChannelCapabilities].
*
* Used for previews, using it in production would grant every user
* all privileges.
*/
@InternalStreamChatApi
public fun ChannelCapabilities.toSet(): Set<String> = setOf(
BAN_CHANNEL_MEMBERS,
CONNECT_EVENTS,
DELETE_ANY_MESSAGE,
DELETE_CHANNEL,
DELETE_OWN_MESSAGE,
FLAG_MESSAGE,
FREEZE_CHANNEL,
LEAVE_CHANNEL,
MUTE_CHANNEL,
PIN_MESSAGE,
QUOTE_MESSAGE,
READ_EVENTS,
SEARCH_MESSAGES,
SEND_CUSTOM_EVENTS,
SEND_LINKS,
SEND_MESSAGE,
SEND_REACTION,
SEND_REPLY,
SET_CHANNEL_COOLDOWN,
SEND_TYPING_EVENTS,
TYPING_EVENTS,
UPDATE_ANY_MESSAGE,
UPDATE_CHANNEL,
UPDATE_CHANNEL_MEMBERS,
UPDATE_OWN_MESSAGE,
UPLOAD_FILE,
)
| 32 | null | 273 | 1,451 | 8e46f46a68810d8086c48a88f0fff29faa2629eb | 1,639 | stream-chat-android | FSF All Permissive License |
src/main/kotlin/github/walkmansit/aoc2020/Day11.kt | walkmansit | 317,479,715 | false | null | package github.walkmansit.aoc2020
class Day11(val input: List<String>) : DayAoc<Int, Int> {
private class SeatsTable(lines: List<String>) {
// Point(Y,X)
private val neighbords = arrayOf(
arrayOf(0 to 1, 1 to 1, 1 to 0), // 0 TOP LEFT
arrayOf(1 to 0, 1 to -1, 0 to -1), // 1 TOP RIGHT
arrayOf(0 to 1, 1 to 1, 1 to 0, 1 to -1, 0 to -1), // 2 TOP
arrayOf(-1 to 0, -1 to 1, 0 to 1), // 3 BOTTOM LEFT
arrayOf(-1 to 0, -1 to 1, 0 to 1, 1 to 1, 1 to 0), // 4 LEFT
arrayOf(0 to -1, -1 to -1, -1 to 0), // 5 BOTTOM RIGHT
arrayOf(0 to -1, -1 to -1, -1 to 0, -1 to 1, 0 to 1), // 6 BOTTOM
arrayOf(1 to 0, 1 to -1, 0 to -1, -1 to -1, -1 to 0), // 7 RIGHT
arrayOf(0 to 1, 1 to 1, 1 to 0, 1 to -1, 0 to -1, -1 to -1, -1 to 0, -1 to 1) // 8 FULL
)
private enum class CellType {
FLOOOR,
SEAT,
OCCUPIED
}
private lateinit var cells: Array<Array<CellType>>
private lateinit var buffer: Array<Array<CellType>>
private var height: Int = 0
private var width: Int = 0
private lateinit var neigboarPosIdx: Array<Array<Int>>
init {
height = lines.size
width = lines[0].length
cells = Array(height) { Array(width) { CellType.SEAT } }
neigboarPosIdx = Array(height) { Array(width) { 8 } }
// buffer = cells.clone()
for (i in 0 until height)
for (j in 0 until width) {
// init cells
if (lines[i][j] == '.') {
cells[i][j] = CellType.FLOOOR
}
if (i == 0) {
if (j == 0) {
neigboarPosIdx[i][j] = 0 // top left
continue
}
if (j == width - 1) {
neigboarPosIdx[i][j] = 1 // top right
continue
}
neigboarPosIdx[i][j] = 2 // top
continue
}
if (j == 0) {
if (i == height - 1) {
neigboarPosIdx[i][j] = 3 // bottom left
continue
}
neigboarPosIdx[i][j] = 4 // bottom
continue
}
if (i == height - 1) {
if (j == width - 1) {
neigboarPosIdx[i][j] = 5 // bottom right
continue
}
neigboarPosIdx[i][j] = 6 // bottom
continue
}
if (j == width - 1) {
neigboarPosIdx[i][j] = 7 // right
}
}
}
private fun countOccupied(): Int {
var sum = 0
for (i in 0 until height)
for (j in 0 until width)
if (cells[i][j] == CellType.OCCUPIED) sum++
return sum
}
fun simulateIteration(withDirections: Boolean, ngbCount: Int): Boolean {
fun countOccupiedNeigbords(y: Int, x: Int): Int {
var sum = 0
for ((i, j) in neighbords[neigboarPosIdx[y][x]]) {
if (cells[y + i][x + j] == CellType.OCCUPIED)
sum++
}
return sum
}
fun countNeigbordsWithDirections(y: Int, x: Int): Int {
fun isDirectionOccupied(y: Int, x: Int, dy: Int, dx: Int): Boolean {
var nextY = y + dy
var nextX = x + dx
while (nextY in 0 until height && nextX in 0 until width) {
if (cells[nextY][nextX] == CellType.OCCUPIED) return true
if (cells[nextY][nextX] == CellType.SEAT) return false
nextX += dx
nextY += dy
}
return false
}
var sum = 0
for ((dy, dx) in neighbords[neigboarPosIdx[y][x]]) {
if (isDirectionOccupied(y, x, dy, dx)) sum++
}
return sum
}
buffer = clone2DimArray(cells)
var hasChanges = false
for (i in 0 until height)
for (j in 0 until width) {
val occupiedSum =
if (withDirections) countNeigbordsWithDirections(i, j) else countOccupiedNeigbords(i, j)
when (cells[i][j]) {
CellType.SEAT -> {
if (occupiedSum == 0) {
buffer[i][j] = CellType.OCCUPIED
hasChanges = true
}
}
CellType.OCCUPIED -> {
if (occupiedSum > ngbCount - 1) {
buffer[i][j] = CellType.SEAT
hasChanges = true
}
}
}
}
cells = buffer
return hasChanges
}
fun clone2DimArray(array: Array<Array<CellType>>): Array<Array<CellType>> {
val result = Array(height) { Array(width) { CellType.SEAT } }
for (i in 0 until height)
for (j in 0 until width) {
result[i][j] = array[i][j]
}
return result
}
fun simulateStillStable(withDirections: Boolean, ngbCount: Int): Int {
var hasChanges = true
while (hasChanges) {
hasChanges = simulateIteration(withDirections, ngbCount)
}
return countOccupied()
}
}
override fun getResultPartOne(): Int {
return SeatsTable(input).simulateStillStable(false, 4)
}
override fun getResultPartTwo(): Int {
return SeatsTable(input).simulateStillStable(true, 5)
}
}
| 0 | Kotlin | 0 | 0 | 9c005ac4513119ebb6527c01b8f56ec8fd01c9ae | 6,382 | AdventOfCode2020 | MIT License |
app/src/main/java/com/abaferastech/marvelapp/domain/models/Creator.kt | CheeseCake-Team | 633,955,610 | false | null | package com.abaferastech.marvelapp.domain.models
data class Creator(
val id: Int?,
val fullName: String?,
val modified: String?,
val imageUri: String?,
var isFavourite: Boolean? = null
)
| 0 | Kotlin | 0 | 0 | 7c2e38f2571e5ed5135e2461034d77750546ee23 | 209 | MarvelApp | Apache License 2.0 |
android/app/src/main/java/com/algorand/android/modules/perawebview/ui/BasePeraWebViewFragment.kt | perawallet | 364,359,642 | false | {"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596} | /*
* Copyright 2022 Pera Wallet, LDA
* 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.algorand.android.modules.perawebview.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.viewbinding.ViewBinding
import com.algorand.android.customviews.PeraWebView
import com.algorand.android.discover.common.ui.model.PeraWebViewClient
import com.algorand.android.modules.basewebview.ui.BaseWebViewFragment
import com.algorand.android.utils.sendMailRequestUrl
abstract class BasePeraWebViewFragment(
@LayoutRes private val layoutResId: Int,
) : BaseWebViewFragment(layoutResId) {
abstract val binding: ViewBinding
abstract fun bindWebView(view: View?)
abstract val basePeraWebViewViewModel: BasePeraWebViewViewModel
protected val peraWebViewClientListener = object : PeraWebViewClient.PeraWebViewClientListener {
override fun onWalletConnectUrlDetected(url: String) {
handleWalletConnectUrl(url)
}
override fun onEmailRequested(url: String) {
handleMailRequestUrl(url)
}
override fun onPageRequestedShouldOverrideUrlLoading(url: String): Boolean {
return basePeraWebViewViewModel.onPageRequestedShouldOverrideUrlLoading(url)
}
override fun onPageStarted() {
basePeraWebViewViewModel.onPageStarted()
}
override fun onPageFinished(title: String?, url: String?) {
basePeraWebViewViewModel.onPageFinished(title, url)
}
override fun onError() {
basePeraWebViewViewModel.onError()
}
override fun onHttpError() {
basePeraWebViewViewModel.onHttpError()
}
override fun onPageUrlChanged() {
basePeraWebViewViewModel.onPageUrlChanged()
}
override fun onRenderProcessGone() {
basePeraWebViewViewModel.destroyWebView()
}
}
open fun onSendMailRequestFailed() {}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = super.onCreateView(inflater, container, savedInstanceState)
basePeraWebViewViewModel.getWebView()?.let { previousWebView ->
// If we have a previously saved WebView, it is reloaded, bound and theming set
reloadWebView(view, previousWebView)
bindWebView(view)
} ?: bindWebView(view)
getWebView(binding.root)?.let { basePeraWebViewViewModel.saveWebView(it) }
return view
}
private fun reloadWebView(parent: View?, webView: PeraWebView) {
if (parent is ViewGroup) {
for (cx in 0 until parent.childCount) {
val child = parent.getChildAt(cx)
if (child is PeraWebView) {
val index = parent.indexOfChild(child)
parent.removeView(child)
(webView.parent as ViewGroup).removeView(webView)
parent.addView(webView, index)
}
}
}
}
protected fun handleMailRequestUrl(url: String) {
context?.sendMailRequestUrl(url, ::onSendMailRequestFailed)
}
override fun onDestroyView() {
super.onDestroyView()
getWebView(binding.root)?.let { basePeraWebViewViewModel.saveWebView(it) }
}
protected fun getWebView(parent: View): PeraWebView? {
if (parent is ViewGroup) {
for (cx in 0 until parent.childCount) {
val child = parent.getChildAt(cx)
if (child is PeraWebView) {
return child
}
}
}
return null
}
}
| 22 | Swift | 62 | 181 | 92fc77f73fa4105de82d5e87b03c1e67600a57c0 | 4,290 | pera-wallet | Apache License 2.0 |
data/src/main/java/com/marchuk/app/data/models/CurrentForecastResponse.kt | Metior00 | 314,189,031 | false | null | package com.marchuk.app.data.models
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class CurrentForecastResponse(
@Json(name = "cloud")
val cloud: Int,
@Json(name = "condition")
val condition: ConditionResponse,
@Json(name = "feelslike_c")
val feelsLikeC: Double,
@Json(name = "gust_kph")
val gustKph: Double,
@Json(name = "humidity")
val humidity: Int,
@Json(name = "is_day")
val isDay: Int,
@Json(name = "last_updated")
val lastUpdated: String,
@Json(name = "last_updated_epoch")
val lastUpdatedEpoch: Int,
@Json(name = "precip_mm")
val precipMm: Double,
@Json(name = "pressure_mb")
val pressureMb: Double,
@Json(name = "temp_c")
val tempC: Double,
@Json(name = "vis_km")
val visibilityKm: Double,
@Json(name = "wind_kph")
val windKph: Double
) | 0 | Kotlin | 0 | 1 | 5ee4b6778ab85f7e349e8997345bed1bcbb2cbd8 | 912 | forecast-android | MIT License |
src/main/kotlin/net/yested/utils/numbers.kt | jean79 | 27,994,833 | false | null | package net.yested.utils
external fun isNaN(n:Number):Boolean = definedExternally
fun toZero(n:Double):Double =
if (isNaN(n)) {
0.0
} else {
n
}
| 15 | JavaScript | 17 | 85 | dcce8408a12af6d64d0b98889e351b2b115bdbfb | 177 | yested | MIT License |
src/main/kotlin/no/nav/klage/domain/ankevedlegg/AnkeVedlegg.kt | navikt | 253,461,869 | false | null | package no.nav.klage.domain.ankevedlegg
data class AnkeVedlegg(
val tittel: String,
val ref: String,
val ankeInternalSaksnummer: String,
val contentType: String = "Ukjent",
val id: Int? = null,
val sizeInBytes: Int
)
fun AnkeVedlegg.toAnkeVedleggView(content: String) =
AnkeVedleggView(tittel, ref, ankeInternalSaksnummer, contentType, id!!, sizeInBytes, content) | 0 | Kotlin | 0 | 0 | 2eef513ebb1b0fa90ad92768379fe0b4cbd01b66 | 393 | klage-dittnav-api | MIT License |
app-shared-tests/src/test/java/com/appunite/loudius/util/DescribedKtTest.kt | appunite | 604,044,782 | false | {"Kotlin": 363932, "Python": 9529} | /*
* Copyright 2023 AppUnite S.A.
*
* 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.appunite.loudius.util
import org.junit.Test
import strikt.api.expectCatching
import strikt.assertions.isA
import strikt.assertions.isEqualTo
import strikt.assertions.isFailure
import strikt.assertions.isNotNull
import strikt.assertions.isSuccess
import java.lang.Exception
class DescribedKtTest {
@Test
fun `test without failure, is success`() {
expectCatching {
description("test without failure") {
}
}
.isSuccess()
}
@Test
fun `test with unknown error, is not described`() {
expectCatching {
description("test with assertion error") {
throw Exception("Some error")
}
}
.isFailure()
.isA<Exception>()
.get(Exception::message)
.isEqualTo("Some error")
}
@Test
fun `test with assertion error, is described`() {
expectCatching {
description("test with assertion error") {
throw AssertionError("Some error")
}
}
.isFailure()
.isA<DescriptionAssertionError>()
.and {
get(DescriptionAssertionError::message).isEqualTo("Error in step: \"test with assertion error\"")
get(DescriptionAssertionError::cause).isNotNull()
.get(Throwable::message)
.isEqualTo("Some error")
}
}
@Test
fun `test with multiple descriptions, descriptions are merged`() {
expectCatching {
description("first description") {
description("second description") {
throw AssertionError("Some error")
}
}
}
.isFailure()
.isA<DescriptionAssertionError>()
.and {
get(DescriptionAssertionError::message).isEqualTo("Error in step: \"first description -> second description\"")
get(DescriptionAssertionError::cause).isNotNull()
.get(Throwable::message)
.isEqualTo("Some error")
}
}
}
| 7 | Kotlin | 0 | 13 | 9349dc3d54a1a2890189399fb078d25d67a59b13 | 2,748 | Loudius | Apache License 2.0 |
src/main/kotlin/fudge/gui/layout/Layout.kt | natanfudge | 261,799,558 | false | null | package fudge.gui.layout
import fudge.gui.*
import fudge.gui.compose.ComposableObject
internal object Layouts {
val Root = Modifier.layout { childrenSizes, screenConstraints ->
assert(childrenSizes.size == 1) { "Root node can only have one child!" }
val childSize = childrenSizes[0]
listOf(
Rect(
0,
0,
childSize.minWidth,
childSize.minHeight
)/*.constrain(screenConstraints)*/
)
}
}
internal object Layout {
fun layoutGuiTree(root: ComposableObject, rootConstraints: Rect): Placed {
val sizeTree = root.buildSizeTree()
return Placed(
constraints = rootConstraints,
children = root.placeChildren(sizeTree, rootConstraints),
node = root
)
}
}
abstract class LayoutModifier : Modifier {
override fun toString(): String = "LayoutModifier"
abstract fun layoutChildren(childrenSizes: List<NodeSize>, constraints: Rect): List<Rect>
}
abstract class SizeModifier(private val debugName: String?) : Modifier {
abstract fun size(childrenSizes: List<NodeSize>): NodeSize
override fun toString(): String = debugName ?: "Custom SizeModifier"
object Default : SizeModifier("SizeModifier.Default") {
override fun size(childrenSizes: List<NodeSize>): NodeSize {
// Make sure the parent minwidth/minheight is at least as much as the children
val maxMinWidth = childrenSizes.maxOfOrNull { it.minWidth } ?: 0
val maxMinHeight = childrenSizes.maxOfOrNull { it.minHeight } ?: 0
return NodeSize(maxMinWidth, Int.MAX_VALUE, maxMinHeight, Int.MAX_VALUE)
}
}
} | 0 | Kotlin | 0 | 0 | ce7dd5f23a92d13a62c7fa3f6b6f2e7dad7040e8 | 1,725 | Tasks | Creative Commons Zero v1.0 Universal |
omnia/src/commonMain/omnia/io/filesystem/virtual/VirtualFileSystem.kt | StrangePan | 224,343,744 | false | {"Kotlin": 475894} | package omnia.io.filesystem.virtual
import omnia.data.structure.immutable.ImmutableList
import omnia.io.filesystem.AbsolutePath
import omnia.io.filesystem.FileAlreadyExistsException
import omnia.io.filesystem.FileNotFoundException
import omnia.io.filesystem.FileSystem
/**
* A virtual, in-memory file system. Useful for tests, intermediate file processing steps, and other tasks that
* shouldn't touch the operating system's storage.
*/
class VirtualFileSystem(private val workingDirectoryPath: AbsolutePath): FileSystem {
constructor(): this(ROOT_DIRECTORY_PATH)
internal val tree = VirtualFileSystemTree()
init {
createDirectoryAt(ROOT_DIRECTORY_PATH)
if (workingDirectoryPath != ROOT_DIRECTORY_PATH) {
workingDirectoryPath
.extractParentDirectoryPaths()
.drop(1) // first is just the root directory
.plus(workingDirectoryPath)
.forEach(::createDirectoryAt)
}
}
override val rootDirectory: VirtualDirectory get() =
getDirectoryAt(AbsolutePath())
override val workingDirectory: VirtualDirectory get() =
getDirectoryAt(workingDirectoryPath)
override fun objectExistsAt(path: AbsolutePath): Boolean =
tree.getFileSystemObject(path) != null
override fun directoryExistsAt(path: AbsolutePath): Boolean =
tree.getDirectory(path) != null
override fun fileExistsAt(path: AbsolutePath): Boolean =
tree.getFile(path) != null
override fun getObjectAt(path: AbsolutePath): VirtualFileSystemObject =
tree.getFileSystemObject(path) ?: throw FileNotFoundException(path.toString())
override fun getDirectoryAt(path: AbsolutePath): VirtualDirectory =
tree.getDirectory(path) ?: throw FileNotFoundException(path.toString())
override fun getFileAt(path: AbsolutePath): VirtualFile =
tree.getFile(path) ?: throw FileNotFoundException(path.toString())
internal fun getContentsInDirectory(directory: VirtualDirectory): ImmutableList<VirtualFileSystemObject> =
tree.getContentsInDirectory(directory.fullPath)
internal fun getDirectoriesInDirectory(directory: VirtualDirectory): ImmutableList<VirtualDirectory> =
tree.getDirectoriesInDirectory(directory.fullPath)
internal fun getFilesInDirectory(directory: VirtualDirectory): ImmutableList<VirtualFile> =
tree.getFilesInDirectory(directory.fullPath)
override fun createDirectoryAt(path: AbsolutePath): VirtualDirectory {
val directory = VirtualDirectory(this, path)
if (tree.addDirectory(directory)) {
return directory
} else {
throw FileAlreadyExistsException(tree.getFileSystemObject(path)!!)
}
}
override fun createFileAt(path: AbsolutePath): VirtualFile {
val file = VirtualFile(this, path)
if (tree.addFile(file)) {
return file
} else {
throw FileAlreadyExistsException(tree.getFileSystemObject(path)!!)
}
}
companion object {
private val ROOT_DIRECTORY_PATH = AbsolutePath()
}
}
internal fun AbsolutePath.extractParentDirectoryPaths() =
this.components
.scan(AbsolutePath()) { path, component -> path + component }
.dropLast(1)
| 0 | Kotlin | 0 | 1 | b7bb7a1c9d1deb40a3ce7544d6dfd117fdac052e | 3,092 | omnia | The Unlicense |
app/src/main/java/com/klim/koinsample/ui/gallery/GalleryFragment.kt | makstron | 349,967,030 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "JSON": 1, "Proguard": 1, "Kotlin": 30, "XML": 31, "Java": 1} | package com.klim.koinsample.ui.gallery
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.klim.koinsample.R
import org.koin.androidx.viewmodel.ext.android.viewModel
class GalleryFragment : Fragment() {
val galleryViewModel: GalleryViewModel by viewModel()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_gallery, container, false)
val textView: TextView = root.findViewById(R.id.text_gallery)
galleryViewModel.text.observe(viewLifecycleOwner, Observer {
textView.text = it
})
return root
}
} | 0 | Kotlin | 0 | 0 | 86493f318e76f0f9a3d177f66fcb57937aafe934 | 935 | KoinSample | Apache License 2.0 |
src/main/kotlin/com/vm/plugin/minecraft/commands/MoneyCardCommand.kt | Achang0611 | 347,946,435 | false | null | package com.vm.plugin.minecraft.commands
import com.vm.plugin.MoneyCardKotlin
import com.vm.plugin.minecraft.RequirePermissible
import com.vm.plugin.minecraft.Sender.hasPermission
import com.vm.plugin.minecraft.Sender.send
import com.vm.plugin.minecraft.commands.executors.GetCard
import com.vm.plugin.minecraft.commands.executors.GiveCard
import com.vm.plugin.utils.Error.Companion.throwIfNotNull
import com.vm.plugin.utils.JsonManager
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
class MoneyCardCommand : CommandExecutor, PlayerArgExecutor(), Helper {
override var nextExecutor: LinkedHashMap<String, ArgExecutor> = LinkedHashMap()
init {
MoneyCardKotlin.instance.getCommand("moneycard")?.setExecutor(this)
?: throw InternalError("Cannot register command")
nextExecutor.apply {
put("get", GetCard())
put("give", GiveCard())
// put("reload", ReloadPlugin())
}
}
private val message = JsonManager.Message
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
// card <mode>
val mode = args.getOrElse(0) { "null" }
getExecutorOrNull(mode)?.let {
it.execute(sender, args.drop(1))
return true
}
val p = sender as? Player ?: run {
val (msg, err) = message.getValue("warning.UnsupportedSender")
err.throwIfNotNull()
sender send msg
return true
}
getExecutorOrNull(mode, true)?.execute(p, args.drop(1)) ?: sendHelp(sender)
return true
}
override fun execute(sender: CommandSender, args: List<String>) {
throw UnsupportedOperationException()
}
override fun sendHelp(sender: CommandSender) {
for (argExecutor in nextExecutor.values) {
if (argExecutor is Helper) {
if (argExecutor is RequirePermissible) {
if (!sender.hasPermission(argExecutor.required)) {
continue
}
}
argExecutor.sendHelp(sender)
}
}
}
} | 0 | Kotlin | 0 | 0 | 59609c031c8f2b890807e2a8d4f3eff7dd7e2429 | 2,281 | MoneyCardKotlinReloaded | MIT License |
app/src/main/java/com/thewizrd/simpleweather/viewmodels/WeatherNowViewModel.kt | SimpleAppProjects | 82,603,731 | false | null | package com.thewizrd.simpleweather.viewmodels
import android.app.Application
import android.content.Context
import android.content.Intent
import android.location.LocationManager
import android.util.Log
import androidx.core.location.LocationManagerCompat
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.thewizrd.common.controls.WeatherUiModel
import com.thewizrd.common.controls.toUiModel
import com.thewizrd.common.helpers.locationPermissionEnabled
import com.thewizrd.common.location.LocationProvider
import com.thewizrd.common.location.LocationResult
import com.thewizrd.common.utils.ErrorMessage
import com.thewizrd.common.wearable.WearableSettings
import com.thewizrd.common.weatherdata.WeatherDataLoader
import com.thewizrd.common.weatherdata.WeatherRequest
import com.thewizrd.common.weatherdata.WeatherResult
import com.thewizrd.shared_resources.di.localBroadcastManager
import com.thewizrd.shared_resources.di.settingsManager
import com.thewizrd.shared_resources.exceptions.ErrorStatus
import com.thewizrd.shared_resources.exceptions.WeatherException
import com.thewizrd.shared_resources.locationdata.LocationData
import com.thewizrd.shared_resources.locationdata.buildEmptyGPSLocation
import com.thewizrd.shared_resources.utils.CommonActions
import com.thewizrd.shared_resources.utils.CustomException
import com.thewizrd.shared_resources.utils.JSONParser
import com.thewizrd.shared_resources.utils.Logger
import com.thewizrd.shared_resources.weatherdata.model.LocationType
import com.thewizrd.shared_resources.weatherdata.model.WeatherAlert
import com.thewizrd.simpleweather.R
import com.thewizrd.simpleweather.controls.ImageDataViewModel
import com.thewizrd.weather_api.weatherModule
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
sealed interface WeatherNowState {
val weather: WeatherUiModel?
val isLoading: Boolean
val errorMessages: List<ErrorMessage>
val isGPSLocation: Boolean
val locationData: LocationData?
val noLocationAvailable: Boolean
val showDisconnectedView: Boolean
val isImageLoading: Boolean
data class NoWeather(
override val weather: WeatherUiModel? = null,
override val isLoading: Boolean,
override val errorMessages: List<ErrorMessage>,
override val isGPSLocation: Boolean,
override val locationData: LocationData? = null,
override val noLocationAvailable: Boolean = false,
override val showDisconnectedView: Boolean = false,
override val isImageLoading: Boolean = false
) : WeatherNowState
data class HasWeather(
override val weather: WeatherUiModel,
override val isLoading: Boolean,
override val errorMessages: List<ErrorMessage>,
override val isGPSLocation: Boolean,
override val locationData: LocationData? = null,
override val noLocationAvailable: Boolean = false,
override val showDisconnectedView: Boolean = false,
override val isImageLoading: Boolean = false
) : WeatherNowState
}
private data class WeatherNowViewModelState(
val weather: WeatherUiModel? = null,
val isLoading: Boolean = false,
val errorMessages: List<ErrorMessage> = emptyList(),
val isGPSLocation: Boolean = false,
val locationData: LocationData? = null,
val noLocationAvailable: Boolean = false,
val showDisconnectedView: Boolean = false,
val scrollViewPosition: Int = 0,
val isImageLoading: Boolean = false
) {
fun toWeatherNowState(): WeatherNowState {
return if (weather?.isValid == true) {
WeatherNowState.HasWeather(
weather = weather,
isLoading = isLoading,
errorMessages = errorMessages,
isGPSLocation = isGPSLocation,
locationData = locationData,
noLocationAvailable = noLocationAvailable,
showDisconnectedView = showDisconnectedView,
isImageLoading = isImageLoading
)
} else {
WeatherNowState.NoWeather(
isLoading = isLoading,
errorMessages = errorMessages,
isGPSLocation = isGPSLocation,
locationData = locationData,
noLocationAvailable = noLocationAvailable,
showDisconnectedView = showDisconnectedView,
isImageLoading = isImageLoading
)
}
}
}
class WeatherNowViewModel(app: Application) : AndroidViewModel(app) {
private val viewModelState =
MutableStateFlow(WeatherNowViewModelState(isLoading = true, noLocationAvailable = true))
private val alertsState = MutableStateFlow<Collection<WeatherAlert>?>(emptyList())
private val imageDataState = MutableStateFlow<ImageDataViewModel?>(null)
private val weatherDataLoader = WeatherDataLoader()
private val wm = weatherModule.weatherManager
private val locationProvider = LocationProvider(app)
val uiState = viewModelState.map {
it.toWeatherNowState()
}.stateIn(
viewModelScope,
SharingStarted.Eagerly,
viewModelState.value.toWeatherNowState()
)
val weather = viewModelState.map {
it.weather
}.stateIn(
viewModelScope,
SharingStarted.Eagerly,
null
)
val imageData = imageDataState.stateIn(
viewModelScope,
SharingStarted.Lazily,
null
)
val alerts = alertsState.stateIn(
viewModelScope,
SharingStarted.Lazily,
alertsState.value
)
val errorMessages = viewModelState.map {
it.errorMessages
}.stateIn(
viewModelScope,
SharingStarted.Lazily,
viewModelState.value.errorMessages
)
private fun getLocationData(): LocationData? {
return viewModelState.value.locationData
}
fun initialize(locationData: LocationData? = null) {
viewModelState.update {
it.copy(isLoading = true)
}
viewModelScope.launch {
var locData = locationData ?: settingsManager.getHomeData()
if (settingsManager.useFollowGPS()) {
if (locData != null && settingsManager.getAPI() != locData.weatherSource) {
settingsManager.updateLocation(buildEmptyGPSLocation())
}
val result = updateLocation()
if (result is LocationResult.Changed) {
settingsManager.updateLocation(result.data)
locData = result.data
}
}
updateLocation(locData)
}
}
fun refreshWeather(forceRefresh: Boolean = false) {
viewModelState.update {
it.copy(isLoading = true)
}
viewModelScope.launch {
var locationChanged = false
if (settingsManager.useFollowGPS()) {
val result = updateLocation()
if (result is LocationResult.Changed) {
settingsManager.updateLocation(result.data)
weatherDataLoader.updateLocation(result.data)
locationChanged = true
}
}
val result = weatherDataLoader.loadWeatherResult(
WeatherRequest.Builder()
.forceRefresh(forceRefresh)
.loadAlerts()
.build()
)
if (result is WeatherResult.Success && !result.isSavedData) {
if (locationChanged) {
localBroadcastManager.sendBroadcast(Intent(CommonActions.ACTION_WEATHER_SENDLOCATIONUPDATE))
}
localBroadcastManager.sendBroadcast(
Intent(CommonActions.ACTION_WEATHER_SENDWEATHERUPDATE).apply {
putExtra(WearableSettings.KEY_PARTIAL_WEATHER_UPDATE, !locationChanged)
}
)
}
updateWeatherState(result)
}
}
private fun updateWeatherState(result: WeatherResult) {
when (result) {
is WeatherResult.Error -> {
viewModelState.update { state ->
if (state.locationData?.countryCode?.let { !wm.isRegionSupported(it) } == true) {
Logger.writeLine(
Log.WARN,
"Location: %s",
JSONParser.serializer(state.locationData)
)
Logger.writeLine(
Log.WARN,
CustomException(R.string.error_message_weather_region_unsupported)
)
}
val errorMessages =
state.errorMessages + ErrorMessage.WeatherError(result.exception)
state.copy(
errorMessages = errorMessages,
isLoading = false,
noLocationAvailable = false
)
}
}
is WeatherResult.NoWeather -> {
viewModelState.update { state ->
val errorMessages =
state.errorMessages + ErrorMessage.WeatherError(WeatherException(ErrorStatus.NOWEATHER))
state.copy(
errorMessages = errorMessages,
isLoading = false,
noLocationAvailable = false
)
}
}
is WeatherResult.Success -> {
val weatherData = result.data.toUiModel()
viewModelState.update { state ->
state.copy(
weather = weatherData,
isLoading = false,
noLocationAvailable = false,
isGPSLocation = state.locationData?.locationType == LocationType.GPS
)
}
alertsState.update {
result.data.weatherAlerts
}
viewModelScope.launch {
imageDataState.update {
weatherData.getImageData()
}
}
}
is WeatherResult.WeatherWithError -> {
val weatherData = result.data.toUiModel()
viewModelState.update { state ->
if (state.locationData?.countryCode?.let { !wm.isRegionSupported(it) } == true) {
Logger.writeLine(
Log.WARN,
"Location: %s",
JSONParser.serializer(state.locationData)
)
Logger.writeLine(
Log.WARN,
CustomException(R.string.error_message_weather_region_unsupported)
)
}
val errorMessages =
state.errorMessages + ErrorMessage.WeatherError(result.exception)
state.copy(
weather = weatherData,
errorMessages = errorMessages,
isLoading = false,
noLocationAvailable = false,
isGPSLocation = state.locationData?.locationType == LocationType.GPS
)
}
alertsState.update {
result.data.weatherAlerts
}
viewModelScope.launch {
imageDataState.update {
weatherData.getImageData()
}
}
}
}
}
fun setErrorMessageShown(error: ErrorMessage) {
viewModelState.update { state ->
state.copy(
errorMessages = state.errorMessages.filterNot { it == error }
)
}
}
private suspend fun updateLocation(): LocationResult {
var locationData = getLocationData()
if (settingsManager.useFollowGPS() && locationData?.locationType == LocationType.GPS) {
if (!getApplication<Application>().locationPermissionEnabled()) {
return LocationResult.NotChanged(locationData)
}
val locMan =
getApplication<Application>().getSystemService(Context.LOCATION_SERVICE) as? LocationManager
if (locMan == null || !LocationManagerCompat.isLocationEnabled(locMan)) {
locationData = settingsManager.getHomeData()
return LocationResult.NotChanged(locationData)
}
return locationProvider.getLatestLocationData(locationData)
}
return LocationResult.NotChanged(locationData)
}
fun updateLocation(locationData: LocationData?) {
viewModelState.update {
it.copy(locationData = locationData)
}
if (locationData?.isValid == true) {
viewModelState.update {
it.copy(locationData = locationData, noLocationAvailable = false)
}
weatherDataLoader.updateLocation(locationData)
refreshWeather(false)
} else {
checkInvalidLocation(locationData)
viewModelState.update {
it.copy(isLoading = false)
}
}
}
private fun checkInvalidLocation(locationData: LocationData?) {
if (locationData == null || !locationData.isValid) {
viewModelScope.launch {
withContext(Dispatchers.Default) {
Logger.writeLine(
Log.WARN,
"Location: %s",
JSONParser.serializer(locationData, LocationData::class.java)
)
Logger.writeLine(
Log.WARN,
"Home: %s",
JSONParser.serializer(
settingsManager.getHomeData(),
LocationData::class.java
)
)
Logger.writeLine(Log.WARN, IllegalStateException("Invalid location data"))
}
viewModelState.update {
it.copy(noLocationAvailable = true, isLoading = false)
}
}
}
}
fun onImageLoading() {
viewModelState.update {
it.copy(isImageLoading = true)
}
}
fun onImageLoaded() {
viewModelState.update {
it.copy(isImageLoading = false)
}
}
override fun onCleared() {
super.onCleared()
}
} | 0 | null | 8 | 37 | 56ddf09611d786e3bb2b802bdbcbbec648f0df9a | 14,957 | SimpleWeather-Android | Apache License 2.0 |
Common/src/main/java/com/nankung/common/module/base/viewmodel/BaseViewModel.kt | anunkwp | 245,392,754 | false | {"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "INI": 2, "Proguard": 3, "Kotlin": 91, "XML": 57, "Java": 1} | package com.nankung.common.module.base.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
/**
* Created by 「 <NAME> 」 on 16/3/2563. ^^
*/
open class BaseViewModel(application: Application) : AndroidViewModel(application){} | 1 | null | 1 | 1 | 852c96bbd9b9d41d42f5c27248cbe3f219dc9fda | 259 | KotlinMvvmStructure | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.