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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
composeApp/src/commonMain/kotlin/domain/AppLauncher.kt | CzinkeM | 825,876,701 | false | {"Kotlin": 99278, "Swift": 621} | package domain
expect class AppLauncher {
fun launchApp(uri: String)
}
| 0 | Kotlin | 0 | 0 | 28a2477f0d669b5c60a2052fe6e546af2ea13b78 | 76 | thevr-happyhour-browser | MIT License |
AppCheck-ins/app/src/main/java/com/example/iram/check_ins/Messages/Errors.kt | IramML | 141,610,474 | false | null | package com.example.iram.check_ins.Messages
enum class Errors {
NO_NETWORK_AVAILABLE,
HTTP_ERROR,
NO_APP_FOURSQUARE_AVAILABLE,
ERROR_CONNECTION_FSQR,
ERROR_EXCHANGE_TOKEN,
ERROR_SAVE_TOKEN,
PERMISSION_DENIED,
ERROR_QUERY
} | 0 | Kotlin | 0 | 0 | 511b10c4207402c0ddd99efde5e8689f07b07fd0 | 255 | CheckinsApp | MIT License |
store/src/commonMain/kotlin/org/mobilenativefoundation/store/store5/Store.kt | MobileNativeFoundation | 226,169,258 | false | {"Kotlin": 361534} | package org.mobilenativefoundation.store.store5
/**
* A Store is responsible for managing a particular data request.
*
* When you create an implementation of a Store, you provide it with a Fetcher, a function that defines how data will be fetched over network.
*
* You can also define how your Store will cache data in-memory and on-disk. See [StoreBuilder] for full configuration
*
* Example usage:
*
* val store = StoreBuilder
* .fromNonFlow<Pair<String, RedditConfig>, List<Post>> { (query, config) ->
* provideRetrofit().fetchData(query, config.limit).data.children.map(::toPosts)
* }
* .persister(reader = { (query, _) -> db.postDao().loadData(query) },
* writer = { (query, _), posts -> db.dataDAO().insertData(query, posts) },
* delete = { (query, _) -> db.dataDAO().clearData(query) },
* deleteAll = db.postDao()::clearAllFeeds)
* .build()
*
* // single shot response
* viewModelScope.launch {
* val data = store.fresh(key)
* }
*
* // get cached data and collect future emissions as well
* viewModelScope.launch {
* val data = store.cached(key, refresh=true)
* .collect{data.value=it }
* }
*
*/
interface Store<Key : Any, Output : Any> :
Read.Stream<Key, Output>,
Clear.Key<Key>,
Clear.All
| 57 | Kotlin | 202 | 3,174 | f9072fc59cc8bfe95cfe008cc8a9ce999301b242 | 1,318 | Store | Apache License 2.0 |
simplified-ui-catalog/src/main/java/org/nypl/simplified/ui/catalog/CatalogBookDetailEvent.kt | NYPL-Simplified | 30,199,881 | false | {"Kotlin": 2986168, "Java": 384210, "HTML": 109577, "Shell": 3481, "Ruby": 356} | package org.nypl.simplified.ui.catalog
import org.nypl.simplified.accounts.api.AccountID
import org.nypl.simplified.books.api.Book
import org.nypl.simplified.books.api.BookFormat
import org.nypl.simplified.ui.errorpage.ErrorPageParameters
sealed class CatalogBookDetailEvent {
data class OpenErrorPage(
val parameters: ErrorPageParameters
) : CatalogBookDetailEvent()
data class LoginRequired(
val account: AccountID
) : CatalogBookDetailEvent()
data class OpenViewer(
val book: Book,
val format: BookFormat
) : CatalogBookDetailEvent()
data class OpenFeed(
val feedArguments: CatalogFeedArguments
) : CatalogBookDetailEvent()
}
| 109 | Kotlin | 21 | 32 | 781e4e2122f1528253a6cf17931083944f91ceba | 671 | Simplified-Android-Core | Apache License 2.0 |
network/domain/src/main/java/com/pritom/dutta/movie/domain/utils/NetworkResult.kt | pritomdutta27 | 798,807,287 | false | {"Kotlin": 113585} | package com.pritom.dutta.movie.domain.utils
/**
* Created by <NAME> on 11/5/24.
*/
sealed class NetworkResult<out T>(
val data: T? = null,
val code: Int? = null,
val message: String? = null
) {
class Success<T>(data: T) : NetworkResult<T>(data)
class Error<T>(code: Int? = 404, message: String?, data: T? = null) :
NetworkResult<T>(data, code, message)
class Loading<T> : NetworkResult<T>()
}
| 0 | Kotlin | 0 | 0 | 04a4ebf3f1d03a603256d68d590f954b11ac2f89 | 430 | The-Theater-Movie-App | MIT License |
app/src/main/java/au/cmcmarkets/ticker/data/BlockchainRepository.kt | gabeira | 720,885,123 | false | {"Kotlin": 40007} | package au.cmcmarkets.ticker.data
import android.util.Log
import au.cmcmarkets.ticker.data.api.BitcoinApi
import au.cmcmarkets.ticker.data.model.Ticker
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
class BlockchainRepository @Inject constructor(private val retrofit: BitcoinApi) {
//Alternative way, explore new implementation
fun getTickersFlow() = flow { emit(retrofit.getTickers()) }
suspend fun getTickerBy(
currency: String,
onSuccess: (Ticker) -> Unit,
onFailed: (String) -> Unit
) {
try {
retrofit.getTickers()[currency]?.let {
Log.d("BlockchainRepository", "Last price ${currency}: ${it.last}")
onSuccess(it)
} ?: {
onFailed("Error loading ticker for $currency, not found")
}
} catch (e: Exception) {
val error = "Error loading ticker for $currency, ${e.localizedMessage}"
Log.e("BlockchainRepository", error)
onFailed(error)
}
}
} | 0 | Kotlin | 0 | 0 | de52d304b7932a12c7a122f7c51c04f6a5e3f6fc | 1,048 | bitcoin-ticker | MIT License |
kotlin-electron/src/jsMain/generated/electron/utility/UpdateTargetUrlEvent.kt | JetBrains | 93,250,841 | false | {"Kotlin": 12635434, "JavaScript": 423801} | // Generated by Karakum - do not modify it manually!
package electron.utility
typealias UpdateTargetUrlEvent = electron.core.UpdateTargetUrlEvent
| 38 | Kotlin | 162 | 1,347 | 997ed3902482883db4a9657585426f6ca167d556 | 148 | kotlin-wrappers | Apache License 2.0 |
app/src/main/java/com/mike/livedatademo/view/LiveDataDemoActivity.kt | AnkitDroidGit | 113,415,080 | false | null | package com.mike.livedatademo.view
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
class LiveDataDemoActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
| 0 | Kotlin | 0 | 0 | 20fab6604593e8d68d708a01b4f7ee6f10a9dd2a | 317 | LiveDataDemo | Apache License 2.0 |
src/main/kotlin/dev/vitorvidal/marketplace/domain/repository/AddressRepository.kt | vitorvidaldev | 572,271,482 | false | {"Kotlin": 45558} | package dev.vitorvidal.marketplace.domain.repository
import dev.vitorvidal.marketplace.domain.entity.Address
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.JpaSpecificationExecutor
import org.springframework.stereotype.Repository
import java.util.*
@Repository
interface AddressRepository : JpaRepository<Address, UUID>, JpaSpecificationExecutor<Address> | 0 | Kotlin | 0 | 1 | b6ee1a99e884eed6483c826517777a9ad7f9c8fd | 417 | Marketplace-API | MIT License |
lambda/src/main/kotlin/demo/SqsToDynamoFunction.kt | Guslington | 143,250,361 | false | null | package demo
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig
import com.amazonaws.services.lambda.runtime.Context
import com.amazonaws.services.lambda.runtime.RequestHandler
import com.amazonaws.services.sqs.model.Message
import com.google.gson.Gson
class SqsToDynamoFunction : RequestHandler<Message, String> {
override fun handleRequest(input: Message?, context: Context?): String {
//val environment = System.getenv("Environment")
val region = System.getenv("Region")
val tableName = System.getenv("OutboundDynamoTable")
val body = input!!.body
val gson = Gson();
val inbound = gson.fromJson(body, InboundMessage::class.java)
val dynamoDBClient = AmazonDynamoDBClientBuilder
.standard()
.withRegion(region)
.build()
val config = DynamoDBMapperConfig.builder()
.withTableNameOverride(DynamoDBMapperConfig.TableNameOverride
.withTableNameReplacement(tableName)).build();
val mapper = DynamoDBMapper(dynamoDBClient, config)
mapper.save(inbound)
return "{}"
}
} | 0 | Kotlin | 0 | 0 | a55ff3bec0a4d034f1762efeaf125dba2b92c100 | 1,320 | demo-serverless | MIT License |
buildSrc/src/main/kotlin/com/jetbrains/rd/gradle/tasks/util/FileSystem.kt | JetBrains | 107,686,809 | false | {"C#": 1845849, "Kotlin": 1605734, "C++": 1087156, "CMake": 45400, "Batchfile": 8969, "C": 688, "Shell": 672, "Dockerfile": 152} | package com.jetbrains.rd.gradle.tasks.util
import org.gradle.api.Project
import org.gradle.api.tasks.SourceSet
import java.io.File
import org.jetbrains.kotlin.gradle.plugin.*
val rdTmpDir: File = File(System.getProperty("java.io.tmpdir"), "rd")
get() {
field.mkdirs()
return field
}
val portFile = File(rdTmpDir, "port.txt")
get() {
rdTmpDir.mkdirs()
return field
}
val portFileStamp = portFile.resolveSibling("port.txt.stamp")
const val cppDirectorySystemPropertyKey = "model.out.src.cpp.dir"
const val ktDirectorySystemPropertyKey = "model.out.src.kt.dir"
const val csDirectorySystemPropertyKey = "model.out.src.cs.dir"
| 36 | C# | 53 | 384 | cbf1373f7a764d0aeccee3146c814a69cea34ae7 | 675 | rd | Apache License 2.0 |
src/main/kotlin/org/move/ide/inspections/fixes/EnableCompilerV2FeatureFix.kt | pontem-network | 279,299,159 | false | {"Kotlin": 2175494, "Move": 38620, "Lex": 5509, "HTML": 2114, "Java": 1275} | package org.move.ide.inspections.fixes
import com.intellij.model.SideEffectGuard
import com.intellij.model.SideEffectGuard.EffectType.SETTINGS
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import io.ktor.http.*
import org.move.cli.settings.moveSettings
import org.move.ide.inspections.DiagnosticIntentionFix
import org.move.ide.inspections.fixes.CompilerV2Feat.*
enum class CompilerV2Feat(val title: String) {
INDEXING("Index notation"),
RECEIVER_STYLE_FUNCTIONS("Receiver-Style functions"),
RESOURCE_CONTROL("Resource access control"),
PUBLIC_PACKAGE("`public(package)` function visibility");
}
class EnableCompilerV2FeatureFix(
element: PsiElement,
val feature: CompilerV2Feat
):
DiagnosticIntentionFix<PsiElement>(element) {
override fun getText(): String =
"Enable ${feature.title.quote()} feature of Aptos Move V2 Compiler in the settings"
override fun invoke(project: Project, file: PsiFile, element: PsiElement) {
@Suppress("UnstableApiUsage")
SideEffectGuard.checkSideEffectAllowed(SETTINGS)
project.moveSettings.modify {
when (feature) {
INDEXING -> it.enableIndexExpr = true
RECEIVER_STYLE_FUNCTIONS -> it.enableReceiverStyleFunctions = true
RESOURCE_CONTROL -> it.enableResourceAccessControl = true
PUBLIC_PACKAGE -> it.enablePublicPackage = true
}
}
}
} | 3 | Kotlin | 29 | 69 | 51a5703d064a4b016ff2a19c2f00fe8f8407d473 | 1,503 | intellij-move | MIT License |
zoomimage-compose-coil-base/src/main/kotlin/com/github/panpf/zoomimage/compose/coil/internal/AsyncImage.kt | panpf | 647,222,866 | false | null | package com.github.panpf.zoomimage.compose.coil.internal
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.DefaultAlpha
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.LayoutModifier
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.MeasureResult
import androidx.compose.ui.layout.MeasureScope
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Constraints
import coil.ImageLoader
import coil.compose.AsyncImagePainter
import coil.compose.AsyncImagePainter.State
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import coil.size.Dimension
import coil.size.Size
import coil.size.SizeResolver
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.mapNotNull
/**
* A composable that executes an [ImageRequest] asynchronously and renders the result.
*
* @param model Either an [ImageRequest] or the [ImageRequest.data] value.
* @param contentDescription Text used by accessibility services to describe what this image
* represents. This should always be provided unless this image is used for decorative purposes,
* and does not represent a meaningful action that a user can take.
* @param imageLoader The [ImageLoader] that will be used to execute the request.
* @param modifier Modifier used to adjust the layout algorithm or draw decoration content.
* @param transform A callback to transform a new [State] before it's applied to the
* [AsyncImagePainter]. Typically this is used to modify the state's [Painter].
* @param onState Called when the state of this painter changes.
* @param alignment Optional alignment parameter used to place the [AsyncImagePainter] in the given
* bounds defined by the width and height.
* @param contentScale Optional scale parameter used to determine the aspect ratio scaling to be
* used if the bounds are a different size from the intrinsic size of the [AsyncImagePainter].
* @param alpha Optional opacity to be applied to the [AsyncImagePainter] when it is rendered
* onscreen.
* @param colorFilter Optional [ColorFilter] to apply for the [AsyncImagePainter] when it is
* rendered onscreen.
* @param filterQuality Sampling algorithm applied to a bitmap when it is scaled and drawn into the
* destination.
* @param clipToBounds Optional controls whether content that is out of scope should be cropped
*/
@Composable
internal fun AsyncImage(
model: Any?,
contentDescription: String?,
imageLoader: ImageLoader,
modifier: Modifier = Modifier,
transform: (State) -> State = AsyncImagePainter.DefaultTransform,
onState: ((State) -> Unit)? = null,
alignment: Alignment = Alignment.Center,
contentScale: ContentScale = ContentScale.Fit,
alpha: Float = DefaultAlpha,
colorFilter: ColorFilter? = null,
filterQuality: FilterQuality = DrawScope.DefaultFilterQuality,
clipToBounds: Boolean = true,
) {
// Create and execute the image request.
val request = updateRequest(requestOf(model), contentScale)
val painter = rememberAsyncImagePainter(
request, imageLoader, transform, onState, contentScale, filterQuality
)
// Draw the content without a parent composable or subcomposition.
val sizeResolver = request.sizeResolver
Content(
modifier = if (sizeResolver is ConstraintsSizeResolver) {
modifier.then(sizeResolver)
} else {
modifier
},
painter = painter,
contentDescription = contentDescription,
alignment = alignment,
contentScale = contentScale,
alpha = alpha,
colorFilter = colorFilter,
clipToBounds = clipToBounds
)
}
/** Draws the current image content. */
@Composable
internal fun Content(
modifier: Modifier,
painter: Painter,
contentDescription: String?,
alignment: Alignment,
contentScale: ContentScale,
alpha: Float,
colorFilter: ColorFilter?,
clipToBounds: Boolean = true,
) = Layout(
modifier = modifier
.contentDescription(contentDescription)
.let { if (clipToBounds) it.clipToBounds() else it }
.then(
ContentPainterModifier(
painter = painter,
alignment = alignment,
contentScale = contentScale,
alpha = alpha,
colorFilter = colorFilter
)
),
measurePolicy = { _, constraints ->
layout(constraints.minWidth, constraints.minHeight) {}
}
)
@Composable
internal fun updateRequest(request: ImageRequest, contentScale: ContentScale): ImageRequest {
return if (request.defined.sizeResolver == null) {
val sizeResolver = if (contentScale == ContentScale.None) {
SizeResolver(Size.ORIGINAL)
} else {
remember { ConstraintsSizeResolver() }
}
request.newBuilder().size(sizeResolver).build()
} else {
request
}
}
/** A [SizeResolver] that computes the size from the constrains passed during the layout phase. */
internal class ConstraintsSizeResolver : SizeResolver, LayoutModifier {
private val _constraints = MutableStateFlow(ZeroConstraints)
override suspend fun size() = _constraints.mapNotNull(Constraints::toSizeOrNull).first()
override fun MeasureScope.measure(
measurable: Measurable,
constraints: Constraints
): MeasureResult {
// Cache the current constraints.
_constraints.value = constraints
// Measure and layout the content.
val placeable = measurable.measure(constraints)
return layout(placeable.width, placeable.height) {
placeable.place(0, 0)
}
}
fun setConstraints(constraints: Constraints) {
_constraints.value = constraints
}
}
@Stable
private fun Modifier.contentDescription(contentDescription: String?): Modifier {
if (contentDescription != null) {
return semantics {
this.contentDescription = contentDescription
this.role = Role.Image
}
} else {
return this
}
}
@Stable
private fun Constraints.toSizeOrNull() = when {
isZero -> null
else -> Size(
width = if (hasBoundedWidth) Dimension(maxWidth) else Dimension.Undefined,
height = if (hasBoundedHeight) Dimension(maxHeight) else Dimension.Undefined
)
} | 0 | null | 3 | 50 | 90b43fc7f56cf9e746f87d641480bbd3cfdc7dce | 7,049 | zoomimage | Apache License 2.0 |
app/src/main/kotlin/com/whereismymotivation/ui/common/share/Payload.kt | unusualcodeorg | 730,655,456 | false | {"Kotlin": 472092} | package com.whereismymotivation.ui.common.share
import android.graphics.Bitmap
import androidx.annotation.Keep
data class Payload<T> private constructor(
val type: Type,
val data: T,
val bitmap: Bitmap? = null
) {
companion object {
fun <T> text(data: T) = Payload(Type.TEXT, data)
fun <T> image(data: T, bitmap: Bitmap) = Payload(Type.IMAGE, data, bitmap)
fun <T> whatsappText(data: T) = Payload(Type.WHATSAPP_TEXT, data)
fun <T> whatsappImage(data: T, bitmap: Bitmap) = Payload(Type.WHATSAPP_IMAGE, data, bitmap)
}
@Keep
enum class Type {
TEXT,
IMAGE,
WHATSAPP_TEXT,
WHATSAPP_IMAGE
}
} | 0 | Kotlin | 4 | 38 | 5b77e6a6b14ae9ad21e8edd55e8c9b3cc2066f75 | 690 | wimm-android-app | Apache License 2.0 |
src/main/kotlin/org/cascadebot/slashcommandstest/commandmeta/CommandPath.kt | CascadeBot | 393,667,127 | false | null | package org.cascadebot.slashcommandstest.commandmeta
class CommandPath(var rootId: Long) {
var path: List<String> = listOf()
private set
constructor(rootId: Long, path: List<String>) : this(rootId) {
this.path = path;
}
override fun equals(other: Any?): Boolean {
return when(other) {
is CommandPath -> {
var matches = this.rootId == other.rootId
if (this.path.size != other.path.size) {
matches = false
}
if (!matches) {
return false
}
if (this.path.indices.any { this.path[it] != other.path[it] }) {
matches = false
}
matches
}
else -> {
false;
}
}
}
override fun hashCode(): Int {
var result = rootId.hashCode()
result = 31 * result + path.hashCode()
return result
}
} | 0 | Kotlin | 0 | 0 | b43987c93539d353d24bfc7fd6a222d790b6474d | 1,013 | SlashCommandsTest | MIT License |
app/src/main/java/at/ict4d/covid19map/ui/tabs/TabContainerFragmentStateAdapter.kt | ICT4Dat | 250,661,220 | false | null | package at.ict4d.covid19map.ui.tabs
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import at.ict4d.covid19map.ui.tabs.list.MapPostListFragment
import at.ict4d.covid19map.ui.tabs.map.MapContainerFragment
class TabContainerFragmentStateAdapter(
fragmentManager: FragmentManager,
lifecycle: Lifecycle
) : FragmentStateAdapter(fragmentManager, lifecycle) {
override fun getItemCount() = 2
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> MapContainerFragment.newInstance()
1 -> MapPostListFragment.newInstance()
else -> throw IllegalArgumentException("position tab not valid")
}
}
}
| 0 | Kotlin | 0 | 1 | cee51a8d576d2330b17c28bba4246b1f0107f6d9 | 819 | safecast-covid19-android-map | Apache License 2.0 |
composeApp/src/commonMain/kotlin/org/sn/notebykmp/presentation/screen/notes/navigation/NotesNavigation.kt | SaeedNoshadi89 | 798,733,711 | false | {"Kotlin": 142944, "Swift": 522, "HTML": 280} | package org.sn.notebykmp.presentation.screen.notes.navigation
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavOptions
import androidx.navigation.compose.composable
import org.sn.notebykmp.presentation.screen.notes.NotesScreen
const val notesRoute = "notes_route"
fun NavController.navigateToNotes( navOptions: NavOptions? = null){
navigate(notesRoute, navOptions)
}
fun NavGraphBuilder.notesScreenGraph(
onEditNote: (noteId: String) -> Unit,
onNavigateToBookmark: () -> Unit,
) {
composable(
route = notesRoute
) {
NotesScreen(onNavigateToBookmark = onNavigateToBookmark, onEditNote = {onEditNote(it)})
}
} | 0 | Kotlin | 2 | 31 | 27416f64e3fcf1c6c572a4194dc794d7bc12f758 | 716 | NoteByKMP | MIT License |
lovebird-common/src/main/kotlin/com/lovebird/common/util/RandomUtils.kt | wooda-ege | 722,352,043 | false | {"Kotlin": 249715, "HTML": 190698, "Shell": 1813} | package com.lovebird.common.util
object RandomUtils {
private const val ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvxyz"
fun generateCode(): String {
val random = java.util.Random()
return (1..8)
.map { ALPHA_NUMERIC_STRING[random.nextInt(ALPHA_NUMERIC_STRING.length)] }
.joinToString("")
}
}
| 1 | Kotlin | 0 | 11 | d23922be1370650cc51e95e44468bfbad7648fa7 | 348 | lovebird-server | MIT License |
src/jvmMain/kotlin/khala/internal/zmq/bindings/ZmqSocket.kt | ardenit | 292,069,266 | false | {"Kotlin": 108807} | package khala.internal.zmq.bindings
import org.zeromq.ZMQ
internal actual class ZmqSocket(val socket: ZMQ.Socket) {
fun connect(address: String) {
socket.connect(address)
}
fun bind(address: String) {
socket.bind(address)
}
actual fun close() {
socket.close()
}
} | 3 | Kotlin | 0 | 0 | 8955092d9c6c36b1a7407017ef2a327e51e6d7b4 | 316 | khala-internal | Apache License 2.0 |
src/main/kotlin/at/cpickl/gadsu/acupuncture/acupuncts.kt | christophpickl | 56,092,216 | false | null | package at.cpickl.gadsu.acupuncture
/**
* Right now only contains the "important" ones. Would need to mark some of them as "important", but define EACH AND EVERY one of them here!
*/
/*
object Acupuncts {
val allPuncts = lazy {
byMeridian.values.flatMap { it }
}
fun byMeridian(meridian: Meridian) = byMeridian[meridian]!!
}
private class AcupunctsPunctBuilder() {
// needs to be linked to keep ordering
private val map = LinkedHashMap<Meridian, LinkedList<Acupunct>>()
private lateinit var currentMeridian: Meridian
fun meridian(meridian: Meridian, func: AcupunctsPunctBuilder.() -> Unit): AcupunctsPunctBuilder {
currentMeridian = meridian
with(this, func)
return this
}
fun punct(
number: Int,
germanName: String,
chineseName: String,
localisation: String,
indications: String = "",
note: String = "",
flags: List<AcupunctFlag> = emptyList()
): AcupunctsPunctBuilder {
if (!map.containsKey(currentMeridian)) {
map.put(currentMeridian, LinkedList())
}
map[currentMeridian]!!.add(Acupunct.build(currentMeridian, number, germanName, chineseName, note, localisation, indications, flags))
return this
}
fun build() = map
}
*/
| 43 | Kotlin | 1 | 2 | f6a84c42e1985bc53d566730ed0552b3ae71d94b | 1,344 | gadsu | Apache License 2.0 |
gto-support-androidx-room/src/main/kotlin/org/ccci/gto/android/common/androidx/room/RoomDatabase+Flow.kt | CruGlobal | 30,609,844 | false | {"Kotlin": 825671, "Java": 253176, "Prolog": 179} | package org.ccci.gto.android.common.androidx.room
import android.annotation.SuppressLint
import androidx.room.CoroutinesRoom.Companion.createFlow
import androidx.room.RoomDatabase
@SuppressLint("RestrictedApi")
fun RoomDatabase.changeFlow(vararg tableName: String) = createFlow(
this,
inTransaction = false,
tableNames = arrayOf(*tableName),
callable = {}
)
| 13 | Kotlin | 2 | 9 | 85a6c4bc4edffc5670b375a9029b9bbd5b5c5f4e | 376 | android-gto-support | MIT License |
libCamera/src/main/java/io/github/toyota32k/lib/camera/gesture/FocusGestureListener.kt | toyota-m2k | 594,937,009 | false | {"Kotlin": 475131, "Shell": 17521} | package io.github.toyota32k.lib.camera.gesture
import android.view.GestureDetector
import android.view.MotionEvent
import androidx.camera.core.FocusMeteringAction
import androidx.concurrent.futures.await
import androidx.core.view.GestureDetectorCompat
import io.github.toyota32k.lib.camera.TcLib
import kotlinx.coroutines.launch
import java.lang.ref.WeakReference
class FocusGestureListener(
cameraOwner: ICameraGestureOwner,
private val enableFocus:Boolean,
private val longTapToFocus:Boolean,
var singleTapCustomAction:(()->Boolean)? = null,
var longTapCustomAction:(()->Boolean)? = null
) : GestureDetector.SimpleOnGestureListener() {
companion object {
val logger = TcLib.logger
}
private val cameraOwnerRef = WeakReference(cameraOwner)
private fun focus(e:MotionEvent):Boolean {
if(!enableFocus) return false
val cameraOwner = cameraOwnerRef.get() ?: return false
val previewView = cameraOwner.previewView ?: return false
val camera = cameraOwner.camera ?: return false
val meteringPointFactory = previewView.meteringPointFactory
val focusPoint = meteringPointFactory.createPoint(e.x, e.y)
val meteringAction = FocusMeteringAction
.Builder(focusPoint).build()
cameraOwner.gestureScope.launch {
try {
camera.cameraControl
.startFocusAndMetering(meteringAction)
.await()
} catch(e:Throwable) {
logger.error(e)
}
}
return true
}
private fun invokeCustomCommand(fn:(()->Boolean)?):Boolean {
return fn?.invoke() ?: return false
}
override fun onSingleTapUp(e: MotionEvent): Boolean {
logger.debug("single tap")
if(invokeCustomCommand(singleTapCustomAction)) {
return true
}
return if(!longTapToFocus) {
focus(e)
} else false
}
override fun onLongPress(e: MotionEvent) {
logger.debug("long tap")
if(invokeCustomCommand(longTapCustomAction)) {
return
}
if(longTapToFocus) {
focus(e)
}
}
private val detector = GestureDetectorCompat(cameraOwner.context, this)
fun onTouchEvent(event: MotionEvent):Boolean {
return detector.onTouchEvent(event)
}
} | 2 | Kotlin | 0 | 0 | 497d4de9572937a209ef0153cf04feb287ae5118 | 2,379 | android-camera | Apache License 2.0 |
DCC/app/src/main/java/com/rachelleboyette/desertcodecampdemo/model/dto/CatImageDto.kt | rtimm17 | 214,676,610 | false | null | package com.rachelleboyette.desertcodecampdemo.model.dto
import com.rachelleboyette.desertcodecampdemo.model.CatImage
class CatImageDto(val url: String) {
companion object {
fun fromDto(dto: CatImageDto): CatImage {
return CatImage(dto.url)
}
}
} | 0 | Kotlin | 0 | 0 | 461d0a3ca50de7bd424441081500eed67c08663e | 285 | DesertCodeCamp-Kotlin | MIT License |
compiler/testData/codegen/box/delegatedProperty/accessTopLevelDelegatedPropertyInClinit.kt | MobilePetroleum | 44,005,900 | true | {"Java": 15729962, "Kotlin": 10738386, "JavaScript": 176060, "Protocol Buffer": 43096, "HTML": 25327, "Lex": 17330, "ANTLR": 9689, "CSS": 9358, "Groovy": 5199, "Shell": 4638, "Batchfile": 3703, "IDL": 3251} | // KT-5612
class Delegate {
public fun getValue(thisRef: Any?, prop: PropertyMetadata): String {
return "OK"
}
}
val prop by Delegate()
val a = prop
fun box() = a
| 0 | Java | 0 | 0 | 396f38e9b3b2eb9af9b873a12d048e19c8f456cf | 183 | kotlin | Apache License 2.0 |
src/main/kotlin/io/github/guttenbase/export/zip/ZipDatabaseMetaDataWriter.kt | guttenbase | 644,774,036 | false | {"Kotlin": 537749, "PLpgSQL": 271} | package io.github.guttenbase.export.zip
import io.github.guttenbase.meta.DatabaseMetaData
import java.io.IOException
import java.sql.SQLException
import kotlin.Throws
/**
* Write ZIP file entry containing information about data base such as schema or version.
*
*
* 2012-2034 akquinet tech@spree
*
*
* @author M. Dahm
*/
class ZipDatabaseMetaDataWriter : ZipAbstractMetaDataWriter() {
@Throws(IOException::class, SQLException::class)
fun writeDatabaseMetaDataEntry(databaseMetaData: DatabaseMetaData): ZipDatabaseMetaDataWriter {
setProperty(DATABASE_SCHEMA, databaseMetaData.schema)
setProperty(DATABASE_NAME, databaseMetaData.databaseMetaData.databaseProductName)
setProperty(DATABASE_MAJOR_VERSION, java.lang.String.valueOf(databaseMetaData.databaseMetaData.databaseMajorVersion))
setProperty(DATABASE_MINOR_VERSION, java.lang.String.valueOf(databaseMetaData.databaseMetaData.databaseMinorVersion))
setProperty(DATABASE_TYPE, databaseMetaData.databaseType.name)
var i = 1
databaseMetaData.tableMetaData.forEach {
setProperty(TABLE_NAME + (i++), it.tableName)
}
return this
}
companion object {
const val DATABASE_NAME = "Database"
const val DATABASE_TYPE = "Database-Type"
const val DATABASE_MAJOR_VERSION = "Major-Version"
const val DATABASE_MINOR_VERSION = "Minor-Version"
const val DATABASE_SCHEMA = "Database-Schema"
const val TABLE_NAME = "Table-Name"
}
}
| 0 | Kotlin | 0 | 1 | 5f6f8e10ef8a478052074d7bdab311a387f909d5 | 1,455 | guttenbase | Apache License 2.0 |
app/src/main/java/com/katana/koin/di/app_module.kt | cuongnv219 | 211,757,729 | false | null | package com.katana.koin.di
import android.content.Context
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.katana.koin.data.AppDataManager
import com.katana.koin.data.DataManager
import com.katana.koin.data.local.prefs.AppPrefsHelper
import com.katana.koin.data.local.prefs.PrefsHelper
import com.katana.koin.data.remote.ApiHelper
import com.katana.koin.data.remote.AppApiHelper
import com.utils.SchedulerProvider
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@InstallIn(SingletonComponent::class)
@Module
class AppModule {
@Singleton
@Provides
fun provideSchedulerProvider() = SchedulerProvider()
@Singleton
@Provides
fun provideAppApiHelper(): ApiHelper = AppApiHelper()
@Singleton
@Provides
fun provideAppPrefsHelper(@ApplicationContext context: Context, gson: Gson): PrefsHelper = AppPrefsHelper(context, "kaz", gson)
@Singleton
@Provides
fun provideGson(): Gson = GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
@Singleton
@Provides
fun provideAppDataManager(prefsHelper: PrefsHelper, apiHelper: ApiHelper): DataManager = AppDataManager(prefsHelper, apiHelper)
} | 0 | Kotlin | 0 | 1 | 298323acccd6a92306a8a8e8a7d331aff682e600 | 1,336 | mvvm-rx | Apache License 2.0 |
app/src/main/java/com/nekotoneko/redmoon/darkforestengine/sample/storyviewer/StoryView.kt | silwek | 209,760,391 | false | null | package com.nekotoneko.redmoon.darkforestengine.sample.storyviewer
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.nekotoneko.redmoon.darkforestengine.sample.R
import com.nekotoneko.redmoon.darkforestengine.sample.models.Scene
import com.nekotoneko.redmoon.darkforestengine.sample.models.SceneGroup
import kotlinx.android.synthetic.main.view_story.view.*
/**
* @author Silwèk on 2019-08-17
*/
class StoryView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
var storyActionListener: StoryActionListener? = null
var choicesAdaper: SceneChoicesAdapter? = null
var choicesList: RecyclerView? = null
fun onStoryLoad() {
progressBar.visibility = View.VISIBLE
btNext.setOnClickListener(null)
btNext.visibility = View.GONE
choicesList = findViewById(R.id.choices)
choicesList?.visibility = View.GONE
choicesAdaper = SceneChoicesAdapter(context)
choicesAdaper?.clickListener = object : SceneChoicesAdapter.SceneChoiceClickListener {
override fun onChoice(sceneChoice: Scene) {
storyActionListener?.onChoose(sceneChoice)
}
}
choicesList?.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
choicesList?.adapter = choicesAdaper
}
fun display(scene: Scene) {
progressBar.visibility = GONE
(storyContent as StoryContentView).display(scene.content)
btNext.setOnClickListener {
storyActionListener?.onNext()
}
btNext.visibility = View.VISIBLE
choicesList?.visibility = View.GONE
choicesAdaper?.setItems(emptyList())
}
fun display(scene: Scene, choices: List<Scene>) {
progressBar.visibility = GONE
if (choices.isEmpty()) {
display(scene)
} else if (scene is SceneGroup && scene.type == SceneGroup.STORY_CROSSROADS) {
display(choices[0])
} else {
(storyContent as StoryContentView).display(scene.content)
btNext.setOnClickListener(null)
btNext.visibility = View.GONE
choicesList?.visibility = View.VISIBLE
choicesAdaper?.setItems(choices)
}
}
interface StoryActionListener {
fun onNext()
fun onChoose(scene: Scene)
}
} | 0 | Kotlin | 0 | 0 | 0341ed46c8053f4a6a61999da7e1904d46dff56d | 2,631 | darkforestengine | MIT License |
features/recoverypassword/src/main/java/br/com/crosslife/recoverypassword/viewmodel/RecoveryPasswordViewModel.kt | ujizin | 361,117,604 | false | null | package br.com.crosslife.recoverypassword.viewmodel
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import br.com.crosslife.commons.extensions.notify
import br.com.crosslife.commons.extensions.viewmodel.ViewModelExtensions
import br.com.crosslife.domain.model.PasswordNotEqualsError
import br.com.crosslife.domain.model.Result
import br.com.crosslife.domain.repository.UserRepository
import br.com.crosslife.navigation.Screen
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.onStart
import javax.inject.Inject
@HiltViewModel
class RecoveryPasswordViewModel @Inject constructor(
private val userRepository: UserRepository,
savedStateHandle: SavedStateHandle,
) : ViewModel(), ViewModelExtensions {
private val token = savedStateHandle.get<String>(Screen.RecoveryPassword.TOKEN_ARG).orEmpty()
val recoveryPasswordState: StateFlow<Result<Unit>> = MutableStateFlow(Result.Initial)
fun changePassword(newPassword: String, confirmNewPassword: String) {
userRepository.changePasswordWithToken(
token,
newPassword,
).onStart {
check(newPassword == confirmNewPassword) { throw PasswordNotEqualsError() }
}.notify(viewModelScope, recoveryPasswordState())
}
} | 0 | Kotlin | 0 | 2 | a577fdeefb9b707b308c1bb1f4d8f8373735704a | 1,431 | crosslife-suzano-mobile | MIT License |
SceytChatUiKit/src/main/java/com/sceyt/sceytchatuikit/persistence/filetransfer/NeedMediaInfoData.kt | sceyt | 549,073,085 | false | null | package com.sceyt.sceytchatuikit.persistence.filetransfer
import android.util.Size
import com.sceyt.sceytchatuikit.data.models.messages.SceytAttachment
sealed class NeedMediaInfoData(val item: SceytAttachment) {
class NeedDownload(attachment: SceytAttachment) : NeedMediaInfoData(attachment)
class NeedThumb(attachment: SceytAttachment, val size: Size) : NeedMediaInfoData(attachment)
} | 0 | Kotlin | 0 | 0 | 0b135841180b7c4fdd66b1b0f7655d8d79fe8a03 | 396 | sceyt-chat-android-uikit | MIT License |
Android/dokit-ft/src/main/java/com/didichuxing/doraemonkit/kit/filemanager/bean/SaveFileInfo.kt | didi | 144,705,602 | false | null | package com.didichuxing.doraemonkit.kit.filemanager.bean
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2020/6/23-18:18
* 描 述:
* 修订历史:
* ================================================
*/
data class DirInfo(val dirPath: String, val fileName: String) {
} | 252 | null | 3074 | 20,003 | 166a1a92c6fd509f6b0ae3e8dd9993f631b05709 | 312 | DoKit | Apache License 2.0 |
script/src/main/java/com/angcyo/script/DslScript.kt | angcyo | 229,037,684 | false | {"Kotlin": 3430781, "JavaScript": 5542, "HTML": 1598} | package com.angcyo.script
import android.content.Context
import com.angcyo.library.L
import com.angcyo.library.app
import com.angcyo.library.utils.isPublic
import com.angcyo.script.annotation.ScriptInject
import com.angcyo.script.core.Console
import com.eclipsesource.v8.V8
import com.eclipsesource.v8.V8Array
import com.eclipsesource.v8.V8Object
import com.eclipsesource.v8.V8Value
/**
* Java JavaScript 互操作, Java 解析 js脚本并执行
*
* https://github.com/cashapp/zipline
*
* https://eclipsesource.com/blogs/tutorials/getting-started-with-j2v8/
*
* Email:<EMAIL>
* @author angcyo
* @date 2021/12/22
* Copyright (c) 2020 ShenZhen Wayto Ltd. All rights reserved.
*/
class DslScript {
lateinit var v8: V8
//对象保持, 用来释放
val v8ObjectHoldSet = mutableSetOf<V8Value>()
//<editor-fold desc="核心对象">
var console: Console
//<e/ditor-fold desc="核心对象">
init {
console = Console()
}
/**初始化引擎*/
fun initEngine(context: Context) {
val dir = context.getExternalFilesDir("v8")
v8 = V8.createV8Runtime("v8", dir?.absolutePath)
injectObj(console)
}
/**释放引擎资源*/
fun releaseEngine() {
v8ObjectHoldSet.forEach {
try {
it.release()
} catch (e: Exception) {
e.printStackTrace()
}
}
v8ObjectHoldSet.clear()
try {
v8.release(true)
} catch (e: Exception) {
e.printStackTrace()
}
}
/**运行脚本, 默认是主线程*/
fun runScript(script: String) {
L.i("准备执行脚本↓\n$script")
try {
val result = v8.executeScript(script)
L.i("脚本返回:$result")
} catch (e: Exception) {
e.printStackTrace()
}
}
/**注入对象*/
fun injectObj(obj: Any, key: String? = null) {
val clsInject = obj.javaClass.getAnnotation(ScriptInject::class.java)
if (clsInject == null || !clsInject.ignore) {
//注入对象
var objKey: String = key ?: clsInject?.key ?: obj.javaClass.simpleName
if (objKey.isEmpty()) {
objKey = obj.javaClass.simpleName
}
v8.add(objKey, convertToV8Value(obj))
}
}
fun convertToV8Value(obj: Any?): V8Value? {
val result: V8Value? = when (obj) {
is Collection<*> -> {
V8Array(v8).apply {
obj.forEach {
push(convertToV8Obj(it))
}
}
}
is Array<*> -> {
V8Array(v8).apply {
obj.forEach {
push(convertToV8Obj(it))
}
}
}
is Map<*, *> -> {
V8Object(v8).apply {
obj.forEach { entry ->
val key = entry.key
if (key is String) {
add(key, convertToV8Value(entry.value))
}
}
}
}
else -> {
convertToV8Obj(obj)
}
}
result?.let { v8ObjectHoldSet.add(it) }
return result
}
fun convertToV8Obj(obj: Any?): V8Object? {
if (obj == null) {
return null
}
val v8Obj = V8Object(v8)
v8ObjectHoldSet.add(v8Obj)
obj.javaClass.apply {
//注入属性
for (f in declaredFields) {
val fInject = f.getAnnotation(ScriptInject::class.java)
if ((fInject == null && f.isPublic()) || fInject?.ignore == false) {
f.isAccessible = true
//注入对象的属性
var key: String = fInject?.key ?: f.name
if (key.isEmpty()) {
key = f.name
}
val value = f.get(obj)
when {
value == null -> v8Obj.addNull(key)
Boolean::class.java.isAssignableFrom(f.type) -> v8Obj.add(
key,
value as Boolean
)
Int::class.java.isAssignableFrom(f.type) -> v8Obj.add(key, value as Int)
Long::class.java.isAssignableFrom(f.type) -> v8Obj.add(
key,
(value as Long).toInt()
)
Float::class.java.isAssignableFrom(f.type) -> v8Obj.add(
key,
(value as Float).toDouble()
)
Double::class.java.isAssignableFrom(f.type) -> v8Obj.add(
key,
value as Double
)
Number::class.java.isAssignableFrom(f.type) -> v8Obj.add(
key,
(value as Number).toInt()
)
String::class.java.isAssignableFrom(f.type) -> v8Obj.add(
key,
value as String
)
else -> v8Obj.add(key, convertToV8Value(value))
}
}
}
//注入方法
for (m in methods) {
val mInject = m.getAnnotation(ScriptInject::class.java)
if (m.isPublic() && (mInject == null || !mInject.ignore)) {
m.isAccessible = true
var key: String = mInject?.key ?: m.name
val includeReceiver = mInject?.includeReceiver ?: false
if (key.isEmpty()) {
key = m.name
}
val v8Callback = v8Obj.registerJavaMethod(
obj,
m.name,
key,
m.parameterTypes,
includeReceiver
)
v8ObjectHoldSet.add(v8Callback)
}
}
}
return v8Obj
}
}
/**脚本*/
fun script(context: Context = app(), action: DslScript.() -> Unit): DslScript {
return DslScript().apply {
initEngine(context)
action(this)
releaseEngine()
}
}
| 0 | Kotlin | 4 | 4 | 9e5646677153f5fba31c31a1bc8ce5753b84660a | 6,459 | UICoreEx | MIT License |
okmock-plugin/src/main/java/com/airsaid/okmock/plugin/transform/AbstractTransform.kt | Airsaid | 389,940,259 | false | {"Java": 73786, "Kotlin": 30836} | /*
* Copyright 2021 Airsaid. https://github.com/airsaid
*
* 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.airsaid.okmock.plugin.transform
import com.android.SdkConstants
import com.android.build.api.transform.*
import com.android.build.gradle.internal.pipeline.TransformManager
import com.android.utils.FileUtils
import com.google.common.collect.ImmutableSet
import com.google.common.io.Files
import org.gradle.api.Project
import org.gradle.api.provider.Property
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.util.*
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
import java.util.zip.ZipOutputStream
/**
* @author airsaid
*/
abstract class AbstractTransform(private val project: Project, private val isDebug: Property<Boolean>) : Transform(), TransformHandle {
private var mStartInvocationTime = 0L
override fun getInputTypes(): MutableSet<QualifiedContent.ContentType> =
TransformManager.CONTENT_CLASS
override fun getScopes(): MutableSet<in QualifiedContent.Scope> =
ImmutableSet.of(QualifiedContent.Scope.PROJECT, QualifiedContent.Scope.SUB_PROJECTS)
override fun isIncremental() = true
override fun isCacheable() = true
override fun onTransformBefore(invocation: TransformInvocation) {
if (isDebug.get()) {
mStartInvocationTime = System.nanoTime()
}
}
override fun transform(transformInvocation: TransformInvocation) {
super.transform(transformInvocation)
log("> Transform isIncremental: ${transformInvocation.isIncremental}")
if (!transformInvocation.isIncremental) {
transformInvocation.outputProvider.deleteAll()
}
onTransformBefore(transformInvocation)
for (input in transformInvocation.inputs) {
for (jarInput in input.jarInputs) {
log("+---------------------------------------")
log("| Start handler input jar: ${jarInput.file.canonicalPath}")
if (transformInvocation.isIncremental) {
log("| Skip: ${jarInput.status}")
if (jarInput.status == Status.NOTCHANGED) {
continue
} else if (jarInput.status == Status.REMOVED) {
jarInput.file.delete()
continue
}
}
val inputJar = jarInput.file
val outputJar = transformInvocation.outputProvider.getContentLocation(
jarInput.name, jarInput.contentTypes, jarInput.scopes, Format.JAR
)
handlerJar(transformInvocation, inputJar, outputJar)
}
for (dirInput in input.directoryInputs) {
log("+---------------------------------------")
log("| Start handler input dir: ${dirInput.file.canonicalPath}")
val inputDir = dirInput.file
val outputDir = transformInvocation.outputProvider.getContentLocation(
dirInput.name, dirInput.contentTypes, dirInput.scopes, Format.DIRECTORY
)
if (transformInvocation.isIncremental) {
if (dirInput.changedFiles.isEmpty()) {
log("| Skip: changedFiles is empty!")
continue
}
dirInput.changedFiles.forEach { (changedFile, state) ->
if (state == Status.REMOVED) {
log("| changedFile: ${changedFile.canonicalPath}, state: $state")
changedFile.delete()
} else {
changedFile.filterTransformFile { inputFile ->
log("| changedFile: ${inputFile.canonicalPath}, state: $state")
val outputFile = File(outputDir, FileUtils.relativePossiblyNonExistingPath(inputFile, inputDir))
inputFile.transform(transformInvocation, outputFile)
}
}
}
} else {
inputDir.filterTransformFile { inputFile ->
log("| ${inputFile.canonicalPath}")
val outputFile = File(outputDir, FileUtils.relativePossiblyNonExistingPath(inputFile, inputDir))
inputFile.transform(transformInvocation, outputFile)
}
}
}
}
onTransformAfter(transformInvocation)
}
private fun handlerJar(invocation: TransformInvocation, inputJar: File, outputJar: File) {
val jarInputClass: HashSet<Pair<String, ByteArray>> = hashSetOf()
ZipInputStream(FileInputStream(inputJar)).use { zipInputStream ->
var entry: ZipEntry? = zipInputStream.nextEntry
while (entry != null) {
if (!entry.isDirectory && entry.name.endsWith(SdkConstants.DOT_CLASS)) {
log("| ${entry.name}")
val outputBytes = onTransform(invocation, zipInputStream.readBytes())
jarInputClass.add(entry.name to outputBytes)
}
entry = zipInputStream.nextEntry
}
}
Files.createParentDirs(outputJar)
ZipOutputStream(FileOutputStream(outputJar)).use { zos ->
jarInputClass.forEach {
val entryName = it.first
val outputBytes = it.second
zos.putNextEntry(ZipEntry(entryName))
zos.write(outputBytes)
}
}
}
private fun File.filterTransformFile(filter: (file: File) -> Unit) {
if (isDirectory) {
FileUtils.getAllFiles(this)
.toHashSet()
.forEach { it.filterTransformFile(filter) }
} else {
filter(this)
}
}
private fun File.transform(invocation: TransformInvocation, output: File) {
Files.createParentDirs(output)
if (extension == SdkConstants.EXT_CLASS) {
onTransform(invocation, readBytes()).write(output)
} else {
copyTo(output, true)
}
}
private fun ByteArray.write(output: File) =
FileOutputStream(output).use { it.write(this) }
override fun onTransformAfter(invocation: TransformInvocation) {
log("+------ Execution time: ${(System.nanoTime() - mStartInvocationTime) / 1000 / 1000}ms ------")
}
private fun log(message: String) {
if (isDebug.get()) {
project.logger.quiet(message)
}
}
} | 5 | Java | 2 | 8 | 2dd11be9fc4acdd62200a6ef6eb3bf210d0999c9 | 6,406 | OKMock | Apache License 2.0 |
src/main/kotlin/org/uevola/jsonautovalidation/core/JsonValidationComponentScan.kt | ugoevola | 646,607,242 | false | {"Kotlin": 81751} | package org.uevola.jsonautovalidation.core
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
@Configuration
@ComponentScan(
basePackages = ["org.uevola.jsonautovalidation"]
)
open class JsonValidationComponentScan | 0 | Kotlin | 0 | 0 | f3cca3660b402e4408ae452b66a008c5835bc753 | 289 | json-auto-validation | MIT License |
BlueSTSDK/BlueSTSDK/src/main/java/com/st/BlueSTSDK/Features/highSpeedDataLog/communication/DeviceModel/Response.kt | STMicroelectronics | 215,806,141 | false | {"Java": 1879263, "Kotlin": 1551485, "HTML": 13728} | package com.st.BlueSTSDK.Features.highSpeedDataLog.communication.DeviceModel
import com.google.gson.annotations.SerializedName
data class Response(
@SerializedName("JSONVersion")
val version:String,
@SerializedName("device")
val device: Device?
) | 0 | Java | 3 | 4 | 7d15d68a7b0e94baa69a2632ae3de37fb32178a8 | 280 | STAssetTracking_Android | The Unlicense |
src/main/kotlin/com/empcontrol/backend/services/EmployeeService.kt | rgomqui | 838,395,439 | false | {"Kotlin": 24635, "Dockerfile": 254, "Java": 86} | package com.empcontrol.backend.services
import com.empcontrol.backend.domain.Employee
import com.empcontrol.backend.model.EmployeeRequest
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import java.util.Optional
interface EmployeeService {
abstract fun findAll(pageable: Pageable): Page<Employee>
abstract fun findOneById(employeeId: Long): Optional<Employee>
abstract fun findOneByUsername(username: String): Optional<Employee>
abstract fun registerOne(newEmployee: EmployeeRequest): Employee
abstract fun updateOneById(employeeId: Long, updatedEmployee: EmployeeRequest): Employee
abstract fun disableEmployeeById(employeeId: Long): Employee
} | 0 | Kotlin | 0 | 0 | cca4f4937849cd986be363c46882c04aa609de82 | 715 | emp_control_backend | The Unlicense |
Kosalaam/app/src/main/java/com/kosalaamInc/kosalaam/feature/login/LoginActivity.kt | ko-salaam | 385,827,098 | false | null | package com.kosalaamInc.kosalaam.feature.login
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.facebook.*
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.Task
import com.google.firebase.auth.*
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.kosalaamInc.kosalaam.R
import com.kosalaamInc.kosalaam.databinding.ActivityLoginBinding
import com.kosalaamInc.kosalaam.feature.loginIn.LoginInActivity
import com.kosalaamInc.kosalaam.feature.main.MainActivity
import com.kosalaamInc.kosalaam.feature.signUp.SignUpActivity
import com.kosalaamInc.kosalaam.global.Application
import java.util.*
class LoginActivity : AppCompatActivity() {
companion object {
val TAG = "loginActivity"
}
private var binding: ActivityLoginBinding? = null
private val RC_SIGN_IN = 9001
private lateinit var auth: FirebaseAuth
private lateinit var googleSignInClient: GoogleSignInClient
private lateinit var callbackManager: CallbackManager
private val viewModel: LoginViewModel by lazy {
ViewModelProvider(this).get(LoginViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
LoginManager.getInstance().logOut()
auth = Firebase.auth
binding = DataBindingUtil.setContentView<ActivityLoginBinding>(
this, R.layout.activity_login
).apply {
lifecycleOwner = this@LoginActivity
loginVm = viewModel
}
initObserve()
}
override fun onStart() {
super.onStart()
val currentUser = auth.currentUser
}
private fun initObserve() {
with(viewModel) {
signIn_Bt.observe(this@LoginActivity, Observer {
it.getContentIfNotHandled()?.let {
signInBtInit()
}
})
signUp_Bt.observe(this@LoginActivity, Observer {
it.getContentIfNotHandled()?.let {
signUpBtInit()
}
})
facebook_Bt.observe(this@LoginActivity, Observer {
it.getContentIfNotHandled()?.let {
if (checkInternet() == true) {
facebookBtInit()
} else {
Toast.makeText(this@LoginActivity,
"Check your Internet",
Toast.LENGTH_SHORT).show()
}
}
})
google_Bt.observe(this@LoginActivity, Observer {
it.getContentIfNotHandled()?.let {
if (checkInternet() == true) {
googleBtInit()
} else {
Toast.makeText(this@LoginActivity,
"Check your Internet",
Toast.LENGTH_SHORT).show()
}
}
})
}
}
private fun signInBtInit() {
val intent = Intent(this, LoginInActivity::class.java)
startActivity(intent)
}
private fun facebookBtInit() {
callbackManager = CallbackManager.Factory.create()
facebookLogin()
}
private fun googleBtInit() {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.google_OAuth))
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(this, gso)
GooglesignIn()
}
private fun signUpBtInit() {
val intent = Intent(this, SignUpActivity::class.java)
startActivity(intent)
}
@Suppress("DEPRECATION")
private fun GooglesignIn() {
val signInIntent = googleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}
@Suppress("DEPRECATION")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Log.d(TAG, "onActivityResult")
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
// Google Sign In was successful, authenticate with Firebase
val account = task.getResult(ApiException::class.java)!!
Log.d(TAG, "firebaseAuthWithGoogle:" + account.id)
firebaseAuthWithGoogle(account.idToken!!)
} catch (e: ApiException) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e)
}
} else {
callbackManager.onActivityResult(requestCode, resultCode, data)
}
}
private fun facebookLogin() {
LoginManager.getInstance()
.logInWithReadPermissions(this, Arrays.asList("public_profile", "email"))
LoginManager.getInstance().registerCallback(callbackManager, object :
FacebookCallback<LoginResult> {
override fun onSuccess(loginResult: LoginResult) {
Log.d(TAG, "facebook:onSuccess:$loginResult")
handleFacebookAccessToken(loginResult.accessToken)
}
override fun onCancel() {
Log.d(TAG, "facebook:onCancel")
}
override fun onError(error: FacebookException) {
Log.d(TAG, "facebook:onError", error)
}
})
}
private fun handleFacebookAccessToken(token: AccessToken) {
Log.d(TAG, "handleFacebookAccessToken:$token")
val credential = FacebookAuthProvider.getCredential(token.token)
auth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
val isNew: Boolean = task.result.additionalUserInfo!!.isNewUser
var user = auth.currentUser
Application.prefs.setString("platform","facebook")
Application.prefs.setString("token",token.token)
Application.user = user
if (isNew == true) {
user!!.getIdToken(true)
.addOnCompleteListener(object : OnCompleteListener<GetTokenResult?> {
override fun onComplete(task: Task<GetTokenResult?>) {
if (task.isSuccessful()) {
val idToken: String? = task.getResult()?.getToken()
Log.d(TAG, idToken!!)
try {
viewModel.signUp(idToken!!)
initSignUpObserve(user)
}
catch (t: Throwable) {
Application.prefs.setString("platform","")
Application.prefs.setString("token","")
deleteUser(user!!)
//Toast message
}
} else {
//Toast message
Application.prefs.setString("platform","")
Application.prefs.setString("token","")
deleteUser(user!!)
}
}
})
} else {
updateUI(user)
}
Log.d(TAG, "signInWithCredential:success")
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.exception)
Toast.makeText(
baseContext, "Authentication failed.",
Toast.LENGTH_SHORT
).show()
auth.signOut()
updateUI(null)
}
}
}
fun firebaseAuthWithGoogle(idToken: String) {
val credential = GoogleAuthProvider.getCredential(idToken, null)
auth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
val user = auth.currentUser
var token: String? = null
val isNew: Boolean = task.result.additionalUserInfo!!.isNewUser
Application.prefs.setString("platform","google")
Application.prefs.setString("token",idToken)
Application.user = user
if (isNew == true) {
var token: String? = null
user!!.getIdToken(true)
.addOnCompleteListener(object : OnCompleteListener<GetTokenResult?> {
override fun onComplete(task: Task<GetTokenResult?>) {
if (task.isSuccessful()) {
val idToken1: String? = task.getResult()?.getToken()
Log.d(TAG, idToken1!!)
token = idToken1
try {
viewModel.signUp(idToken1!!)
initSignUpObserve(user)
} catch (t: Throwable) {
deleteUser(user!!)
Application.prefs.setString("platform","")
Application.prefs.setString("token","")
//Toast message
}
} else {
//toast message
Application.prefs.setString("platform","")
Application.prefs.setString("token","")
deleteUser(user!!)
}
}
})
} else {
updateUI(user)
}
} else {
// Toast message
Log.w(TAG, "signInWithCredential:failure", task.exception)
updateUI(null)
}
}
}
private fun updateUI(user: FirebaseUser?) {
if (user != null) {
startActivity(Intent(this, MainActivity::class.java))
this.finish()
} else {
Toast.makeText(this,"login failed, Try later",Toast.LENGTH_SHORT).show()
}
}
@Suppress("DEPRECATION")
private fun checkInternet(): Boolean {
val cm = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetwork: NetworkInfo? = cm.activeNetworkInfo
val isConnected: Boolean = activeNetwork?.isConnectedOrConnecting == true
return isConnected
}
private fun initSignUpObserve(user: FirebaseUser?) {
viewModel.signUpBoolean.observe(this, Observer<Boolean> {
Log.d("CheckBoolean", it.toString())
if (it == true) {
Application.user = user
updateUI(user)
} else {
Toast.makeText(this,"login failed, Try later",Toast.LENGTH_SHORT).show()
deleteUser(user!!)
Application.prefs.setString("platform","")
Application.prefs.setString("token","")
}
})
}
private fun deleteUser(user: FirebaseUser?) {
user!!.delete()
.addOnCompleteListener { task ->
if (task.isSuccessful) {
Log.d(TAG, "User account deleted.")
}
else{
}
}
}
} | 8 | Kotlin | 0 | 1 | 5e349d73ba8a060e344f3708c396fe6ec41b569c | 13,250 | ko-salaam-android | MIT License |
app/src/main/kotlin/com/tezov/lib/adapterJavaToKotlin/async/defProviderAsync_K.kt | tezov | 640,329,100 | false | null | package com.tezov.lib.adapterJavaToKotlin.async
import kotlinx.coroutines.Deferred
interface defProviderAsync_K<T:Any> {
fun getFirstIndex(): Deferred<Int?>
fun getLastIndex(): Deferred<Int?>
fun size(): Deferred<Int>
fun get(index:Int): Deferred<T?>
fun select(offset: Int,length: Int): Deferred<List<T>?>
fun indexOf(t: T): Deferred<Int?>
fun toDebugLog(pageStart:Int? = null, pageEnd:Int? = null): Deferred<Unit>
} | 0 | Kotlin | 0 | 0 | 02d5d2125f6211e94410cda57af23469a4fa3a33 | 448 | gofo | MIT License |
app/src/main/java/xyz/harmonyapp/olympusblog/models/AuthToken.kt | sentrionic | 351,882,310 | false | null | package xyz.harmonyapp.olympusblog.models
import android.os.Parcelable
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.ForeignKey.CASCADE
import androidx.room.PrimaryKey
import com.squareup.moshi.Json
import kotlinx.android.parcel.Parcelize
const val AUTH_TOKEN_BUNDLE_KEY = "xyz.harmonyapp.olympusblog.models.AuthToken"
@Parcelize
@Entity(
tableName = "auth_token",
foreignKeys = [
ForeignKey(
entity = AccountProperties::class,
parentColumns = ["id"],
childColumns = ["account_id"],
onDelete = CASCADE
)
]
)
data class AuthToken(
@PrimaryKey
@ColumnInfo(name = "account_id")
var account_id: Int? = -1,
@ColumnInfo(name = "token")
@Json(name = "token")
var token: String? = null
) : Parcelable | 0 | Kotlin | 0 | 0 | 3b784bf9dd60f6cc6889813f2e2932fa3a9b211d | 864 | OlympusAndroid | MIT License |
feature/settings/domain/implementation/src/main/kotlin/com/savvasdalkitsis/uhuruphotos/feature/settings/domain/implementation/usecase/SettingsUseCase.kt | savvasdalkitsis | 485,908,521 | false | {"Kotlin": 2649695, "Ruby": 1294, "PowerShell": 325, "Shell": 158} | /*
Copyright 2022 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.savvasdalkitsis.uhuruphotos.feature.settings.domain.implementation.usecase
import androidx.work.NetworkType
import com.savvasdalkitsis.uhuruphotos.feature.settings.domain.api.usecase.SettingsUseCase
import com.savvasdalkitsis.uhuruphotos.feature.settings.domain.api.usecase.minCacheSize
import com.savvasdalkitsis.uhuruphotos.foundation.log.api.Log
import com.savvasdalkitsis.uhuruphotos.foundation.preferences.api.PlainTextPreferences
import com.savvasdalkitsis.uhuruphotos.foundation.preferences.api.Preferences
import com.savvasdalkitsis.uhuruphotos.foundation.preferences.api.get
import com.savvasdalkitsis.uhuruphotos.foundation.preferences.api.observe
import com.savvasdalkitsis.uhuruphotos.foundation.preferences.api.set
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import se.ansman.dagger.auto.AutoBind
import javax.inject.Inject
@AutoBind
internal class SettingsUseCase @Inject constructor(
@PlainTextPreferences
private val preferences: Preferences,
) : SettingsUseCase {
private val lightboxPhotoDiskCacheSize = "imageDiskCacheSize" // cannot change value for backwards compatibility
private val lightboxPhotoDiskCacheSizeDefault = 500
private val lightboxPhotoMemCacheSize = "imageDiskCacheSize" // cannot change value for backwards compatibility
private val lightboxPhotoMemCacheSizeDefault = 200
private val thumbnailDiskCacheSize = "thumbnailDiskCacheSize"
private val thumbnailDiskCacheSizeDefault = 500
private val thumbnailMemCacheSize = "thumbnailDiskCacheSize"
private val thumbnailMemCacheSizeDefault = 200
private val videoDiskCacheSize = "videoDiskCacheSize"
private val videoDiskCacheSizeDefault = 700
private val feedSyncFrequency = "feedSyncFrequency"
private val feedSyncFrequencyDefault = 12
private val feedDaysToRefresh = "feedDaysToRefresh"
private val feedDaysToRefreshDefault = 3
private val shouldPerformPeriodicFeedSync = "shouldPerformPeriodicFeedSync"
private val shouldPerformPeriodicFeedSyncDefault = true
private val fullSyncNetworkRequirements = "fullSyncNetworkRequirements"
private val fullSyncNetworkRequirementsDefault = NetworkType.NOT_ROAMING
private val fullSyncRequiresCharging = "fullSyncRequiresCharging"
private val fullSyncRequiresChargingDefault = false
private val cloudSyncNetworkRequirements = "cloudSyncNetworkRequirements"
private val cloudSyncNetworkRequirementsDefault = NetworkType.NOT_ROAMING
private val cloudSyncRequiresCharging = "cloudSyncRequiresCharging"
private val cloudSyncRequiresChargingDefault = false
private val shareRemoveGpsData = "shareRemoveGpsData"
private val shareRemoveGpsDataDefault = false
private val loggingEnabled = "loggingEnabled"
private val loggingEnabledDefault = false
private val sendDatabaseEnabled = "sendDatabaseEnabled"
private val sendDatabaseEnabledDefault = false
private val biometricsRequiredForAppAccess = "biometricsRequiredForAppAccess"
private val biometricsRequiredForAppAccessDefault = false
private val biometricsRequiredForHiddenPhotosAccess = "biometricsRequiredForHiddenPhotosAccess"
private val biometricsRequiredForHiddenPhotosAccessDefault = false
private val biometricsRequiredForTrashAccess = "biometricsRequiredForTrashAccess"
private val biometricsRequiredForTrashAccessDefault = false
override fun getLightboxPhotoDiskCacheMaxLimit(): Int =
getCache(lightboxPhotoDiskCacheSize, lightboxPhotoDiskCacheSizeDefault)
override fun getLightboxPhotoMemCacheMaxLimit(): Int =
getCache(lightboxPhotoMemCacheSize, lightboxPhotoMemCacheSizeDefault)
override fun getThumbnailDiskCacheMaxLimit(): Int =
getCache(thumbnailDiskCacheSize, thumbnailDiskCacheSizeDefault)
override fun getThumbnailMemCacheMaxLimit(): Int =
getCache(thumbnailMemCacheSize, thumbnailMemCacheSizeDefault)
override fun getVideoDiskCacheMaxLimit(): Int =
getCache(videoDiskCacheSize, videoDiskCacheSizeDefault)
override fun getFeedSyncFrequency(): Int =
get(feedSyncFrequency, feedSyncFrequencyDefault)
override fun getFeedDaysToRefresh(): Int =
get(feedDaysToRefresh, feedDaysToRefreshDefault)
override fun getFullSyncNetworkRequirements(): NetworkType =
get(fullSyncNetworkRequirements, fullSyncNetworkRequirementsDefault)
override fun getFullSyncRequiresCharging(): Boolean =
get(fullSyncRequiresCharging, fullSyncRequiresChargingDefault)
override fun getCloudSyncNetworkRequirements(): NetworkType =
get(cloudSyncNetworkRequirements, cloudSyncNetworkRequirementsDefault)
override fun getCloudSyncRequiresCharging(): Boolean =
get(cloudSyncRequiresCharging, cloudSyncRequiresChargingDefault)
override fun getShouldPerformPeriodicFullSync(): Boolean =
get(shouldPerformPeriodicFeedSync, shouldPerformPeriodicFeedSyncDefault)
override fun getShareRemoveGpsData(): Boolean =
get(shareRemoveGpsData, shareRemoveGpsDataDefault)
override fun getLoggingEnabled(): Boolean =
get(loggingEnabled, loggingEnabledDefault)
override fun getSendDatabaseEnabled(): Boolean =
get(sendDatabaseEnabled, sendDatabaseEnabledDefault)
override fun getBiometricsRequiredForAppAccess(): Boolean =
get(biometricsRequiredForAppAccess, biometricsRequiredForAppAccessDefault)
override fun getBiometricsRequiredForHiddenPhotosAccess(): Boolean =
get(biometricsRequiredForHiddenPhotosAccess, biometricsRequiredForHiddenPhotosAccessDefault)
override fun getBiometricsRequiredForTrashAccess(): Boolean =
get(biometricsRequiredForTrashAccess, biometricsRequiredForTrashAccessDefault)
override fun observeLightboxPhotoDiskCacheMaxLimit(): Flow<Int> =
observeCache(lightboxPhotoDiskCacheSize, lightboxPhotoDiskCacheSizeDefault)
override fun observeLightboxPhotoMemCacheMaxLimit(): Flow<Int> =
observeCache(lightboxPhotoMemCacheSize, lightboxPhotoMemCacheSizeDefault)
override fun observeThumbnailDiskCacheMaxLimit(): Flow<Int> =
observeCache(thumbnailDiskCacheSize, thumbnailMemCacheSizeDefault)
override fun observeThumbnailMemCacheMaxLimit(): Flow<Int> =
observeCache(thumbnailMemCacheSize, thumbnailMemCacheSizeDefault)
override fun observeVideoDiskCacheMaxLimit(): Flow<Int> =
observeCache(videoDiskCacheSize, videoDiskCacheSizeDefault)
override fun observeFeedSyncFrequency(): Flow<Int> =
observe(feedSyncFrequency, feedSyncFrequencyDefault)
override fun observeFeedDaysToRefresh(): Flow<Int> =
observe(feedDaysToRefresh, feedDaysToRefreshDefault)
override fun observeFullSyncNetworkRequirements(): Flow<NetworkType> =
observe(fullSyncNetworkRequirements, fullSyncNetworkRequirementsDefault)
override fun observeFullSyncRequiresCharging(): Flow<Boolean> =
observe(fullSyncRequiresCharging, fullSyncRequiresChargingDefault)
override fun observeCloudSyncNetworkRequirements(): Flow<NetworkType> =
observe(cloudSyncNetworkRequirements, cloudSyncNetworkRequirementsDefault)
override fun observeCloudSyncRequiresCharging(): Flow<Boolean> =
observe(cloudSyncRequiresCharging, cloudSyncRequiresChargingDefault)
override fun observeShareRemoveGpsData(): Flow<Boolean> =
observe(shareRemoveGpsData, shareRemoveGpsDataDefault)
override fun observeLoggingEnabled(): Flow<Boolean> =
observe(loggingEnabled, loggingEnabledDefault)
override fun observeSendDatabaseEnabled(): Flow<Boolean> =
observe(sendDatabaseEnabled, sendDatabaseEnabledDefault)
override fun observeBiometricsRequiredForAppAccess(): Flow<Boolean> =
observe(biometricsRequiredForAppAccess, biometricsRequiredForAppAccessDefault)
override fun observeBiometricsRequiredForHiddenPhotosAccess(): Flow<Boolean> =
observe(biometricsRequiredForHiddenPhotosAccess, biometricsRequiredForHiddenPhotosAccessDefault)
override fun observeBiometricsRequiredForTrashAccess(): Flow<Boolean> =
observe(biometricsRequiredForTrashAccess, biometricsRequiredForTrashAccessDefault)
override fun setLightboxPhotoDiskCacheMaxLimit(sizeInMb: Int) {
set(lightboxPhotoDiskCacheSize, sizeInMb)
}
override fun setLightboxPhotoMemCacheMaxLimit(sizeInMb: Int) {
set(lightboxPhotoMemCacheSize, sizeInMb)
}
override fun setThumbnailDiskCacheMaxLimit(sizeInMb: Int) {
set(thumbnailDiskCacheSize, sizeInMb)
}
override fun setThumbnailMemCacheMaxLimit(sizeInMb: Int) {
set(thumbnailMemCacheSize, sizeInMb)
}
override fun setVideoDiskCacheMaxLimit(sizeInMb: Int) {
set(videoDiskCacheSize, sizeInMb)
}
override fun setFeedSyncFrequency(frequency: Int) {
set(feedSyncFrequency, frequency)
}
override fun setFeedFeedDaysToRefresh(days: Int) {
set(feedDaysToRefresh, days)
}
override fun setFullSyncNetworkRequirements(networkType: NetworkType) {
set(fullSyncNetworkRequirements, networkType)
}
override fun setFullSyncRequiresCharging(requiresCharging: Boolean) {
set(fullSyncRequiresCharging, requiresCharging)
}
override fun setCloudSyncNetworkRequirements(networkType: NetworkType) {
set(cloudSyncNetworkRequirements, networkType)
}
override fun setCloudSyncRequiresCharging(requiresCharging: Boolean) {
set(cloudSyncRequiresCharging, requiresCharging)
}
override fun setShouldPerformPeriodicFullSync(perform: Boolean) {
set(shouldPerformPeriodicFeedSync, perform)
}
override fun setShareRemoveGpsData(enabled: Boolean) {
set(shareRemoveGpsData, enabled)
}
override fun setLoggingEnabled(enabled: Boolean) {
set(loggingEnabled, enabled)
Log.enabled = enabled
}
override fun setSendDatabaseEnabled(enabled: Boolean) {
set(sendDatabaseEnabled, enabled)
}
override fun setBiometricsRequiredForAppAccess(required: Boolean) {
set(biometricsRequiredForAppAccess, required)
}
override fun setBiometricsRequiredForHiddenPhotosAccess(required: Boolean) {
set(biometricsRequiredForHiddenPhotosAccess, required)
}
override fun setBiometricsRequiredForTrashAccess(required: Boolean) {
set(biometricsRequiredForTrashAccess, required)
}
private fun getCache(key: String, defaultValue: Int) = get(key, defaultValue).coerceAtLeast(
minCacheSize
)
private inline fun <reified T: Enum<T>> get(key: String, defaultValue: T): T =
preferences.get(key, defaultValue)
private inline fun <reified T> get(key: String, defaultValue: T): T =
preferences.get(key, defaultValue)
private inline fun <reified T: Enum<T>> observe(key: String, defaultValue: T): Flow<T> =
preferences.observe(key, defaultValue)
private fun observeCache(key: String, defaultValue: Int): Flow<Int> =
observe(key, defaultValue).map { it.coerceAtLeast(minCacheSize) }
private inline fun <reified T> observe(key: String, defaultValue: T): Flow<T> =
preferences.observe(key, defaultValue)
private inline fun <reified T: Enum<T>> set(key: String, value: T) {
preferences.set(key, value)
}
private inline fun <reified T> set(key: String, value: T) {
preferences.set(key, value)
}
}
| 52 | Kotlin | 26 | 354 | d5b6eb76235e97c78dc9d80128407b41c39c0e18 | 11,990 | uhuruphotos-android | Apache License 2.0 |
idea/tests/testData/inspectionsLocal/redundantCompanionReference/sameNameSuperMemberFunction2.kt | JetBrains | 278,369,660 | false | null | // PROBLEM: none
open class A {
fun foo(x: Int) = "A$x"
}
open class B: A() {
}
class C : B() {
fun test(): String {
return <caret>Companion.foo(1)
}
companion object {
fun foo(x: Int) = "C$x"
}
}
| 0 | null | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 237 | intellij-kotlin | Apache License 2.0 |
conditional-kotlin/src/main/kotlin/com/linecorp/conditional/kotlin/ComposableCoroutineCondition.kt | line | 580,271,941 | false | {"Java": 152567, "Kotlin": 58407} | /*
* Copyright 2023 LINE Corporation
*
* LINE Corporation 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:
*
* 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.linecorp.conditional.kotlin
/**
* [ComposableCoroutineCondition] is a class to compose multiple [CoroutineCondition]s.
* If you don't use [ComposableCoroutineCondition], you can compose like the code below:
*
* ```
* class TestCoroutineCondition : CoroutineCondition() {
* lateinit var a: CoroutineCondition
* lateinit var b: CoroutineCondition
*
* override suspend fun match(ctx: CoroutineConditionContext): Boolean {
* // You have to invoke `matches` function manually.
* return (a and b).matches(ctx)
* }
* }
* ```
*
* Otherwise, if you use [ComposableCoroutineCondition]:
* ```
* class TestCoroutineCondition : ComposableCoroutineCondition() {
* lateinit var a: CoroutineCondition
* lateinit var b: CoroutineCondition
*
* override suspend fun compose(): CoroutineCondition {
* // You don't have to invoke `matches` function manually.
* return a and b
* }
* }
* ```
*/
abstract class ComposableCoroutineCondition(
alias: String? = DEFAULT_ALIAS,
delayMillis: Long = DEFAULT_DELAY_MILLIS,
timeoutMillis: Long = DEFAULT_TIMEOUT_MILLIS,
) : CoroutineCondition(alias, delayMillis, timeoutMillis) {
final override suspend fun match(ctx: CoroutineConditionContext): Boolean = compose().matches(ctx)
protected abstract suspend fun compose(): CoroutineCondition
}
| 1 | Java | 7 | 57 | 58f9929d5aba9b6785513f4d590ae51f310582b0 | 2,019 | conditional | Apache License 2.0 |
src/test/kotlin/ffc/airsync/api/services/util/UriReaderTest.kt | ffc-nectec | 137,835,555 | false | {"Gradle": 2, "Procfile": 1, "Dockerfile": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "JSON": 12, "YAML": 2, "Markdown": 3, "Java Properties": 1, "Kotlin": 167, "Java": 1, "XML": 1} | package ffc.airsync.api.services.util
import org.amshove.kluent.`should contain`
import org.junit.Ignore
import org.junit.Test
import java.net.URI
class UriReaderTest {
@Test
fun readUrl() {
val reader = UriReader(URI("https://raw.githubusercontent.com/ffc-nectec/entities/master/README.md"))
val text = reader.readAsString()
text `should contain` "FFC"
}
@Ignore
@Test
fun readFileUri() {
val reader = UriReader(URI("file:///C:/Windows/WindowsUpdate.log"))
val text = reader.readAsString()
println(text)
}
}
| 5 | Kotlin | 0 | 1 | 03c71b6edf2ebe8c246728a5f09700c8093a8edb | 589 | api | Apache License 2.0 |
demo/app/src/main/kotlin/uk/ac/imperial/vimc/demo/app/Serializer.kt | vimc | 85,062,678 | false | null | package uk.ac.imperial.vimc.demo.app
import com.github.salomonbrys.kotson.jsonSerializer
import com.github.salomonbrys.kotson.registerTypeAdapter
import com.google.gson.*
import uk.ac.imperial.vimc.demo.app.models.Outcome
import uk.ac.imperial.vimc.demo.app.models.Result
import uk.ac.imperial.vimc.demo.app.models.ResultStatus
object Serializer
{
private val toStringSerializer = jsonSerializer<Any> { JsonPrimitive(it.src.toString()) }
private val rangeSerializer = jsonSerializer<IntRange> {
JsonObject().apply {
addProperty("start", it.src.first)
addProperty("end", it.src.last)
}
}
private val outcomeSerializer = jsonSerializer<Outcome> {
JsonObject().apply {
addProperty("year", it.src.year)
addProperty(Outcome.Keys.deaths, it.src.deaths)
addProperty(Outcome.Keys.cases, it.src.cases)
addProperty(Outcome.Keys.dalys, it.src.dalys)
addProperty(Outcome.Keys.fvps, it.src.fvps)
addProperty(Outcome.Keys.deathsAverted, it.src.deathsAverted)
}
}
private val enumSerializer = jsonSerializer<Any> {
JsonPrimitive(it.src.toString().toLowerCase())
}
val gson: Gson = GsonBuilder()
.setPrettyPrinting()
.disableHtmlEscaping()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.registerTypeAdapter<java.time.LocalDate>(toStringSerializer)
.registerTypeAdapter<java.time.Instant>(toStringSerializer)
.registerTypeAdapter(rangeSerializer)
.registerTypeAdapter(outcomeSerializer)
.registerTypeAdapter<ResultStatus>(enumSerializer)
.create()
fun toResult(data: Any?): String = toJson(Result(ResultStatus.SUCCESS, data, emptyList()))
fun toJson(result: Result): String = Serializer.gson.toJson(result)
} | 1 | Kotlin | 1 | 2 | 0b3acb5f22b71300d6c260c5ecb252b0bddbe6ea | 1,902 | montagu-api | MIT License |
weatherapp/app/src/main/kotlin/fr/ekito/myweatherapp/view/Events.kt | Ekito | 129,068,321 | false | null | package fr.ekito.myweatherapp.view
/**
* Abstract Event from ViewModel
*/
open class Event
/**
* Generic Loading Event
*/
object LoadingEvent : Event()
/**
* Generic Success Event
*/
object SuccessEvent : Event()
/**
* Generic Failed Event
*/
data class FailedEvent(val error: Throwable) : Event() | 0 | null | 6 | 60 | be37b060c9abe61717f26367e6957bd6e601dd64 | 309 | mvvm-coroutines | Creative Commons Attribution 4.0 International |
adb-server/adb-server-desktop-device-connection/src/main/java/com/kaspersky/adbserver/desdevconnection/DesktopDeviceSocketConnectionForwardImpl.kt | KasperskyLab | 208,070,025 | false | {"Kotlin": 736940, "Shell": 1880, "Makefile": 387} | package com.kaspersky.adbserver.desdevconnection
import com.kaspersky.adbserver.common.api.CommandExecutor
import com.kaspersky.adbserver.commandtypes.AdbCommand
import com.kaspersky.adbserver.common.log.logger.Logger
import java.net.ServerSocket
import java.net.Socket
import kotlin.random.Random
internal class DesktopDeviceSocketConnectionForwardImpl : DesktopDeviceSocketConnection {
companion object {
private const val DEVICE_PORT: Int = 8500
private const val MIN_CLIENT_PORT: Int = 6000
private const val MAX_CLIENT_PORT: Int = 49000
private const val LOCAL_HOST: String = "127.0.0.1"
}
private val clientPortsList: MutableList<Int> = mutableListOf()
override fun getDesktopSocketLoad(executor: CommandExecutor, logger: Logger): () -> Socket {
val clientPort = getFreePort()
logger.d("calculated desktop client port=$clientPort")
forwardPorts(
executor,
clientPort,
DEVICE_PORT,
logger
)
logger.d("desktop client port=$clientPort is forwarding with device server port=$DEVICE_PORT")
return {
logger.d("started with ip=$LOCAL_HOST, port=$clientPort")
val readyClientSocket = Socket(LOCAL_HOST, clientPort)
logger.d("completed with ip=$LOCAL_HOST, port=$clientPort")
readyClientSocket
}
}
private fun getFreePort(): Int {
var newClientPort: Int
while (true) {
newClientPort = Random.Default.nextInt(
MIN_CLIENT_PORT,
MAX_CLIENT_PORT
)
if (!clientPortsList.contains(newClientPort)) {
break
}
clientPortsList.add(newClientPort)
}
return newClientPort
}
private fun forwardPorts(executor: CommandExecutor, fromPort: Int, toPort: Int, logger: Logger) {
logger.d("fromPort=$fromPort, toPort=$toPort started")
val result = executor.execute(AdbCommand("forward tcp:$fromPort tcp:$toPort"))
logger.d("fromPort=$fromPort, toPort=$toPort) finished with result=$result")
}
override fun getDeviceSocketLoad(logger: Logger): () -> Socket = {
logger.d("Started")
val serverSocket = ServerSocket(DEVICE_PORT)
val readyServerSocket = serverSocket.accept()
logger.d("Completed")
readyServerSocket
}
}
| 55 | Kotlin | 150 | 1,784 | 9c94128c744d640dcd646b86de711d2a1b9c3aa1 | 2,430 | Kaspresso | Apache License 2.0 |
app/src/test/java/fm/weigl/refsberlin/gameslist/view/GamesListViewTest.kt | asco33 | 92,974,118 | false | null | package fm.weigl.refsberlin.gameslist.view
import android.app.Activity
import android.content.res.Resources
import android.text.Editable
import android.widget.EditText
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.given
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.then
import fm.weigl.refsberlin.R
import fm.weigl.refsberlin.TestGames
import fm.weigl.refsberlin.android.Toaster
import fm.weigl.refsberlin.base.LoadingState
import junit.framework.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito.verify
class GamesListViewTest {
val activity: Activity = mock()
val toaster: Toaster = mock()
val resources: Resources = mock()
val adapter: GamesListAdapter = mock()
val delegate: GamesListEventDelegate = mock()
val editText: EditText = mock()
val classToTest = GamesListView(adapter, activity, toaster, resources)
@Before
fun setUp() {
classToTest.delegate = delegate
classToTest.setViews(mock(), editText)
}
@Test
fun setsLoadingStatesCorrectly() {
classToTest.setLoadingState(LoadingState.DONE)
assertEquals(LoadingState.DONE, classToTest.loadingState.get())
classToTest.setLoadingState(LoadingState.LOADING)
assertEquals(LoadingState.LOADING, classToTest.loadingState.get())
classToTest.setLoadingState(LoadingState.REFRESHING)
assertEquals(LoadingState.REFRESHING, classToTest.loadingState.get())
}
@Test
fun delegatesPullToRefresh() {
classToTest.onRefresh()
then(delegate).should().refreshPulled()
}
@Test
fun delegatesFilterTextChanged() {
classToTest.onTextChanged()
verify(delegate).filterTextChanged()
}
@Test
fun returnsTrimmedFilterText() {
val text = " text "
val editable = mock<Editable>()
given(editable.toString()).willReturn(text)
given(editText.text).willReturn(editable)
assertEquals("text", classToTest.getFilterText())
}
@Test
fun setsGamesToAdapter() {
val games = listOf(TestGames.testGame)
given(resources.getString(any(), any())).willReturn("")
classToTest.displayGames(games)
verify(adapter).games = games
}
@Test
fun setsHighlightTextToAdapter() {
val text = "text"
classToTest.highlightGamesWithText(text)
verify(adapter).highlightText = text
}
@Test
fun displaysNumberOfGames() {
val text = "text"
val games = listOf(TestGames.testGame, TestGames.testGame)
given(resources.getString(R.string.number_of_games, 2)).willReturn(text)
classToTest.displayGames(games)
then(toaster).should().showToast(text)
}
@Test
fun clearsEditTextWhenClearButtonClicked() {
classToTest.clearButtonClicked()
then(editText).should().setText("")
}
} | 2 | null | 1 | 1 | 7b0c7b8641206624c3d2df235eb47341130e98f1 | 2,985 | refsberlin | Apache License 2.0 |
app/src/main/java/com/example/huabei_competition/widget/ParticleStream.kt | fcy354268003 | 286,145,839 | false | {"Java": 433034, "Kotlin": 5676} | package com.example.huabei_competition.widget
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.animation.LinearInterpolator
import java.util.*
import kotlin.math.acos
import kotlin.math.cos
import kotlin.math.sin
import kotlin.system.measureTimeMillis
class ParticleStream(context: Context?, attrs: AttributeSet?) : View(context, attrs) {
private var particleList = mutableListOf<Particle>()
var paint = Paint()
var centerX: Float = 0f
var centerY: Float = 0f
private var animator = ValueAnimator.ofFloat(0f, 1f)
var maxOffset = 300f
var path = Path()
private val pathMeasure = PathMeasure()// 用于测量扩散圆上某处的x,y
private var pos = FloatArray(2)// 扩散圆上某点x,y
private var tan = FloatArray(2)//扩散圆上某一点的切线
var radius: Float = 200f
val sum = 5000f
var type: Int = 0
var speedBound = IntArray(2)
var paintColor: Int = Color.WHITE
init {
speedBound[0] = 10
speedBound[1] = 2
animator.duration = 5000
animator.repeatCount = -1
animator.interpolator = LinearInterpolator()
animator.addUpdateListener {
if (type == 1)
updateParticle()
else
updateParticle(it.animatedValue as Float)
invalidate()
}
}
/**
* 瀑布式
*/
private fun updateParticle(value: Float) {
val random = Random()
particleList.forEach {
it.y += it.speed
if (it.y - centerY >= it.maxOffset) {
it.y = centerY
it.x = random.nextInt((centerX).toInt()).toFloat()
it.speed = (random.nextInt(speedBound[0]) + speedBound[1])
}
it.alpha = ((1f - (it.y - centerY) / it.maxOffset) * 225f).toInt()
}
}
/**
* 圆形发散式
*/
private fun updateParticle() {
val random = Random()
particleList.forEach {
if (it.offset > it.maxOffset) {
it.offset = 0
it.speed = (random.nextInt(speedBound[0]) + speedBound[1])
}
it.alpha = ((1f - it.offset / it.maxOffset) * 225f).toInt()
it.x = (centerX + cos(it.angle) * (radius + it.offset)).toFloat()
if (it.y > centerY) {
it.y = (centerY + sin(it.angle) * (radius + it.offset)).toFloat()
} else {
it.y = (centerY - sin(it.angle) * (radius + it.offset)).toFloat()
}
it.offset += it.speed
}
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
Log.d(TAG, "onSizeChanged: ")
paint.color = paintColor
val random = Random()
var nextX = 0f
var nextY = 0f
var speed = 0
if (type == 1) {
centerX = (w / 2).toFloat()
centerY = (h / 2).toFloat()
// 初始化圆形C
path.addCircle(centerX, centerY, radius, Path.Direction.CW)
pathMeasure.setPath(path, false)
var angle: Double
var offset = 0
//初始化粒子
for (i in 0..sum.toInt()) {
pathMeasure.getPosTan(i / sum * pathMeasure.length, pos, tan)
nextX = pos[0] + random.nextInt(6) - 3f
nextY = pos[1] + random.nextInt((6)) - 3f
speed = random.nextInt(speedBound[0]) + speedBound[1]
angle = acos(((pos[0] - centerX) / radius).toDouble())
offset = random.nextInt((radius / 10).toInt())
val particle =
Particle(
x = nextX,
y = nextY,
radius = 2f,
speed = speed,
alpha = 225,
maxOffset = maxOffset,
angle = angle,
offset = offset
)
particleList.add(particle)
}
} else {
centerX = w.toFloat()
centerY = 0f
for (i in 0..sum.toInt()) {
nextX = random.nextInt(centerX.toInt()).toFloat()
nextY = random.nextInt(maxOffset.toInt()).toFloat()
speed = random.nextInt(speedBound[0]) + speedBound[1]
particleList.add(Particle(nextX, nextY, 2f, speed, 225, maxOffset))
}
}
// animator.start()
}
fun start() {
animator.repeatCount = -1
animator.start()
}
fun stop() {
animator.repeatCount = 1
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val time = measureTimeMillis {
paint.isAntiAlias = true
particleList.forEach {
paint.alpha = it.alpha
canvas.drawCircle(it.x, it.y, it.radius, paint)
}
}
Log.d(TAG, "onDraw: $time")
}
}
class Particle(
var x: Float,
var y: Float,
var radius: Float,//粒子半径
var speed: Int,
var alpha: Int,
var maxOffset: Float,
var offset: Int = 0,//当前移动距离
var angle: Double = 0.0// 粒子角度
)
private const val TAG = "MainActivity" | 1 | null | 1 | 1 | 7ee243d5a3ec3374b89438a3e13dc904b3c1a674 | 5,458 | huabei_competition | Apache License 2.0 |
android/ExampleApp/app/src/main/java/com/fjuul/sdk/android/exampleapp/ui/login/OnboardingFormState.kt | fjuul | 220,994,804 | false | {"Java": 874084, "Swift": 350740, "Kotlin": 77067} | package com.fjuul.sdk.android.exampleapp.ui.login
import com.fjuul.sdk.android.exampleapp.data.SdkEnvironment
/**
* Data validation state of the login form.
*/
data class OnboardingFormState(
val tokenError: Int? = null,
val secretError: Int? = null,
val apiKeyError: Int? = null,
val environment: SdkEnvironment? = null,
val isDataValid: Boolean = false
)
| 1 | Java | 0 | 4 | bc58683ed1f36200e07ab71a163aa7e546163d36 | 382 | sdk | Apache License 2.0 |
platform/platform-impl/src/com/intellij/ide/util/TipAndTrickManager.kt | EsolMio | 169,598,741 | false | {"Text": 6869, "INI": 540, "YAML": 412, "Ant Build System": 10, "Batchfile": 34, "Shell": 621, "Markdown": 668, "Ignore List": 116, "Git Revision List": 1, "Git Attributes": 10, "EditorConfig": 244, "XML": 6841, "SVG": 3479, "Kotlin": 46380, "Java": 79395, "HTML": 3171, "Java Properties": 208, "Gradle": 431, "Maven POM": 78, "JFlex": 31, "JSON": 1255, "CSS": 69, "Groovy": 3323, "XSLT": 113, "JavaScript": 209, "desktop": 1, "Python": 14865, "JAR Manifest": 17, "PHP": 47, "Gradle Kotlin DSL": 452, "Protocol Buffer": 3, "Microsoft Visual Studio Solution": 4, "C#": 33, "Smalltalk": 17, "Diff": 133, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 1, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 27, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 65, "GraphQL": 54, "OpenStep Property List": 47, "Tcl": 1, "fish": 1, "Dockerfile": 3, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "Elixir": 2, "Ruby": 5, "XML Property List": 81, "Starlark": 2, "E-mail": 18, "Roff": 38, "Roff Manpage": 2, "Swift": 3, "C": 87, "TOML": 147, "Proguard": 2, "PlantUML": 6, "Checksums": 58, "Java Server Pages": 8, "reStructuredText": 59, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 16, "C++": 33, "Rust": 9, "Makefile": 2, "VBScript": 1, "NSIS": 5, "Thrift": 3, "Cython": 14, "Regular Expression": 3, "JSON5": 4} | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.util
import com.intellij.ide.GeneralSettings
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.ui.GotItTooltipService
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
@Service
class TipAndTrickManager {
private var openedDialog: TipDialog? = null
fun showTipDialog(project: Project) = showTipDialog(project, TipAndTrickBean.EP_NAME.extensionList)
/**
* Show the dialog with one tip without "Next tip" and "Previous tip" buttons
*/
fun showTipDialog(project: Project, tip: TipAndTrickBean) = showTipDialog(project, listOf(tip))
private fun showTipDialog(project: Project, tips: List<TipAndTrickBean>) {
closeTipDialog()
openedDialog = TipDialog(project, tips).also { dialog ->
Disposer.register(dialog.disposable, Disposable { openedDialog = null }) // clear link to not leak the project
dialog.show()
}
}
fun closeTipDialog() {
openedDialog?.close(DialogWrapper.OK_EXIT_CODE)
}
fun canShowDialogAutomaticallyNow(project: Project): Boolean {
return GeneralSettings.getInstance().isShowTipsOnStartup
&& !DISABLE_TIPS_FOR_PROJECT.get(project, false)
&& !GotItTooltipService.getInstance().isFirstRun
&& openedDialog?.isVisible != true
&& !TipsUsageManager.getInstance().wereTipsShownToday()
}
companion object {
val DISABLE_TIPS_FOR_PROJECT = Key.create<Boolean>("DISABLE_TIPS_FOR_PROJECT")
@JvmStatic
fun getInstance(): TipAndTrickManager = service()
}
} | 1 | null | 1 | 1 | 4eb05cb6127f4dd6cbc09814b76b80eced9e4262 | 1,910 | intellij-community | Apache License 2.0 |
idea/src/org/jetbrains/kotlin/idea/presentation/KtLightClassListCellRenderer.kt | JakeWharton | 99,388,807 | true | null | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.idea.presentation
import com.intellij.ide.util.PsiElementListCellRenderer
import com.intellij.psi.presentation.java.ClassPresentationUtil
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.name.FqName
class KtLightClassListCellRenderer : PsiElementListCellRenderer<KtLightClass>() {
override fun getElementText(element: KtLightClass) = ClassPresentationUtil.getNameForClass(element, false)
// TODO: correct text for local, anonymous, enum entries ... etc
override fun getContainerText(element: KtLightClass, name: String) = element.qualifiedName?.let { qName ->
"(" + FqName(qName).parent().asString() + ")"
} ?: ""
override fun getIconFlags() = 0
}
| 0 | Kotlin | 30 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 1,346 | kotlin | Apache License 2.0 |
EvoMaster/core/src/main/kotlin/org/evomaster/core/search/gene/regex/DisjunctionRxGene.kt | BrotherKim | 397,139,860 | false | {"Markdown": 32, "Shell": 14, "Maven POM": 66, "Text": 16, "Ignore List": 13, "Java": 1366, "SQL": 44, "YAML": 13, "JSON": 37, "JavaScript": 183, "XML": 14, "Mermaid": 1, "Java Properties": 36, "INI": 15, "HTML": 52, "Dockerfile": 2, "CSS": 8, "JSON with Comments": 3, "Less": 8, "SVG": 16, "Kotlin": 541, "OASv2-yaml": 1, "XSLT": 3, "Python": 3, "Graphviz (DOT)": 1, "OASv2-json": 18, "BibTeX": 1, "R": 5, "OASv3-json": 12, "ANTLR": 4} | package org.evomaster.core.search.gene.regex
import org.evomaster.core.output.OutputFormat
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.gene.GeneUtils
import org.evomaster.core.search.service.AdaptiveParameterControl
import org.evomaster.core.search.service.Randomness
class DisjunctionRxGene(
name: String,
val terms: List<RxTerm>,
/** does this disjunction match the beginning of the string, or could it be at any position? */
var matchStart: Boolean,
/** does this disjunction match the end of the string, or could it be at any position? */
var matchEnd: Boolean
) : RxAtom(name) {
/**
* whether we should append a prefix.
* this can only happen if [matchStart] is false
*/
var extraPrefix = false
/**
* whether we should append a postfix.
* this can only happen if [matchEnd] is false
*/
var extraPostfix = false
init {
for(t in terms){
t.parent = this
}
}
override fun copy(): Gene {
val copy = DisjunctionRxGene(name, terms.map { it.copy() as RxTerm }, matchStart, matchEnd)
copy.extraPrefix = this.extraPrefix
copy.extraPostfix = this.extraPostfix
return copy
}
override fun randomize(randomness: Randomness, forceNewValue: Boolean, allGenes: List<Gene>) {
terms.filter { it.isMutable() }
.forEach { it.randomize(randomness, forceNewValue, allGenes) }
if (!matchStart) {
extraPrefix = randomness.nextBoolean()
}
if (!matchEnd) {
extraPostfix = randomness.nextBoolean()
}
}
override fun isMutable(): Boolean {
return !matchStart || !matchEnd || terms.any { it.isMutable() }
}
override fun standardMutation(randomness: Randomness, apc: AdaptiveParameterControl, allGenes: List<Gene>) {
if(!matchStart && randomness.nextBoolean(0.05)){
extraPrefix = ! extraPrefix
} else if(!matchEnd && randomness.nextBoolean(0.05)){
extraPostfix = ! extraPostfix
} else {
val terms = terms.filter { it.isMutable() }
if(terms.isEmpty()){
return
}
val term = randomness.choose(terms)
term.standardMutation(randomness, apc, allGenes)
}
}
override fun getValueAsPrintableString(previousGenes: List<Gene>, mode: GeneUtils.EscapeMode?, targetFormat: OutputFormat?): String {
val prefix = if (extraPrefix) "prefix_" else ""
val postfix = if (extraPostfix) "_postfix" else ""
return prefix +
terms.map { it.getValueAsPrintableString(previousGenes, mode, targetFormat) }
.joinToString("") +
postfix
}
override fun copyValueFrom(other: Gene) {
if (other !is DisjunctionRxGene) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
for (i in 0 until terms.size) {
this.terms[i].copyValueFrom(other.terms[i])
}
this.extraPrefix = other.extraPrefix
this.extraPostfix = other.extraPostfix
}
override fun containsSameValueAs(other: Gene): Boolean {
if (other !is DisjunctionRxGene) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
for (i in 0 until terms.size) {
if (!this.terms[i].containsSameValueAs(other.terms[i])) {
return false
}
}
return this.extraPrefix == other.extraPrefix &&
this.extraPostfix == other.extraPostfix
}
override fun flatView(excludePredicate: (Gene) -> Boolean): List<Gene> {
return if (excludePredicate(this)) listOf(this)
else listOf(this).plus(terms.flatMap { it.flatView(excludePredicate) })
}
} | 1 | null | 1 | 1 | a7a120fe7c3b63ae370e8a114f3cb71ef79c287e | 3,920 | ASE-Technical-2021-api-linkage-replication | MIT License |
spenn-avstemming/src/test/kotlin/no/nav/helse/spenn/avstemming/AvstemmingerTest.kt | navikt | 176,742,371 | false | {"Kotlin": 304937, "Java": 41250, "Shell": 1358, "Dockerfile": 168} | package no.nav.helse.spenn.avstemming
import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import junit.framework.TestCase.assertEquals
import no.nav.helse.rapids_rivers.testsupport.TestRapid
import org.intellij.lang.annotations.Language
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import java.time.LocalDate
import java.time.LocalDateTime
import java.util.*
internal class AvstemmingerTest {
private val oppdragDao = mockk<OppdragDao>(relaxed = true)
private val avstemmingDao = mockk<AvstemmingDao>(relaxed = true)
private val utgåendeMeldinger = mutableListOf<String>()
private val utkø = object : UtKø {
override fun send(messageString: String) {
utgåendeMeldinger.add(messageString)
}
}
private val rapid = TestRapid().apply {
Avstemminger(this, oppdragDao, avstemmingDao, utkø)
}
@BeforeEach
fun clear() {
clearAllMocks()
rapid.reset()
utgåendeMeldinger.clear()
}
@Test
fun `avstemmer ikke dersom det ikke er noe å avstemme`() {
val dagen = LocalDate.of(2018, 1, 1)
rapid.sendTestMessage(utførAvstemming(dagen))
assertEquals(0, utgåendeMeldinger.size)
}
@Test
fun `avstemmer oppdrag`() {
val dagen = LocalDate.of(2018, 1, 1)
val oppdragTilAvstemming = mapOf(
"SPREF" to listOf(
OppdragDto(1024L, "fnr", "fagsystemId1", LocalDateTime.now(), Oppdragstatus.AKSEPTERT, 5000, "00", null, null)
),
"SP" to listOf(
OppdragDto(1025L, "fnr", "fagsystemId2", LocalDateTime.now(), Oppdragstatus.AKSEPTERT, 5000, "00", null, null)
)
)
every {
oppdragDao.hentOppdragForAvstemming(any())
} returns oppdragTilAvstemming
rapid.sendTestMessage(utførAvstemming(dagen))
verify(exactly = 1) {
avstemmingDao.nyAvstemming(any(), "SP", any(), 1)
avstemmingDao.nyAvstemming(any(), "SPREF", any(), 1)
oppdragDao.oppdaterAvstemteOppdrag("SP", any())
oppdragDao.oppdaterAvstemteOppdrag("SPREF", any())
}
assertEquals(6, utgåendeMeldinger.size)
}
@Language("JSON")
private fun utførAvstemming(dagen: LocalDate) = """
{
"@event_name": "utfør_avstemming",
"@id": "${UUID.randomUUID()}",
"@opprettet": "${LocalDateTime.now()}",
"dagen": "$dagen"
}
"""
@Language("JSON")
private fun avstemming(fagområde: String, nøkkelTom: Long) = """
{
"@event_name": "avstemming",
"@id": "${UUID.randomUUID()}",
"@opprettet": "${LocalDateTime.now()}",
"fagområde": "$fagområde",
"detaljer": {
"nøkkel_tom": $nøkkelTom,
"antall_oppdrag": 1
}
}
"""
}
| 1 | Kotlin | 1 | 2 | 598ec269a48405dd5612aceeb06cc636b366356c | 2,931 | helse-spenn | MIT License |
Android/ChangePageDemo/app/src/main/java/idv/william/changepagedemo/tabFragment/Tab2Fragment.kt | William-Weng | 124,631,494 | false | {"Text": 4, "Markdown": 10, "OpenStep Property List": 84, "XML": 168, "Swift": 93, "JSON": 75, "HTML": 1, "Godot Resource": 12, "Ignore List": 6, "Git Attributes": 2, "GDScript": 8, "SVG": 1, "Gradle Kotlin DSL": 6, "Java Properties": 10, "Shell": 4, "Batchfile": 2, "TOML": 2, "Proguard": 2, "Kotlin": 28, "INI": 8, "Java": 14, "Go Checksums": 1, "Go Module": 1, "Go": 3, "Objective-C++": 1, "Objective-C": 3, "Ruby": 1} | package idv.william.changepagedemo.tabFragment
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import idv.william.Utility
import idv.william.changepagedemo.R
import idv.william.changepagedemo.viewPager.Page1Fragment
import idv.william.changepagedemo.viewPager.Page2Fragment
import idv.william.changepagedemo.viewPager.Page3Fragment
class Tab2Fragment : Fragment() {
private lateinit var viewPager: ViewPager2
private val adapter = Adapter()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_tab2, container, false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Utility._Instance.wwLog(`class` = javaClass, message = "onCreate")
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initSetting()
}
/**
* 初始化設定
*/
private fun initSetting() {
val pagerAdapter = adapter.ViewPagerAdapter(this)
pagerAdapter.fragments = arrayOf(Page1Fragment(), Page2Fragment(), Page3Fragment())
viewPager = requireActivity().findViewById(R.id.viewPager)
viewPager.adapter = pagerAdapter
}
override fun onDestroyView() {
super.onDestroyView()
Utility._Instance.wwLog(`class` = javaClass, message = "onDestroyView")
}
override fun onDestroy() {
super.onDestroy()
Utility._Instance.wwLog(`class` = javaClass, message = "onDestroy")
}
/**
* 界面轉換器
*/
private inner class Adapter {
/**
* [給ViewPager用的轉換器](https://ithelp.ithome.com.tw/articles/10247948)
* @param fragmentActivity [Fragment](https://medium.com/wearejaya/data-structures-in-kotlin-array-parti-2984c85411b7)
*/
inner class ViewPagerAdapter(fragmentActivity: Fragment): FragmentStateAdapter(fragmentActivity) {
var fragments: Array<Fragment> = arrayOf()
override fun getItemCount(): Int {
return fragments.size
}
override fun createFragment(position: Int): Fragment {
return fragments[position]
}
}
}
} | 0 | Java | 0 | 3 | 47ba89224f791d0ee008ae46587b8f1d27778b59 | 2,514 | Problem | MIT License |
lib/core/src/test/java/dev/pthomain/android/dejavu/persistence/base/KeyValuePersistenceManagerUnitTest.kt | pthomain | 95,957,187 | false | {"Kotlin": 562195} | /*
*
* Copyright (C) 2017-2020 <NAME>
*
* 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 dev.pthomain.android.dejavu.persistence.base
import com.nhaarman.mockitokotlin2.*
import dev.pthomain.android.dejavu.configuration.error.glitch.Glitch
import dev.pthomain.android.dejavu.persistence.BasePersistenceManagerUnitTest
import dev.pthomain.android.dejavu.persistence.base.CacheDataHolder.Complete
import dev.pthomain.android.dejavu.persistence.base.CacheDataHolder.Incomplete
import dev.pthomain.android.dejavu.persistence.base.store.KeyValuePersistenceManager
import dev.pthomain.android.dejavu.persistence.base.store.KeyValueStore
import dev.pthomain.android.dejavu.serialisation.KeySerialiser
import dev.pthomain.android.dejavu.serialisation.KeySerialiser.Companion.SEPARATOR
import dev.pthomain.android.dejavu.shared.metadata.token.InstructionToken
import dev.pthomain.android.dejavu.cache.metadata.token.instruction.INVALID_HASH
import dev.pthomain.android.dejavu.cache.metadata.token.instruction.operation.Operation
import dev.pthomain.android.dejavu.cache.metadata.token.instruction.operation.Operation.Remote.Cache
import dev.pthomain.android.dejavu.test.assertByteArrayEqualsWithContext
import dev.pthomain.android.dejavu.test.assertEqualsWithContext
import dev.pthomain.android.dejavu.test.network.model.TestResponse
import dev.pthomain.android.dejavu.test.verifyNeverWithContext
import dev.pthomain.android.dejavu.test.verifyWithContext
//FIXME
internal class KeyValuePersistenceManagerUnitTest
: BasePersistenceManagerUnitTest<KeyValuePersistenceManager<Glitch>>() {
private lateinit var mockRightCacheDataHolder: Incomplete
private lateinit var mockWrongCacheDataHolder2: Incomplete
private lateinit var mockWrongCacheDataHolder1: Incomplete
private lateinit var mockIncompleteCacheDataHolder: Incomplete
private lateinit var mockCompleteCacheDataHolder: Complete
private lateinit var mockKeySerialiser: dev.pthomain.android.dejavu.serialisation.KeySerialiser
private lateinit var mockDejaVu.Configuration: DejaVu.Configuration<Glitch>
private lateinit var mockKeyValueStore: KeyValueStore<String, String, Incomplete>
private val mockEntryWithValidHash = mockHash + SEPARATOR + "abcd"
private val unrelatedEntryName = "unrelatedEntryName"
private val entryOfRightType = "EntryOfRightType"
private val entryOfWrongType1 = "EntryOfWrongType1"
private val entryOfWrongType2 = "EntryOfWrongType2"
private val invalidatedEntryName = "invalidatedEntryName"
override fun setUp(instructionToken: InstructionToken): KeyValuePersistenceManager<Glitch> {
mockKeySerialiser = mock()
mockIncompleteCacheDataHolder = Incomplete(
mockCacheDateTime,
mockExpiryDateTime,
mockBlob,
INVALID_HASH,
INVALID_HASH,
true,
true
)
mockDejaVu.Configuration = setUpConfiguration(instructionToken.instruction)
mockCompleteCacheDataHolder = with(mockIncompleteCacheDataHolder) {
Complete(
instructionToken.instruction.requestMetadata,
cacheDate,
expiryDate,
data,
isCompressed,
isEncrypted
)
}
mockKeyValueStore = mock()
mockWrongCacheDataHolder1 = mock()
mockWrongCacheDataHolder2 = mock()
mockRightCacheDataHolder = mock()
return KeyValuePersistenceManager(
mockDejaVu.Configuration,
mockDateFactory,
mockKeySerialiser,
mockKeyValueStore,
mockSerialisationManager
)
}
override fun prepareClearCache(context: String,
instructionToken: InstructionToken) {
val entryList = arrayOf(entryOfWrongType1, entryOfRightType, entryOfWrongType2)
whenever(mockKeyValueStore.values()).thenReturn(mapOf(
entryList[0] to mockWrongCacheDataHolder1,
entryList[1] to mockRightCacheDataHolder,
entryList[2] to mockWrongCacheDataHolder2
))
whenever(mockKeySerialiser.deserialise(eq(entryOfWrongType1))).thenReturn(mockWrongCacheDataHolder1)
whenever(mockKeySerialiser.deserialise(eq(entryOfWrongType2))).thenReturn(mockWrongCacheDataHolder2)
whenever(mockKeySerialiser.deserialise(eq(entryOfRightType))).thenReturn(mockRightCacheDataHolder)
val requestMetadata = instructionToken.instruction.requestMetadata
if (requestMetadata.responseClass == TestResponse::class.java) {
whenever(mockRightCacheDataHolder.responseClassHash).thenReturn(requestMetadata.classHash)
whenever(mockWrongCacheDataHolder1.responseClassHash).thenReturn("wrong1")
whenever(mockWrongCacheDataHolder2.responseClassHash).thenReturn("wrong2")
}
}
override fun verifyClearCache(context: String,
useTypeToClear: Boolean,
clearStaleEntriesOnly: Boolean,
mockClassHash: String) {
verifyWithContext(mockKeyValueStore, context).delete(eq(entryOfRightType))
if (!useTypeToClear) {
verifyWithContext(mockKeyValueStore, context).delete(eq(entryOfWrongType1))
verifyWithContext(mockKeyValueStore, context).delete(eq(entryOfWrongType2))
} else {
verifyNeverWithContext(mockKeyValueStore, context).delete(eq(entryOfWrongType1))
verifyNeverWithContext(mockKeyValueStore, context).delete(eq(entryOfWrongType2))
}
}
override fun prepareCache(iteration: Int,
operation: Cache,
hasPreviousResponse: Boolean,
isSerialisationSuccess: Boolean) {
if (isSerialisationSuccess) {
whenever(mockKeySerialiser.serialise(any()))
.thenReturn(mockEntryWithValidHash)
whenever(mockKeyValueStore.get(eq(mockEntryWithValidHash))).thenReturn(mockRightCacheDataHolder)
whenever(mockKeyValueStore.values()).thenReturn(mapOf(
unrelatedEntryName to mockWrongCacheDataHolder1,
mockEntryWithValidHash to mockRightCacheDataHolder
))
}
}
override fun verifyCache(context: String,
iteration: Int,
instructionToken: InstructionToken,
operation: Cache,
encryptData: Boolean,
compressData: Boolean,
hasPreviousResponse: Boolean,
isSerialisationSuccess: Boolean) {
if (isSerialisationSuccess) {
val dataHolderCaptor = argumentCaptor<Complete>()
verifyWithContext(mockKeySerialiser, context).serialise(dataHolderCaptor.capture())
val cacheDataHolder = dataHolderCaptor.firstValue
assertCacheDataHolder(
context,
instructionToken,
cacheDataHolder
)
verifyWithContext(mockKeyValueStore, context).delete(eq(mockEntryWithValidHash))
val argumentCaptor = argumentCaptor<Incomplete>()
verifyWithContext(mockKeyValueStore, context)
.save(eq(mockEntryWithValidHash), argumentCaptor.capture())
//TODO verify capture
} else {
verifyNeverWithContext(mockKeyValueStore, context).delete(eq(mockEntryWithValidHash))
}
verifyNeverWithContext(mockKeyValueStore, context).delete(eq(unrelatedEntryName))
}
private fun assertCacheDataHolder(context: String,
instructionToken: InstructionToken,
dataHolder: Complete) {
assertEqualsWithContext(
instructionToken.instruction.requestMetadata,
dataHolder.requestMetadata,
"RequestMetadata didn't match",
context
)
assertEqualsWithContext(
currentDateTime,
dataHolder.cacheDate,
"Cache date didn't match",
context
)
val operation = instructionToken.instruction.operation as Cache
assertEqualsWithContext(
currentDateTime + operation.durationInSeconds,
dataHolder.expiryDate,
"Expiry date didn't match",
context
)
assertByteArrayEqualsWithContext(
mockBlob,
dataHolder.data,
context
)
}
override fun prepareInvalidate(context: String,
operation: Operation,
instructionToken: InstructionToken) {
val entryList = mapOf(
mockEntryWithValidHash to mockRightCacheDataHolder
)
whenever(mockKeySerialiser.deserialise(
eq(instructionToken.instruction.requestMetadata),
eq(mockEntryWithValidHash)
)).thenReturn(mockCompleteCacheDataHolder)
val invalidatedHolder = mockCompleteCacheDataHolder.copy(expiryDate = 0L)
whenever(mockKeySerialiser.serialise(eq(invalidatedHolder)))
.thenReturn(invalidatedEntryName)
whenever(mockKeyValueStore.values()).thenReturn(entryList)
// whenever(mockKeyValueStore.get(
// eq(mockEntryWithValidHash)
// )).thenReturn(mockValidEntry)
//
// whenever(mockFileFactory.invoke(
// eq(mockCacheDirectory),
// eq(invalidatedEntryName)
// )).thenReturn(mockInvalidatedEntry)
}
override fun prepareCheckInvalidation(context: String,
operation: Operation,
instructionToken: InstructionToken) {
prepareInvalidate(
context,
operation,
instructionToken
)
}
override fun verifyCheckInvalidation(context: String,
operation: Operation,
instructionToken: InstructionToken) {
// if (operation.type == INVALIDATE || operation.type == REFRESH) {
// verifyWithContext(
// mockValidEntry,
// context
// ).renameTo(eq(mockInvalidatedEntry))
// } else {
// verifyNeverWithContext(
// mockValidEntry,
// context
// ).renameTo(any())
// }
}
override fun prepareGetCachedResponse(context: String,
operation: Cache,
instructionToken: InstructionToken,
hasResponse: Boolean,
isStale: Boolean,
isCompressed: Int,
isEncrypted: Int,
cacheDateTimeStamp: Long,
expiryDate: Long) {
val EntryList = arrayOf(mockEntryWithValidHash)
// whenever(mockCacheDirectory.list()).thenReturn(EntryList)
//
// whenever(mockFileFactory.invoke(eq(mockCacheDirectory), eq(mockEntryWithValidHash)))
// .thenReturn(mockValidEntry)
//
// whenever(mockFileInputStreamFactory.invoke(eq(mockValidEntry)))
// .thenReturn(mockInputStream)
//
// whenever(mockFileReader.invoke(eq(mockInputStream))).thenReturn(mockBlob)
whenever(mockKeySerialiser.deserialise(
eq(instructionToken.instruction.requestMetadata),
eq(mockEntryWithValidHash)
)).thenReturn(mockCompleteCacheDataHolder.copy(
cacheDate = cacheDateTimeStamp,
expiryDate = expiryDate,
isCompressed = isCompressed == 1,
isEncrypted = isEncrypted == 1
))
}
override fun verifyGetCachedResponse(context: String,
operation: Cache,
instructionToken: InstructionToken,
hasResponse: Boolean,
isStale: Boolean,
cachedResponse: ResponseWrapper<*, *, Glitch>?) {
assertEqualsWithContext(
mockBlob,
mockIncompleteCacheDataHolder.data,
context
)
}
}
| 1 | Kotlin | 7 | 12 | 6e82c422293f1ed54f3522d6df94c5948116a79a | 13,713 | dejavu | Apache License 2.0 |
app/src/main/java/org/covidwatch/android/data/model/UserFlow.kt | covidwatchorg | 261,834,815 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 2, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 2, "PlantUML": 2, "YAML": 3, "Proguard": 1, "Kotlin": 162, "INI": 1, "XML": 185, "Java": 2, "Protocol Buffer": 1} | package org.covidwatch.android.data.model
sealed class UserFlow
object FirstTimeUser : UserFlow()
object ReturnUser : UserFlow() | 11 | Kotlin | 7 | 11 | a9d6fe16427f131fb8e5a5044db34cedb760c56e | 131 | covidwatch-android-en | Apache License 2.0 |
common/declarative/src/main/kotlin/br/com/zup/beagle/action/ShowNativeDialog.kt | thosantunes | 269,216,984 | true | {"Kotlin": 1067509, "Swift": 638142, "C++": 262909, "Objective-C": 58562, "Java": 26545, "Ruby": 17188, "Shell": 1780, "C": 1109} | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* 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 br.com.zup.beagle.action
/**
* will show dialogues natively, such as an error alert indicating alternative flows, business system errors and others.
*
* @param title defines the title on the Dialog.
* @param message defines the Dialog message.
* @param buttonText define text of button in dialog.
*
*/
data class ShowNativeDialog(
val title: String,
val message: String,
val buttonText: String
) : Action | 1 | null | 1 | 1 | 046531e96d0384ae2917b0fd790f09d1a8142912 | 1,060 | beagle | Apache License 2.0 |
test-suite-kotlin/src/test/kotlin/io/micronaut/docs/httpclientexceptionbody/BooksController.kt | gaecom | 227,128,310 | true | {"Gradle": 44, "Markdown": 12, "Shell": 6, "AsciiDoc": 215, "Java Properties": 3, "Text": 3, "Ignore List": 1, "Batchfile": 1, "YAML": 10, "XML": 16, "Groovy": 1171, "Java": 2728, "INI": 11, "JSON": 7, "Kotlin": 301, "HTML": 8, "SVG": 2, "CSS": 81, "JavaScript": 3} | package io.micronaut.docs.httpclientexceptionbody
import io.micronaut.context.annotation.Requires
import io.micronaut.http.HttpResponse
import io.micronaut.http.HttpStatus
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import java.util.HashMap
@Requires(property = "spec.name", value = "BindHttpClientExceptionBodySpec")
//tag::clazz[]
@Controller("/books")
class BooksController {
@Get("/{isbn}")
fun find(isbn: String): HttpResponse<*> {
if (isbn == "1680502395") {
val m = HashMap<String, Any>()
m["status"] = 401
m["error"] = "Unauthorized"
m["message"] = "No message available"
m["path"] = "/books/$isbn"
return HttpResponse.status<Any>(HttpStatus.UNAUTHORIZED).body(m)
}
return HttpResponse.ok(Book("1491950358", "Building Microservices"))
}
}
//end::clazz[]
| 0 | null | 0 | 1 | d4a5f4a4a52da7ad88f782f3e0765aaacee3b4ae | 918 | micronaut-core | Apache License 2.0 |
BackEnd/Core/sailfish-core/src/main/kotlin/com/exactpro/sf/services/mina/MessageNextFilter.kt | exactpro | 163,079,637 | false | {"Java": 9440948, "TypeScript": 685302, "HTML": 525493, "JavaScript": 345815, "CSS": 187499, "Kotlin": 165033, "SCSS": 122654, "PLpgSQL": 52944, "Batchfile": 39562, "Shell": 36088, "FreeMarker": 1866} | /*******************************************************************************
* Copyright 2009-2021 Exactpro (Exactpro Systems Limited)
*
* 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.exactpro.sf.services.mina
import com.exactpro.sf.common.messages.IMessage
import com.exactpro.sf.common.util.EvolutionBatch
import mu.KotlinLogging
import org.apache.mina.core.filterchain.IoFilter
import org.apache.mina.core.session.IdleStatus
import org.apache.mina.core.session.IoSession
import org.apache.mina.core.write.WriteRequest
class MessageNextFilter : IoFilter.NextFilter {
private val _exceptions = arrayListOf<Throwable>()
val exceptions: Collection<Throwable>
get() = _exceptions
private val _results = arrayListOf<IMessage>()
val results: Collection<IMessage>
get() = _results
override fun messageReceived(session: IoSession, message: Any) {
if (message !is IMessage) {
LOGGER.error { "Decoded result ${message::class.java} is not ${IMessage::class.java}" }
return
}
if (message.name == EvolutionBatch.MESSAGE_NAME) {
_results += EvolutionBatch(message).batch
} else {
_results += message
}
}
override fun exceptionCaught(session: IoSession, cause: Throwable) {
_exceptions += cause
}
override fun sessionCreated(session: IoSession): Unit = throw UnsupportedOperationException()
override fun sessionOpened(session: IoSession): Unit = throw UnsupportedOperationException()
override fun sessionClosed(session: IoSession): Unit = throw UnsupportedOperationException()
override fun sessionIdle(session: IoSession, status: IdleStatus?): Unit = throw UnsupportedOperationException()
override fun inputClosed(session: IoSession): Unit = throw UnsupportedOperationException()
override fun messageSent(session: IoSession, writeRequest: WriteRequest?): Unit = throw UnsupportedOperationException()
override fun filterWrite(session: IoSession, writeRequest: WriteRequest?): Unit = throw UnsupportedOperationException()
override fun filterClose(session: IoSession): Unit = throw UnsupportedOperationException()
companion object {
private val LOGGER = KotlinLogging.logger { }
}
} | 28 | Java | 17 | 95 | 697eaa4290392ded41f0114dcea541a7fce86feb | 2,880 | sailfish-core | Apache License 2.0 |
kotlin/1323. Maximum 69 Number .kt | bchadwic | 372,917,249 | false | null | class Solution {
fun maximum69Number (f_num: Int): Int {
/*
initial thoughts: find the left most `6` and change it to a `9`
change it by adding a 3 or 3*10*x? depending on where the value we are changing is
revised approach: add all the numbers to a stack, then pop them off into a num and change the left
most 6 to a 9
helpful resource
https://stackoverflow.com/questions/3389264/how-to-get-the-separate-digits-of-an-int-number
*/
// get the length of a number using this formula (0-indexed)
val size = kotlin.math.log10(f_num.toDouble()).toInt()
val stack = Stack<Int>()
// create a non final copy
var num = f_num
for(i in 0..size){
stack.push(num % 10)
num /= 10
}
var changed = false
while(!stack.isEmpty()){
num *= 10
with(stack.pop()){
num += if(!changed && this == 6){
changed = !changed
9
} else this
}
}
return num
}
}
| 1 | null | 5 | 13 | 29070c0250b7ea3f91db04076c8aff5504a9caec | 1,186 | BoardMasters-Question-Of-The-Day | MIT License |
examples/todoList/src/main/kotlin/com/brianegan/bansa/todoList/RootView.kt | brianegan | 47,591,925 | false | null | package com.brianegan.bansa.todoList
import android.content.Context
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.LinearLayout
import com.brianegan.bansa.Store
import trikita.anvil.Anvil
import trikita.anvil.DSL.*
import trikita.anvil.RenderableView
import trikita.anvil.recyclerview.v7.RecyclerViewv7DSL.*
class RootView(c: Context, val store: Store<ApplicationState>) : RenderableView(c) {
val stateChangeSubscription = store.subscribe { Anvil.render() }
val mapCounterToCounterViewModel = buildMapCounterToCounterViewModel(store)
val adapter = BansaRenderableRecyclerViewAdapter(
mapCounterToCounterViewModel,
::todoView,
{ models, pos ->
models[pos].id.leastSignificantBits
}, true
)
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
stateChangeSubscription.unsubscribe()
}
override fun view() {
frameLayout {
padding(dip(16), dip(16), dip(16), 0)
linearLayout {
size(FILL, dip(48))
orientation(LinearLayout.HORIZONTAL)
margin(0, dip(10))
editText {
size(dip(0), FILL)
weight(1F)
singleLine(true)
imeOptions(EditorInfo.IME_ACTION_DONE)
text(store.state.newTodoMessage)
onTextChanged({ s -> store.dispatch(UPDATE_NEW_TODO_MESSAGE(s.toString())) })
onEditorAction { textView, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_SEARCH
|| actionId == EditorInfo.IME_ACTION_DONE
|| event?.action == KeyEvent.ACTION_DOWN
&& event?.keyCode == KeyEvent.KEYCODE_ENTER
&& store.state.newTodoMessage.length > 0
) {
store.dispatch(ADD(store.state.newTodoMessage))
true
} else {
false
}
}
}
button {
id(R.id.todo_submit)
size(WRAP, FILL)
text(R.string.add_todo)
onClick {
if (store.state.newTodoMessage.length > 0) {
store.dispatch(ADD(store.state.newTodoMessage))
}
}
}
}
recyclerView {
init {
layoutManager(LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false))
itemAnimator(DefaultItemAnimator())
hasFixedSize(false)
margin(dip(0), dip(56), dip(0), dip(0))
size(FILL, FILL)
}
adapter(adapter.update(store.state.todos))
}
}
}
}
| 4 | null | 29 | 442 | ffb606ad2aefa58cac08e9daee26b6767b03186b | 3,213 | bansa | MIT License |
mobile-common-lib/src/commonMain/kotlin/fi/riista/common/domain/observation/dto/ObservationSpecimenMarkingDTO.kt | suomenriistakeskus | 78,840,058 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 2, "Text": 4, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "Markdown": 4, "Gradle Kotlin DSL": 1, "Kotlin": 1344, "XML": 401, "Java": 161, "Protocol Buffer": 1, "JSON": 1} | package fi.riista.common.domain.observation.dto
typealias ObservationSpecimenMarkingDTO = String
| 0 | Kotlin | 0 | 3 | 23645d1abe61c68d649b6d0ca1d16556aa8ffa16 | 98 | oma-riista-android | MIT License |
frontend/silk-foundation/src/jsMain/kotlin/com/varabyte/kobweb/silk/components/style/breakpoint/BreakpointValues.kt | varabyte | 389,223,226 | false | null | package com.varabyte.kobweb.silk.components.style.breakpoint
import kotlinx.browser.window
import org.jetbrains.compose.web.css.*
import org.w3c.dom.Window
private val Window.bodyFontSize: Number
get() {
val bodySize = document.body?.let { body ->
getComputedStyle(body).getPropertyValue("font-size").removeSuffix("px").toIntOrNull()
}
return bodySize ?: 16
}
sealed class BreakpointUnitValue<out T : CSSUnitValue>(val width: T) {
abstract fun toPx(): CSSpxValue
class Px(value: CSSpxValue) : BreakpointUnitValue<CSSpxValue>(value) {
override fun toPx(): CSSpxValue {
return width
}
}
class Em(value: CSSSizeValue<CSSUnit.em>) : BreakpointUnitValue<CSSSizeValue<CSSUnit.em>>(value) {
override fun toPx(): CSSpxValue {
return (width.value.toDouble() * window.bodyFontSize.toDouble()).px
}
}
class Rem(value: CSSSizeValue<CSSUnit.rem>) : BreakpointUnitValue<CSSSizeValue<CSSUnit.rem>>(value) {
override fun toPx(): CSSpxValue {
return (width.value.toDouble() * window.bodyFontSize.toDouble()).px
}
}
}
/**
* A class used for storing generic values associated with breakpoints.
*/
data class BreakpointValues<out T : CSSUnitValue>(
val sm: BreakpointUnitValue<T>,
val md: BreakpointUnitValue<T>,
val lg: BreakpointUnitValue<T>,
val xl: BreakpointUnitValue<T>,
)
/**
* A convenience class for constructing an association of breakpoints to CSS pixel sizes.
*/
fun BreakpointSizes(
sm: CSSpxValue,
md: CSSpxValue,
lg: CSSpxValue,
xl: CSSpxValue,
) = BreakpointValues(
BreakpointUnitValue.Px(sm),
BreakpointUnitValue.Px(md),
BreakpointUnitValue.Px(lg),
BreakpointUnitValue.Px(xl)
)
/**
* A convenience class for constructing an association of breakpoints to CSS em sizes.
*/
fun BreakpointSizes(
sm: CSSSizeValue<CSSUnit.em>,
md: CSSSizeValue<CSSUnit.em>,
lg: CSSSizeValue<CSSUnit.em>,
xl: CSSSizeValue<CSSUnit.em>,
) = BreakpointValues(
BreakpointUnitValue.Em(sm),
BreakpointUnitValue.Em(md),
BreakpointUnitValue.Em(lg),
BreakpointUnitValue.Em(xl)
)
/**
* A convenience class for constructing an association of breakpoints to CSS rem sizes.
*/
fun BreakpointSizes(
sm: CSSSizeValue<CSSUnit.rem> = 0.cssRem,
md: CSSSizeValue<CSSUnit.rem> = sm,
lg: CSSSizeValue<CSSUnit.rem> = md,
xl: CSSSizeValue<CSSUnit.rem> = lg,
) = BreakpointValues(
BreakpointUnitValue.Rem(sm),
BreakpointUnitValue.Rem(md),
BreakpointUnitValue.Rem(lg),
BreakpointUnitValue.Rem(xl),
)
| 113 | null | 70 | 992 | a6061d7a3b53383e055a94ef4aa430af6647f8b4 | 2,636 | kobweb | Apache License 2.0 |
app/src/main/java/com/crossbowffs/quotelock/data/modules/openai/OpenAIDatabase.kt | Yubyf | 60,074,817 | false | {"Kotlin": 995709} | package com.crossbowffs.quotelock.data.modules.openai
import android.content.Context
import android.provider.BaseColumns
import androidx.room.ColumnInfo
import androidx.room.Dao
import androidx.room.Database
import androidx.room.Delete
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.PrimaryKey
import androidx.room.Query
import androidx.room.Room
import androidx.room.RoomDatabase
import com.crossbowffs.quotelock.data.modules.openai.OpenAIUsageContract.DATABASE_NAME
import kotlinx.coroutines.flow.Flow
const val OPENAI_USAGE_DB_VERSION = 1
object OpenAIUsageContract {
const val DATABASE_NAME = "openai_usage.db"
const val TABLE = "usage"
const val ID = BaseColumns._ID
const val API_KEY = "api_key"
const val MODEL = "model"
const val TOKENS = "tokens"
const val TIMESTAMP = "timestamp"
}
@Entity(tableName = OpenAIUsageContract.TABLE)
data class OpenAIUsageEntity(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = OpenAIUsageContract.ID)
val id: Int? = null,
@ColumnInfo(name = OpenAIUsageContract.API_KEY)
val apiKey: String,
@ColumnInfo(name = OpenAIUsageContract.MODEL)
val model: String,
@ColumnInfo(name = OpenAIUsageContract.TOKENS)
val tokens: Int,
@ColumnInfo(name = OpenAIUsageContract.TIMESTAMP)
val timestamp: Long = System.currentTimeMillis(),
)
@Dao
interface OpenAIUsageDao {
@Query(
"SELECT * FROM ${OpenAIUsageContract.TABLE} WHERE ${OpenAIUsageContract.API_KEY} = :apiKey " +
"AND ${OpenAIUsageContract.TIMESTAMP} >= (:startDate / 1000)"
)
fun getUsageByApiKeyStream(apiKey: String, startDate: Long): Flow<List<OpenAIUsageEntity>>
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(quote: OpenAIUsageEntity): Long?
@Delete
suspend fun delete(quote: OpenAIUsageEntity): Int
@Query("DELETE FROM ${OpenAIUsageContract.TABLE} WHERE ${OpenAIUsageContract.ID} = :id")
suspend fun delete(id: Long): Int
@Query("DELETE FROM ${OpenAIUsageContract.TABLE}")
suspend fun deleteAll()
}
@Database(entities = [OpenAIUsageEntity::class], version = OPENAI_USAGE_DB_VERSION)
abstract class OpenAIUsageDatabase : RoomDatabase() {
abstract fun dao(): OpenAIUsageDao
companion object {
@Volatile
private var INSTANCE: OpenAIUsageDatabase? = null
fun getDatabase(context: Context): OpenAIUsageDatabase {
// if the INSTANCE is not null, then return it,
// if it is, then create the database
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
OpenAIUsageDatabase::class.java,
DATABASE_NAME
).setJournalMode(JournalMode.TRUNCATE).build()
INSTANCE = instance
// return instance
instance
}
}
}
} | 8 | Kotlin | 3 | 79 | 7e82ba2c535ed6f68a81c762805038f2b8bf0e4f | 3,019 | QuoteLockX | MIT License |
domain-events/src/main/kotlin/events/employee/EmployeeEvents.kt | honeyballs | 227,557,896 | false | null | package events.employee
import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.fasterxml.jackson.annotation.JsonTypeName
import events.Event
import java.math.BigDecimal
import java.time.LocalDate
@JsonTypeName("employee-created")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
data class EmployeeCreated(
val employeeId: String,
val firstname: String,
val lastname: String,
val birthday: LocalDate,
val street: String,
val no: Int,
val city: String,
val zipCode: Int,
val iban: String,
val bic: String,
val bankname: String,
val department: String,
val position: String,
val availableVacationHours: Int,
val hourlyRate: BigDecimal,
val mail: String
) : Event() {
init {
type = "Employee created"
}
}
@JsonTypeName("employee-change-name")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
data class EmployeeChangedName(
val firstname: String,
val lastname: String,
val mail: String
) : Event() {
init {
type = "Employee changed name"
}
}
@JsonTypeName("employee-moved")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
data class EmployeeMoved(
val street: String,
val no: Int,
val city: String,
val zipCode: Int
) : Event() {
init {
type = "Employee moved"
}
}
@JsonTypeName("employee-adjusted-rate")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
data class EmployeeRateAdjusted(
val rate: BigDecimal
) : Event() {
init {
type = "Employee rate adjusted"
}
}
@JsonTypeName("employee-changed-department")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
data class EmployeeChangedDepartment(
val department: String
) : Event() {
init {
type = "Employee changed department"
}
}
@JsonTypeName("employee-changed-banking")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
data class EmployeeChangedBanking(
val iban: String,
val bic: String,
val bankname: String
) : Event() {
init {
type = "Employee changed banking"
}
}
@JsonTypeName("employee-changed-position")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
data class EmployeeChangedPosition(
val position: String
) : Event() {
init {
type = "Employee changed job position"
}
}
@JsonTypeName("employee-deleted")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
data class EmployeeDeleted(
val deleted: Boolean = true
) : Event() {
init {
type = "Employee deleted"
}
} | 0 | Kotlin | 0 | 0 | 96fb9e43eeb8c190e0737216b442e70623d17ab9 | 2,737 | microservice-event-sourcing | MIT License |
app/src/main/java/de/htwdd/htwdresden/ui/models/Overview.kt | HTWDD | 42,391,208 | false | null | package de.htwdd.htwdresden.ui.models
import androidx.databinding.ObservableField
import de.htwdd.htwdresden.BR
import de.htwdd.htwdresden.R
import de.htwdd.htwdresden.interfaces.Identifiable
import de.htwdd.htwdresden.interfaces.Modelable
import de.htwdd.htwdresden.utils.extensions.*
import de.htwdd.htwdresden.utils.holders.StringHolder
//-------------------------------------------------------------------------------------------------- Protocols
interface Overviewable: Identifiable<Modelable>
//-------------------------------------------------------------------------------------------------- Schedule Item
class OverviewScheduleItem(val item: Timetable, val addElective: Boolean = false): Overviewable {
override val viewType: Int
get() = R.layout.list_item_overview_schedule_bindable
override val bindings by lazy {
ArrayList<Pair<Int, Modelable>>().apply {
add(BR.overviewScheduleModel to model)
}
}
private val model = OverviewScheduleModel()
private val sh: StringHolder by lazy { StringHolder.instance }
init {
model.apply {
name.set(item.name)
setProfessor(item.professor)
studiumIntegrale.set(item.studiumIntegrale)
custom.set(item.createdByUser)
type.set(with(item.type) {
when {
startsWith("v", true) -> sh.getString(R.string.lecture)
startsWith("ü", true) -> sh.getString(R.string.excersise)
startsWith("p", true) -> sh.getString(R.string.practical)
startsWith("b", true) -> sh.getString(R.string.block)
startsWith("r", true) -> sh.getString(R.string.requested)
else -> sh.getString(R.string.unknown)
}
})
beginTime.set(item.beginTime.format("HH:mm"))
endTime.set(item.endTime.format("HH:mm"))
/* val colors = sh.getStringArray(R.array.timetableColors)
val colorPosition = Integer.parseInt("${item.name} - ${item.professor}".toSHA256().subSequence(0..5).toString(), 16) % colors.size
lessonColor.set(colors[colorPosition].toColor())*/
val colors = sh.getStringArray(R.array.typeColors)
val colorPosition = item.type.getColorPositionForLessonType() % colors.size
lessonColor.set(colors[colorPosition].toColor())
//if we're in the elective choice list
if (addElective){
showDay.set(true)
day.set(
item.day.convertDayToString(sh)
)
}
setRooms(item.rooms)
}
}
override fun equals(other: Any?) = hashCode() == other.hashCode()
override fun hashCode() = item.hashCode()
}
//-------------------------------------------------------------------------------------------------- FreeDay Item
class OverviewFreeDayItem: Overviewable {
override val viewType: Int
get() = R.layout.list_item_overview_free_day_bindable
override val bindings: ArrayList<Pair<Int, Modelable>>
get() = ArrayList()
override fun equals(other: Any?) = hashCode() == other.hashCode()
override fun hashCode() = viewType * 31
}
//-------------------------------------------------------------------------------------------------- Mensa Item
class OverviewMensaItem(private val item: Meal): Overviewable {
override val viewType: Int
get() = R.layout.list_item_overview_mensa_bindable
override val bindings by lazy {
ArrayList<Pair<Int, Modelable>>().apply {
add(BR.overviewMensaModel to model)
}
}
private val model = OverviewMensaModel()
init {
model.apply {
name.set(item.name)
}
}
override fun equals(other: Any?) = hashCode() == other.hashCode()
override fun hashCode() = item.hashCode()
}
//-------------------------------------------------------------------------------------------------- Grade Item
class OverviewGradeItem(private val grades: String, private val credits: Float): Overviewable {
override val viewType: Int
get() = R.layout.list_item_overview_grade_bindable
override val bindings by lazy {
ArrayList<Pair<Int, Modelable>>().apply {
add(BR.overviewGradeModel to model)
}
}
private val model = OverviewGradeModel()
private val sh by lazy { StringHolder.instance }
init {
model.apply {
grades.set(sh.getString(R.string.grades, [email protected]))
credits.set(sh.getString(R.string.exams_stats_count_credits, [email protected]))
}
}
override fun equals(other: Any?) = hashCode() == other.hashCode()
override fun hashCode(): Int {
var result = grades.hashCode()
result = 31 * result + credits.hashCode()
return result
}
}
//-------------------------------------------------------------------------------------------------- Header Item
class OverviewHeaderItem(private val header: String, private val subheader: String, private val subheaderVisible: Boolean? = true): Overviewable {
override val viewType: Int
get() = R.layout.list_item_overview_header_bindable
override val bindings by lazy {
ArrayList<Pair<Int, Modelable>>().apply {
add(BR.overviewHeaderModel to model)
}
}
private val model = OverviewHeaderModel()
var credits: String
get() = model.subheader.get() ?: ""
set(value) = model.subheader.set(value)
init {
model.apply {
header.set([email protected])
subheader.set([email protected])
//bug 21007 average grades turned off
subheaderVisible.set([email protected])
}
}
override fun equals(other: Any?) = hashCode() == other.hashCode()
override fun hashCode(): Int {
var result = header.hashCode()
result = 31 * result + subheader.hashCode()
result = 31 * result + subheaderVisible.hashCode()
return result
}
}
//-------------------------------------------------------------------------------------------------- StudyGroup Item
class OverviewStudyGroupItem: Overviewable {
override val viewType: Int
get() = R.layout.list_item_overview_no_studygroup_bindable
override val bindings: ArrayList<Pair<Int, Modelable>>
get() = ArrayList()
override fun equals(other: Any?) = hashCode() == other.hashCode()
override fun hashCode() = 31 * viewType
}
//-------------------------------------------------------------------------------------------------- Login Item
class OverviewLoginItem: Overviewable {
override val viewType: Int
get() = R.layout.list_item_overview_no_login_bindable
override val bindings: ArrayList<Pair<Int, Modelable>>
get() = ArrayList()
override fun equals(other: Any?) = hashCode() == other.hashCode()
override fun hashCode() = 31 * viewType
}
//-------------------------------------------------------------------------------------------------- Schedule Model
class OverviewScheduleModel: Modelable {
val name = ObservableField<String>()
val professor = ObservableField<String>()
val type = ObservableField<String>()
val beginTime = ObservableField<String>()
val endTime = ObservableField<String>()
val rooms = ObservableField<String>()
val hasProfessor = ObservableField<Boolean>()
val hasRooms = ObservableField<Boolean>()
val showDay = ObservableField<Boolean>()
val day = ObservableField<String>()
val studiumIntegrale = ObservableField<Boolean>()
val custom = ObservableField<Boolean>()
val lessonColor = ObservableField<Int>()
fun setProfessor(professor: String?) {
hasProfessor.set(!professor.isNullOrEmpty())
this.professor.set(professor)
}
fun setRooms(list: List<String>) {
hasRooms.set(!list.isNullOrEmpty())
rooms.set(list.joinToString(", "))
}
}
//-------------------------------------------------------------------------------------------------- Mensa Model
class OverviewMensaModel: Modelable {
val name = ObservableField<String>()
}
//-------------------------------------------------------------------------------------------------- Grade Model
class OverviewGradeModel: Modelable {
val grades = ObservableField<String>()
val credits = ObservableField<String>()
}
//-------------------------------------------------------------------------------------------------- Header Model
class OverviewHeaderModel: Modelable {
val header = ObservableField<String>()
val subheader = ObservableField<String>()
val subheaderVisible = ObservableField<Boolean>()
} | 1 | null | 4 | 6 | 064c5f3ca118a6f51993fb47997cb8089e584963 | 8,993 | HTWDresden-Android | MIT License |
app/src/main/java/com/breezefsmparaspanmasala/features/nearbyshops/model/ShopListResponse.kt | DebashisINT | 646,827,078 | false | null | package com.breezefsmparaspanmasala.features.nearbyshops.model
import com.breezefsmparaspanmasala.base.BaseResponse
/**
* Created by Pratishruti on 28-11-2017.
*/
class ShopListResponse : BaseResponse() {
var data: ShopListResponseData? = null
} | 0 | Kotlin | 0 | 0 | f127bbd9a3df67b161bb1913fc1cc88359be5655 | 254 | ParasPanMasala | Apache License 2.0 |
src/main/kotlin/aoc03/solution.kt | dnene | 317,653,484 | false | null | package aoc03
import java.io.File
tailrec fun Array<CharArray>.countTrees(
slopeRight: Int,
slopeDown: Int,
startRow: Int = 0,
startCol: Int = 0,
treesSoFar: Int = 0
): Int {
val newRow = startRow + slopeDown
return if (newRow > (this.size - 1)) treesSoFar
else {
val newCol = (startCol + slopeRight) % this[0].size
val newTreeCount = if (this[newRow][newCol] == '#') treesSoFar + 1 else treesSoFar
countTrees(slopeRight, slopeDown, newRow, newCol, newTreeCount)
}
}
fun main(args: Array<String>) {
File("data/inputs/aoc03.txt")
.readLines()
.map { it.toCharArray() }
.toTypedArray()
.run {
// Note: Part 1
countTrees(3,1)
.let { println(it) }
// Note: Part 2
listOf((1 to 1), (3 to 1), (5 to 1), (7 to 1), (1 to 2))
.map { countTrees(it.first, it.second) }
.fold(1L) { acc, elem -> acc * elem }
.let { println(it) }
}
} | 0 | Kotlin | 0 | 0 | db0a2f8b484575fc3f02dc9617a433b1d3e900f1 | 1,040 | aoc2020 | MIT License |
SharedCode/src/commonTest/kotlin/dev/polek/episodetracker/common/model/SeasonsViewModelTest.kt | y-polek | 234,707,032 | false | null | package dev.polek.episodetracker.common.model
import assertk.assertThat
import assertk.assertions.isEqualTo
import assertk.assertions.isNull
import dev.polek.episodetracker.common.presentation.showdetails.model.SeasonViewModel
import dev.polek.episodetracker.common.presentation.showdetails.model.SeasonsViewModel
import kotlin.test.Test
class SeasonsViewModelTest {
private val seasons = SeasonsViewModel(
listOf(
SeasonViewModel(
number = 1,
name = "Season 1",
episodes = listOf()),
SeasonViewModel(
number = 3,
name = "Season 3",
episodes = listOf()),
SeasonViewModel(
number = 4,
name = "Season 4",
episodes = listOf()),
SeasonViewModel(
number = 2,
name = "Season 2",
episodes = listOf())
)
)
@Test
fun `test 'get(Int)' operator`() {
assertThat(seasons[0]).isNull()
assertThat(seasons[1]?.number).isEqualTo(1)
assertThat(seasons[2]?.number).isEqualTo(2)
assertThat(seasons[3]?.number).isEqualTo(3)
assertThat(seasons[4]?.number).isEqualTo(4)
assertThat(seasons[42]).isNull()
}
@Test
fun `test get(IntRange)`() {
assertThat(
seasons.get(1..4).map(SeasonViewModel::number).toList()
).isEqualTo(
listOf(1, 2, 3, 4)
)
assertThat(
seasons.get(0..42).map(SeasonViewModel::number).toList()
).isEqualTo(
listOf(1, 2, 3, 4)
)
assertThat(
seasons.get(1 until 1).map(SeasonViewModel::number).toList()
).isEqualTo(
emptyList()
)
}
}
| 0 | Kotlin | 1 | 3 | 3ecbee176b5d1a74e293b94af74229aa17cff2dd | 1,813 | EpisodeTracker | Apache License 2.0 |
app/src/main/java/com/dscvit/periodsapp/ui/requests/RequestsFragment.kt | GDGVIT | 234,146,371 | false | null | package com.dscvit.periodsapp.ui.requests
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.dscvit.periodsapp.R
import com.dscvit.periodsapp.adapter.RequestListAdapter
import com.dscvit.periodsapp.model.Result
import com.dscvit.periodsapp.model.requests.Request
import com.dscvit.periodsapp.repository.AppRepository
import com.dscvit.periodsapp.utils.*
import com.dscvit.periodsapp.websocket.ChatWsListener
import kotlinx.android.synthetic.main.fragment_requests.*
import okhttp3.OkHttpClient
import org.koin.android.ext.android.inject
import org.koin.android.viewmodel.ext.android.viewModel
import java.util.*
import kotlin.math.*
class RequestsFragment : Fragment() {
private val repo by inject<AppRepository>()
private val requestsViewModel by viewModel<RequestsViewModel>()
private lateinit var requestsList: List<Request>
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_requests, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
requestsProgressBar.hide()
val sharedPrefs = PreferenceHelper.customPrefs(requireContext(), Constants.PREF_NAME)
val authKey = sharedPrefs.getString(Constants.PREF_AUTH_KEY, "")
val senderId = sharedPrefs.getInt(Constants.PREF_USER_ID, 0)
requestsToolbar.title = "Requests"
val requestListAdapter = RequestListAdapter()
requestsRecyclerView.apply {
layoutManager = LinearLayoutManager(requireContext())
adapter = requestListAdapter
addItemDecoration(
DividerItemDecoration(
requireContext(),
DividerItemDecoration.VERTICAL
)
)
}
//getLocationAndUpdateDb()
val lat = sharedPrefs.getFloat(Constants.PREF_CURR_LAT, 0f).toDouble()
val lon = sharedPrefs.getFloat(Constants.PREF_CURR_LON, 0f).toDouble()
Log.d("esh", lat.toString())
Log.d("esh", lon.toString())
makeNetworkCallUpdateDb(lat, lon)
repo.getAllRequests().observe(viewLifecycleOwner, Observer {
if (it.isEmpty()) {
noRequestTextView.show()
} else {
noRequestTextView.hide()
}
requestsList = it
requestListAdapter.updateRequests(it)
})
val client = OkHttpClient()
val wsListener: ChatWsListener by inject()
requestsRecyclerView.addOnItemClickListener(object : OnItemClickListener {
override fun onItemClicked(position: Int, view: View) {
val receiverId = requestsList[position].userId
val selTime = requestsList[position].dateTimeString.substring(11, 13).toInt()
val selDate = requestsList[position].dateTimeString.substring(8, 10).toInt()
val timeFormat = Calendar.getInstance()
timeFormat.timeZone = TimeZone.getTimeZone("UTC")
val currTime = timeFormat.get(Calendar.HOUR_OF_DAY)
val currDate = timeFormat.get(Calendar.DATE)
val timeDiff = currTime - selTime
var isSameDay = false
if (currDate == selDate) {
isSameDay = true
}
if (timeDiff < 3 && isSameDay) {
val baseUrl = "${Constants.WS_BASE_URL}$authKey/$receiverId/1/"
val request = okhttp3.Request.Builder().url(baseUrl).build()
val ws = client.newWebSocket(request, wsListener)
val msg = "Hi I am willing to help"
ws.send("{\"message\": \"$msg\", \"sender_id\": $senderId, \"receiver_id\": $receiverId}")
ws.close(1000, "Close Normal")
requestsViewModel.requestIsDone(requestsList[position].id)
requestsProgressBar.show()
requestsRecyclerView.hide()
Handler().postDelayed({
requestsProgressBar.hide()
findNavController().navigate(R.id.chatsFragment)
}, 1500)
} else {
requireContext().shortToast("Request has expired")
}
}
})
}
/*
@SuppressWarnings("MissingPermission")
private fun getLocationAndUpdateDb() {
val locationManager =
requireContext().getSystemService(Context.LOCATION_SERVICE) as LocationManager
locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, object :
LocationListener {
override fun onLocationChanged(location: Location?) {
if (location != null) {
val lat = location.latitude
val lon = location.longitude
makeNetworkCallUpdateDb(lat, lon)
}
}
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}
override fun onProviderEnabled(provider: String?) {}
override fun onProviderDisabled(provider: String?) {
requireContext().shortToast("Turn on Location")
}
}, Looper.getMainLooper())
}
*/
private fun makeNetworkCallUpdateDb(lat: Double, lon: Double) {
requestsViewModel.getAlerts().observe(viewLifecycleOwner, Observer {
when (it.status) {
Result.Status.LOADING -> {
}
Result.Status.SUCCESS -> {
if (it.data?.message == "Received Alert") {
for (alert in it.data.alert) {
if (calculateDistance(lat, lon, alert.latitude, alert.longitude) <= 5) {
val request = Request(
alert.id,
alert.userId,
alert.userUsername,
alert.dateTimeCreation,
0
)
requestsViewModel.upsertRequest(request)
}
}
}
}
Result.Status.ERROR -> {
requireContext().shortToast("Error in getting alerts")
Log.d("esh", it.message)
}
}
})
}
private fun calculateDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
val r = 6371
val dLat = degToRad(lat1) - degToRad(lat2)
val dLon = degToRad(lon1) - degToRad(lon2)
val temp =
sin(dLat / 2).pow(2) + cos(degToRad(lat1)) * cos(degToRad(lat2)) * (sin(dLon / 2).pow(2))
return r * (2 * asin(sqrt(temp)))
}
private fun degToRad(deg: Double): Double {
return (deg * PI / 180)
}
}
| 0 | null | 2 | 2 | 027cfe5e05ab0953c21b6924a3ddea8b8f48c36f | 7,585 | PeriodAlert-App | MIT License |
app/src/main/java/ru/keytomyself/dzeninteract/screens/pager/views/pages/SelectionVariantView.kt | andrey-ananiev | 600,169,706 | false | null | package ru.keytomyself.dzeninteract.screens.pager.views.pages
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.selection.selectable
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import ru.keytomyself.dzeninteract.R
import ru.keytomyself.dzeninteract.screens.pager.models.PageModel
import ru.keytomyself.dzeninteract.screens.pager.views.VariantItem
@Composable
fun SelectionVariantView(
page: PageModel.SelectionVariant,
onPositionChanged: (Int) -> Unit,
) {
page.variantIdList.forEachIndexed { i, variantId ->
val index = i + 1
Row(
modifier = Modifier
.fillMaxWidth(0.7F)
.clip(MaterialTheme.shapes.medium)
.selectable(
selected = page.variantPosition == index,
onClick = { onPositionChanged(index) }
)
.padding(4.dp),
verticalAlignment = Alignment.CenterVertically
) {
VariantItem(
isChecked = index == page.variantPosition,
textId = variantId,
iconId = R.drawable.ic_check
)
}
}
} | 0 | Kotlin | 0 | 0 | 7c4e011bc47f7c5be850c6bf89588d26c8efe8fb | 1,404 | vk-Cup-2022-23-Dzen-Interact | Creative Commons Zero v1.0 Universal |
app/src/main/java/ru/timelimit/healthtracking/ui/home/HomeSecondFragment.kt | Unkorunk | 260,849,753 | false | null | package ru.timelimit.healthtracking.ui.home
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import ru.timelimit.healthtracking.R
class HomeSecondFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home_second, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<TextView>(R.id.textview_home_second).text =
getString(R.string.hello_home_second)
// view.findViewById<Button>(R.id.button_home_second).setOnClickListener {
// findNavController().navigate(R.id.action_HomeSecondFragment_to_HomeFragment)
// }
}
}
| 0 | Kotlin | 0 | 0 | 0541b39693b3fde07c1f965d6a5016d120ea63cc | 1,167 | health-tracking-frontend | MIT License |
mobile_app1/module364/src/main/java/module364packageKt0/Foo1335.kt | uber-common | 294,831,672 | false | null | package module364packageKt0;
annotation class Foo1335Fancy
@Foo1335Fancy
class Foo1335 {
fun foo0(){
module364packageKt0.Foo1334().foo6()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
fun foo4(){
foo3()
}
fun foo5(){
foo4()
}
fun foo6(){
foo5()
}
} | 6 | Java | 6 | 72 | 9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e | 331 | android-build-eval | Apache License 2.0 |
compose-multiplatform/library/src/commonMain/kotlin/com/kizitonwose/calendar/core/Year.kt | kizitonwose | 182,417,603 | false | {"Kotlin": 670112, "HTML": 343, "CSS": 102} | package com.kizitonwose.calendar.core
import androidx.compose.runtime.Immutable
import com.kizitonwose.calendar.core.format.fromIso8601Year
import com.kizitonwose.calendar.core.format.toIso8601String
import com.kizitonwose.calendar.core.serializers.YearIso8601Serializer
import kotlinx.datetime.Clock
import kotlinx.datetime.LocalDate
import kotlinx.datetime.Month
import kotlinx.datetime.TimeZone
import kotlinx.serialization.Serializable
@Immutable
@Serializable(with = YearIso8601Serializer::class)
public data class Year(val value: Int) : Comparable<Year> {
internal val year = value
init {
try {
atMonth(Month.JANUARY).atStartOfMonth()
} catch (e: IllegalArgumentException) {
throw IllegalArgumentException("Year value $value is out of range", e)
}
}
/**
* Same as java.time.Year.compareTo()
*/
override fun compareTo(other: Year): Int {
return value - other.value
}
/**
* Converts this year to the ISO 8601 string representation.
*/
override fun toString(): String = toIso8601String()
public companion object {
/**
* Obtains the current [Year] from the specified [clock] and [timeZone].
*
* Using this method allows the use of an alternate clock or timezone for testing.
*/
public fun now(
clock: Clock = Clock.System,
timeZone: TimeZone = TimeZone.currentSystemDefault(),
): Year = Year(LocalDate.now(clock, timeZone).year)
/**
* Checks if the year is a leap year, according to the ISO proleptic calendar system rules.
*
* This method applies the current rules for leap years across the whole time-line.
* In general, a year is a leap year if it is divisible by four without remainder.
* However, years divisible by 100, are not leap years, with the exception of years
* divisible by 400 which are.
*
* For example, 1904 was a leap year it is divisible by 4. 1900 was not a leap year
* as it is divisible by 100, however 2000 was a leap year as it is divisible by 400.
*
* The calculation is proleptic - applying the same rules into the far future and far past.
* This is historically inaccurate, but is correct for the ISO-8601 standard.
*/
public fun isLeap(year: Int): Boolean {
val prolepticYear: Long = year.toLong()
return prolepticYear and 3 == 0L && (prolepticYear % 100 != 0L || prolepticYear % 400 == 0L)
}
/**
* Obtains an instance of [Year] from a text string such as `2020`.
*
* The string format must be `yyyy`, ideally obtained from calling [Year.toString].
*
* @throws IllegalArgumentException if the text cannot be parsed or the boundaries of [Year] are exceeded.
*
* @see Year.toString
*/
public fun parseIso8601(string: String): Year {
return try {
string.fromIso8601Year()
} catch (e: IllegalArgumentException) {
throw IllegalArgumentException("Invalid Year value $string", e)
}
}
}
}
/**
* Checks if the year is a leap year, according to the ISO proleptic calendar system rules.
*
* This method applies the current rules for leap years across the whole time-line.
* In general, a year is a leap year if it is divisible by four without remainder.
* However, years divisible by 100, are not leap years, with the exception of years
* divisible by 400 which are.
*
* For example, 1904 was a leap year it is divisible by 4. 1900 was not a leap year
* as it is divisible by 100, however 2000 was a leap year as it is divisible by 400.
*
* The calculation is proleptic - applying the same rules into the far future and far past.
* This is historically inaccurate, but is correct for the ISO-8601 standard.
*/
public fun Year.isLeap(): Boolean = Year.isLeap(year)
/**
* Returns the number of days in this year.
*
* The result is 366 if this is a leap year and 365 otherwise.
*/
public fun Year.length(): Int = if (isLeap()) 366 else 365
/**
* Returns the [LocalDate] at the specified [dayOfYear] in this year.
*
* The day-of-year value 366 is only valid in a leap year
*
* @throws IllegalArgumentException if [dayOfYear] value is invalid in this year.
*/
public fun Year.atDay(dayOfYear: Int): LocalDate {
require(
dayOfYear >= 1 &&
(dayOfYear <= 365 || isLeap() && dayOfYear <= 366),
) {
"Invalid dayOfYear value '$dayOfYear' for year '$year"
}
for (month in Month.entries) {
val yearMonth = atMonth(month)
if (yearMonth.atEndOfMonth().dayOfYear >= dayOfYear) {
return yearMonth.atDay((dayOfYear - yearMonth.atStartOfMonth().dayOfYear) + 1)
}
}
throw IllegalArgumentException("Invalid dayOfYear value '$dayOfYear' for year '$year")
}
/**
* Returns the [LocalDate] at the specified [monthNumber] and [day] in this year.
*
* @throws IllegalArgumentException if either [monthNumber] is invalid or the [day] value
* is invalid in the resolved calendar [Month].
*/
public fun Year.atMonthDay(monthNumber: Int, day: Int): LocalDate = LocalDate(year, monthNumber, day)
/**
* Returns the [LocalDate] at the specified [month] and [day] in this year.
*
* @throws IllegalArgumentException if the [day] value is invalid in the resolved calendar [Month].
*/
public fun Year.atMonthDay(month: Month, day: Int): LocalDate = LocalDate(year, month, day)
/**
* Returns the [YearMonth] at the specified [month] in this year.
*/
public fun Year.atMonth(month: Month): YearMonth = YearMonth(year, month)
/**
* Returns the [YearMonth] at the specified [monthNumber] in this year.
*
* @throws IllegalArgumentException if either [monthNumber] is invalid.
*/
public fun Year.atMonth(monthNumber: Int): YearMonth = YearMonth(year, monthNumber)
/**
* Returns the number of whole years between two year values.
*/
public fun Year.yearsUntil(other: Year): Int = other.year - year
/**
* Returns a [Year] that results from adding the [value] number of years to this year.
*/
public fun Year.plusYears(value: Int): Year = Year(year + value)
/**
* Returns a [Year] that results from subtracting the [value] number of years to this year.
*/
public fun Year.minusYears(value: Int): Year = Year(year - value)
| 13 | Kotlin | 505 | 4,651 | 36de800a6c36a8f142f6432a0992e0ea4ae8a789 | 6,473 | Calendar | MIT License |
language-server/src/main/kotlin/tools/samt/ls/App.kt | samtkit | 602,288,830 | false | {"Kotlin": 612490, "Batchfile": 1420, "Shell": 1226} | package tools.samt.ls
import com.beust.jcommander.JCommander
import org.eclipse.lsp4j.launch.LSPLauncher
import java.io.InputStream
import java.io.OutputStream
import java.io.PrintWriter
import java.net.Socket
private fun startServer(inStream: InputStream, outStream: OutputStream, trace: PrintWriter? = null) {
SamtLanguageServer().use { server ->
val launcher = LSPLauncher.createServerLauncher(server, inStream, outStream, true, trace)
val client = launcher.remoteProxy
if (outStream == System.out) {
redirectLogs(client)
}
server.connect(client)
launcher.startListening().get()
}
}
fun main(args: Array<String>) {
val cliArgs = CliArgs()
val jCommander = JCommander.newBuilder()
.addObject(cliArgs)
.programName("java -jar samt-ls.jar")
.build()
jCommander.parse(*args)
if (cliArgs.help) {
jCommander.usage()
return
}
cliArgs.clientPort?.also { port ->
Socket(cliArgs.clientHost, port).use {
println("Connecting to client at ${it.remoteSocketAddress}")
startServer(
it.inputStream,
it.outputStream,
if (cliArgs.isTracing) PrintWriter(System.out) else null
)
}
return
}
if (cliArgs.isStdio) {
startServer(System.`in`, System.out)
return
}
jCommander.usage()
}
| 0 | Kotlin | 0 | 8 | 58f179de53ebb92da8e02cac021bb691b6447448 | 1,466 | core | MIT License |
code/readonly.kt | linux-china | 257,670,455 | true | {"HTML": 37482, "Cirru": 12092, "Kotlin": 10166, "TypeScript": 9957, "CSS": 2476, "CoffeeScript": 591} | //use val for readonly
data class Foo2(val bar: Double, val bas: Double)
fun main11() {
val foo2 = Foo2(1.0, 2.0)
foo2.bar = 2.0 //illegal
} | 0 | HTML | 3 | 8 | 9521b96e50253a090c47ba00c0ddaa67e0ac173c | 149 | kotlin-is-like-typescript | MIT License |
app/src/androidTest/java/com/javalon/xpensewhiz/data/local/TransactionDaoTest.kt | ezechuka | 472,029,227 | false | {"Kotlin": 333980} | package com.business.money_minder.data.local
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.room.Room
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import app.cash.turbine.test
import com.google.common.truth.Truth.assertThat
import com.business.money_minder.data.local.entity.AccountDto
import com.business.money_minder.data.local.entity.TransactionDto
import com.business.money_minder.presentation.home_screen.Account
import com.business.money_minder.presentation.home_screen.ExpenseCategory
import com.business.money_minder.presentation.home_screen.TransactionType
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
@ExperimentalCoroutinesApi
@RunWith(AndroidJUnit4::class)
class TransactionDaoTest {
@get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()
lateinit var transactionDatabase: TransactionDatabase
lateinit var transactionDao: TransactionDao
lateinit var newTrx: MutableList<TransactionDto>
lateinit var accounts: List<AccountDto>
lateinit var date: Date
lateinit var dateOfEntry: String
@Before
fun setup() {
transactionDatabase = Room.inMemoryDatabaseBuilder(
InstrumentationRegistry.getInstrumentation().targetContext,
TransactionDatabase::class.java
).allowMainThreadQueries()
.build()
transactionDao = transactionDatabase.transactionDao
newTrx = mutableListOf()
for (i in 1..2) {
date = Calendar.getInstance().time
dateOfEntry = SimpleDateFormat("yyyy-MM-dd").format(date)
newTrx.add(
TransactionDto(
date = date,
dateOfEntry = dateOfEntry,
amount = 500.0,
account = "Cash",
category = ExpenseCategory.FOOD_DRINK.title,
transactionType = "expense",
title = "Lunch snack"
)
)
}
// refresh time
date = Calendar.getInstance().time
dateOfEntry = SimpleDateFormat("yyyy-MM-dd").format(date)
newTrx.add(
TransactionDto(
date = date,
dateOfEntry = dateOfEntry,
amount = 500.0,
account = "Cash",
category = ExpenseCategory.FOOD_DRINK.title,
transactionType = "income",
title = "Lunch snack"
)
)
accounts = listOf (
AccountDto(1, "Cash", 0.0, 0.0, 0.0),
AccountDto(2, "Card", 0.0, 0.0, 0.0),
AccountDto(3, "Bank", 0.0, 0.0, 0.0)
)
}
@After
fun teardown() {
transactionDatabase.close()
}
@Test
fun `insert transaction adds a new record to the transaction table`() = runBlocking {
transactionDao.insertTransaction(newTrx[0])
transactionDao.getAllTransaction().test {
val trx = awaitItem()
assertThat(trx.size).isEqualTo(1)
}
}
@Test
fun `insert account adds a new record to the account table`() = runBlocking {
transactionDao.insertAccounts(accounts)
transactionDao.getAccounts().test {
val allAccounts = awaitItem()
assertThat(allAccounts.size).isEqualTo(3)
}
}
@Test
fun `retrieving daily transaction record returns only transactions for current day`() =
runBlocking {
transactionDao.insertTransaction(transaction = newTrx[0])
transactionDao.insertTransaction(transaction = newTrx[1])
transactionDao.getDailyTransaction("2022/04/23").test {
val trx = awaitItem()
assertThat(trx.size).isEqualTo(1)
}
}
@Test
fun `retrieving account record by account type returns only the specific account`() =
runBlocking {
transactionDao.insertAccounts(accounts)
transactionDao.getAccount(Account.CASH.title).test {
val account = awaitItem()
assertThat(account.accountType).isEqualTo(Account.CASH.title)
}
}
@Test
fun `retrieiving transaction record by transaction type returns only the specific transaction`() =
runBlocking {
transactionDao.insertTransaction(newTrx[0])
transactionDao.insertTransaction(newTrx[1])
transactionDao.insertTransaction(newTrx[2])
transactionDao.getTransactionByType(TransactionType.EXPENSE.title).test {
val trx = awaitItem()
assertThat(trx.size).isEqualTo(2)
}
}
@Test
fun `retrieving transactions by account type returns only transactions performed on the account`() =
runBlocking {
transactionDao.insertTransaction(newTrx[0])
transactionDao.getTransactionByAccount(Account.CASH.title).test {
val trx = awaitItem()
assertThat(trx[0].account).isEqualTo(Account.CASH.title)
}
}
@Test
fun `retrieving all records in account table`() = runBlocking {
transactionDao.insertAccounts(accounts)
transactionDao.getAccounts().test {
val accounts = awaitItem()
assertThat(accounts.size).isEqualTo(3)
}
}
@Test
fun `erase all transactions clears the records in transaction table`() = runBlocking {
transactionDao.insertTransaction(newTrx[0])
transactionDao.insertTransaction(newTrx[1])
transactionDao.eraseTransaction()
transactionDao.getAllTransaction().test {
val trx = awaitItem()
assertThat(trx.size).isEqualTo(0)
}
}
@Test
fun `retrieve all expense transactions performed on current day`() = runBlocking {
transactionDao.insertTransaction(newTrx[0])
transactionDao.insertTransaction(newTrx[1])
transactionDao.getCurrentDayExpTransaction().test {
val trx = awaitItem()
assertThat(trx.size).isEqualTo(2)
}
}
@Test
fun `retrieve all expense transactions performed within 30 days`() = runBlocking {
newTrx.clear()
for (i in 1..5) {
val calendar = Calendar.getInstance()
calendar.add(Calendar.DAY_OF_YEAR, -i)
date = calendar.time
dateOfEntry = SimpleDateFormat("yyyy-MM-dd").format(date)
newTrx.add(
TransactionDto(
date = date,
dateOfEntry = dateOfEntry,
amount = 500.0,
account = "Cash",
category = ExpenseCategory.FOOD_DRINK.title,
transactionType = "expense",
title = "Lunch snack"
)
)
}
newTrx.forEach {
transactionDao.insertTransaction(it)
}
transactionDao.getWeeklyExpTransaction().test {
val trx = awaitItem()
assertThat(trx.size).isEqualTo(5)
}
}
@Test
fun `retrieve all expense transactions performed within seven days`() = runBlocking {
newTrx.clear()
for (i in 1..30) {
val calendar = Calendar.getInstance()
calendar.add(Calendar.DAY_OF_YEAR, -i)
date = calendar.time
dateOfEntry = SimpleDateFormat("yyyy-MM-dd").format(date)
newTrx.add(
TransactionDto(
date = date,
dateOfEntry = dateOfEntry,
amount = 500.0,
account = "Cash",
category = ExpenseCategory.FOOD_DRINK.title,
transactionType = "expense",
title = "Lunch snack"
)
)
}
newTrx.forEach {
transactionDao.insertTransaction(it)
}
transactionDao.getWeeklyExpTransaction().test {
val trx = awaitItem()
assertThat(trx.size).isEqualTo(30)
}
}
@Test
fun `retrieve all transactions performed three days ago`() = runBlocking {
newTrx.clear()
for (i in 1..4) {
val calendar = Calendar.getInstance()
calendar.add(Calendar.DAY_OF_YEAR, -i)
date = calendar.time
dateOfEntry = SimpleDateFormat("yyyy-MM-dd").format(date)
newTrx.add(
TransactionDto(
date = date,
dateOfEntry = dateOfEntry,
amount = 500.0,
account = "Cash",
category = ExpenseCategory.FOOD_DRINK.title,
transactionType = "income",
title = "salary"
)
)
}
newTrx.forEach {
transactionDao.insertTransaction(it)
}
transactionDao.get3DayTransaction(TransactionType.INCOME.title).test {
val trx = awaitItem()
assertThat(trx.size).isEqualTo(3)
}
}
@Test
fun `retrieve all transactions performed seven days ago`() = runBlocking {
newTrx.clear()
for (i in 1..8) {
val calendar = Calendar.getInstance()
calendar.add(Calendar.DAY_OF_YEAR, -i)
date = calendar.time
dateOfEntry = SimpleDateFormat("yyyy-MM-dd").format(date)
newTrx.add(
TransactionDto(
date = date,
dateOfEntry = dateOfEntry,
amount = 500.0,
account = "Cash",
category = ExpenseCategory.FOOD_DRINK.title,
transactionType = "income",
title = "salary"
)
)
}
newTrx.forEach {
transactionDao.insertTransaction(it)
}
transactionDao.get7DayTransaction(TransactionType.INCOME.title).test {
val trx = awaitItem()
assertThat(trx.size).isEqualTo(7)
}
}
@Test
fun `retrieve all transactions performed fourteen days ago`() = runBlocking {
newTrx.clear()
for (i in 1..15) {
val calendar = Calendar.getInstance()
calendar.add(Calendar.DAY_OF_YEAR, -i)
date = calendar.time
dateOfEntry = SimpleDateFormat("yyyy-MM-dd").format(date)
newTrx.add(
TransactionDto(
date = date,
dateOfEntry = dateOfEntry,
amount = 500.0,
account = "Cash",
category = ExpenseCategory.FOOD_DRINK.title,
transactionType = "income",
title = "salary"
)
)
}
newTrx.forEach {
transactionDao.insertTransaction(it)
}
transactionDao.get3DayTransaction(TransactionType.INCOME.title).test {
val trx = awaitItem()
assertThat(trx.size).isEqualTo(14)
}
}
} | 1 | Kotlin | 5 | 52 | 7876f00908cca4f8444ab8b4460f1e7edb4cfa1a | 11,439 | xpense-whiz | MIT License |
src/main/kotlin/com/wb/support/ThreadHandler.kt | wangboy | 86,023,627 | false | null | package com.wb.support
import com.google.common.base.Stopwatch
import com.wb.interfaces.IThreadCase
import java.util.concurrent.TimeUnit
/**
* Created by wangbo on 2017/3/28.
*/
class ThreadHandler(
val member: IThreadCase
) : Thread() {
var running: Boolean = false
var watch: Stopwatch = Stopwatch.createUnstarted()
fun startUp() {
if (running) return
running = true
start()
}
fun cleanUp() {
if (!running) return
running = false
}
override fun run() {
member.caseStart()
while (true) {
try {
watch.reset()
watch.start()
member.caseRunOnce()
watch.stop()
var timeRunning = watch.elapsed(TimeUnit.MILLISECONDS)
var interval = member.interval()
if (timeRunning < interval) {
Thread.sleep(interval - timeRunning)
}
} catch (t: Throwable) {
t.printStackTrace()
} finally {
watch.reset()
}
if (!running) break
}
member.caseStop()
}
} | 0 | Kotlin | 0 | 0 | 01d2a762066b2aca689f3754ecbeb020a5602673 | 1,199 | server-core-kotlin | Apache License 2.0 |
identer/src/main/kotlin/no/nav/helse/sparkel/identer/db/IdentifikatorDao.kt | navikt | 341,650,641 | false | null | package no.nav.helse.sparkel.identer.db
import java.time.LocalDateTime
import javax.sql.DataSource
import kotliquery.Session
import kotliquery.queryOf
import kotliquery.sessionOf
import no.nav.helse.sparkel.identer.AktørV2
import no.nav.helse.sparkel.identer.Identifikator
import no.nav.helse.sparkel.identer.Type
import org.intellij.lang.annotations.Language
import org.slf4j.LoggerFactory
class IdentifikatorDao(
private val dataSource: DataSource
) {
private val sikkerlogg = LoggerFactory.getLogger("tjenestekall")
fun lagreAktør(aktorV2: AktørV2) = sessionOf(dataSource).use { session ->
// Vi kan spørre på idnummer uten å ta hensyn til type ettersom DNR/FNR er 11 siffer mens aktørid er 13, slik
// at de vil aldri matche mot hverandre.
val idnumre =
aktorV2.identifikatorer.map { it.idnummer }.joinToString(separator = "','", prefix = "'", postfix = "'")
@Language("PostgreSQL")
val queryPersonKeyExists =
"SELECT 1 FROM identifikator WHERE person_key = ?"
@Language("PostgreSQL")
val queryPersonKey =
"SELECT DISTINCT person_key FROM identifikator WHERE idnummer IN ($idnumre)"
@Language("PostgreSQL")
val deleteSQL =
"DELETE FROM identifikator WHERE person_key = ?"
@Language("PostgreSQL")
val insertSQL =
"INSERT INTO identifikator (idnummer, type, gjeldende, person_key, melding_lest) values (?, ?, ?, ?, ?)"
session.transaction { tx ->
tx.run(
queryOf(queryPersonKey)
.map { it.string("person_key") }
.asList
).takeIf {
it.isNotEmpty()
}?.also { personKeys ->
personKeys.forEach {
tx.run(queryOf(deleteSQL, it).asUpdate)
}
}
tx.run(
queryOf(queryPersonKeyExists, aktorV2.key).map { it.int(1) }.asSingle
)?.also {
sikkerlogg.error("Duplikat personKey ${aktorV2.key} funnet, kan ikke persistere innholdet i meldingen")
throw RuntimeException("Duplikat personKey funnet, kan ikke persistere innholdet i meldingen")
}
val key = aktorV2.key
val meldingLest = LocalDateTime.now()
aktorV2.identifikatorer.forEach { identifikator ->
tx.run(
queryOf(
insertSQL,
identifikator.idnummer,
identifikator.type.name,
identifikator.gjeldende,
key,
meldingLest
).asUpdate
)
}
}
}
fun hentIdenterForFødselsnummer(fnr: String): AktørV2? = sessionOf(dataSource).use { session ->
val personKey = hentKeyForIdent(fnr, Type.FOLKEREGISTERIDENT) ?: return null
hentIdenter(personKey, session)
}
fun hentIdenterForAktørid(fnr: String): AktørV2? = sessionOf(dataSource).use { session ->
val personKey = hentKeyForIdent(fnr, Type.AKTORID) ?: return null
hentIdenter(personKey, session)
}
private fun hentIdenter(personKey: String, session: Session): AktørV2? {
@Language("PostgreSQL")
val query = "SELECT idnummer, type, gjeldende, melding_lest FROM identifikator where person_key = ?"
val identifikatorer = session.run(
queryOf(query, personKey).map {
Identifikator(
idnummer = it.string("idnummer"),
type = Type.valueOf(it.string("type")),
gjeldende = it.boolean("gjeldende")
)
}.asList
)
return AktørV2(identifikatorer = identifikatorer, key = personKey)
}
private fun hentKeyForIdent(ident: String, type: Type) = sessionOf(dataSource).use { session ->
@Language("PostgreSQL")
val query = "SELECT person_key FROM identifikator where type = ? AND idnummer = ?"
session.run(
queryOf(query, type.name, ident).map { it.string("person_key") }.asSingle
)
}
} | 1 | null | 1 | 2 | 4127ee4f6d528da5009699dfcc4c6af2c2b83598 | 4,216 | helse-sparkelapper | MIT License |
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/loginscreen/LoginScreenModule.kt | feelfreelinux | 97,154,881 | false | null | package io.github.feelfreelinux.wykopmobilny.ui.modules.loginscreen
import dagger.Module
import dagger.Provides
import io.github.feelfreelinux.wykopmobilny.api.scraper.ScraperApi
import io.github.feelfreelinux.wykopmobilny.api.user.LoginApi
import io.github.feelfreelinux.wykopmobilny.base.Schedulers
import io.github.feelfreelinux.wykopmobilny.ui.modules.NewNavigator
import io.github.feelfreelinux.wykopmobilny.ui.modules.NewNavigatorApi
import io.github.feelfreelinux.wykopmobilny.utils.usermanager.UserManagerApi
import io.github.feelfreelinux.wykopmobilny.utils.wykop_link_handler.WykopLinkHandler
import io.github.feelfreelinux.wykopmobilny.utils.wykop_link_handler.WykopLinkHandlerApi
@Module
class LoginScreenModule {
@Provides
fun providesLoginScreenPresenter(schedulers: Schedulers, userManager: UserManagerApi, loginApi: LoginApi, scraperApi: ScraperApi) =
LoginScreenPresenter(schedulers, userManager, scraperApi, loginApi)
@Provides
fun provideNavigator(activity: LoginScreenActivity): NewNavigatorApi = NewNavigator(activity)
@Provides
fun provideLinkHandler(activity: LoginScreenActivity, navigator: NewNavigatorApi): WykopLinkHandlerApi = WykopLinkHandler(activity, navigator)
} | 47 | Kotlin | 51 | 166 | ec6365b9570818a7ee00c5b512f01cedead30867 | 1,230 | WykopMobilny | MIT License |
shared/src/main/kotlin/com/egm/stellio/shared/web/ExceptionHandler.kt | stellio-hub | 257,818,724 | false | null | package com.egm.stellio.shared.web
import com.egm.stellio.shared.model.*
import com.fasterxml.jackson.core.JsonParseException
import com.github.jsonldjava.core.JsonLdError
import org.slf4j.LoggerFactory
import org.springframework.core.codec.CodecException
import org.springframework.http.HttpStatus
import org.springframework.http.ProblemDetail
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.server.MethodNotAllowedException
import org.springframework.web.server.NotAcceptableStatusException
import org.springframework.web.server.UnsupportedMediaTypeStatusException
@RestControllerAdvice
class ExceptionHandler {
private val logger = LoggerFactory.getLogger(javaClass)
@ExceptionHandler
fun transformErrorResponse(throwable: Throwable): ResponseEntity<ProblemDetail> =
when (val cause = throwable.cause ?: throwable) {
is AlreadyExistsException -> generateErrorResponse(
HttpStatus.CONFLICT,
AlreadyExistsResponse(cause.message)
)
is ResourceNotFoundException -> generateErrorResponse(
HttpStatus.NOT_FOUND,
ResourceNotFoundResponse(cause.message)
)
is InvalidRequestException -> generateErrorResponse(
HttpStatus.BAD_REQUEST,
InvalidRequestResponse(cause.message)
)
is BadRequestDataException -> generateErrorResponse(
HttpStatus.BAD_REQUEST,
BadRequestDataResponse(cause.message)
)
is JsonLdError -> generateErrorResponse(
HttpStatus.BAD_REQUEST,
JsonLdErrorResponse(cause.type.toString(), cause.message.orEmpty())
)
is JsonParseException, is CodecException -> generateErrorResponse(
HttpStatus.BAD_REQUEST,
JsonParseErrorResponse(cause.message ?: "There has been a problem during JSON parsing")
)
is AccessDeniedException -> generateErrorResponse(
HttpStatus.FORBIDDEN,
AccessDeniedResponse(cause.message)
)
is NotImplementedException -> generateErrorResponse(
HttpStatus.NOT_IMPLEMENTED,
NotImplementedResponse(cause.message)
)
is LdContextNotAvailableException -> generateErrorResponse(
HttpStatus.SERVICE_UNAVAILABLE,
LdContextNotAvailableResponse(cause.message)
)
is UnsupportedMediaTypeStatusException -> generateErrorResponse(
HttpStatus.UNSUPPORTED_MEDIA_TYPE,
UnsupportedMediaTypeResponse(cause.message)
)
is NotAcceptableStatusException -> generateErrorResponse(
HttpStatus.NOT_ACCEPTABLE,
NotAcceptableResponse(cause.message)
)
is MethodNotAllowedException ->
ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED).body(cause.body)
is NonexistentTenantException -> generateErrorResponse(
HttpStatus.NOT_FOUND,
NonexistentTenantResponse(cause.message)
)
else -> generateErrorResponse(
HttpStatus.INTERNAL_SERVER_ERROR,
InternalErrorResponse("$cause")
)
}
private fun generateErrorResponse(status: HttpStatus, exception: ErrorResponse): ResponseEntity<ProblemDetail> {
logger.info("Returning error ${exception.type} (${exception.detail})")
return ResponseEntity.status(status)
.body(
ProblemDetail.forStatusAndDetail(status, exception.detail).also {
it.title = exception.title
it.type = exception.type
}
)
}
}
| 38 | null | 9 | 27 | 7b9b9e05ea75ca060dfacd67ccd1198d1d4ba07c | 3,991 | stellio-context-broker | Apache License 2.0 |
lab4/src/main/kotlin/ru/b4/config/WebSecurityConfig.kt | band-of-four | 152,893,488 | false | null | package ru.b4.config
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.crypto.password.NoOpPasswordEncoder
import javax.sql.DataSource
@Configuration
@EnableWebSecurity
class WebSecurityConfig : WebSecurityConfigurerAdapter() {
@Autowired
private var dataSource: DataSource? = null
override fun configure(http: HttpSecurity) {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/js/**","/css/**", "/index*", "/auth/login", "/auth/registration", "/", "/*.ico").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/auth/login")
.defaultSuccessUrl("/graph", true)
.permitAll()
.and()
.logout().permitAll()
}
@Autowired
override fun configure(auth: AuthenticationManagerBuilder) {
auth.jdbcAuthentication()
.dataSource(dataSource)
.passwordEncoder(NoOpPasswordEncoder.getInstance())
.usersByUsernameQuery("select username, password, active from usr where username=?")
.authoritiesByUsernameQuery("select u.username, " +
"ur.roles from usr u inner join user_role ur on u.id = ur.user_id where u.username=?")
}
}
| 0 | Kotlin | 0 | 4 | f20d2c076d9281c4696ab1d33b649c721fb3b011 | 1,697 | pipchansky | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/dinesh/mynotes/activity/EditNote.kt | Dinesh2811 | 589,404,107 | false | {"Kotlin": 121705} | package com.dinesh.mynotes.activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.View
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.dinesh.mynotes.R
import com.dinesh.mynotes.app.NavigationDrawer
import com.dinesh.mynotes.room.Note
import com.dinesh.mynotes.room.NotesViewModel
import com.dinesh.mynotes.rv.RvMain
import java.time.LocalDateTime
class EditNote : NavigationDrawer() {
lateinit var v: View
private lateinit var notesViewModel: NotesViewModel
lateinit var etTitle: EditText
lateinit var etNote: EditText
private var note: Note = Note()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initializeRecyclerView()
retrieveNote()
// val editable = etNote.text as Editable
//
// val spannable = SpannableStringBuilder.valueOf(editable)
// Linkify.addLinks(spannable, Linkify.WEB_URLS)
//
// val clickableSpan = object : ClickableSpan() {
// override fun onClick(widget: View) {
// // Handle the URL click event here
// val url = (widget as EditText).text.subSequence(widget.selectionStart, widget.selectionEnd).toString()
// // Open the URL using an appropriate method (e.g., using an Intent to open a browser)
// }
// }
//
// val spans = spannable.getSpans(0, spannable.length, URLSpan::class.java)
// for (span in spans) {
// val start = spannable.getSpanStart(span)
// val end = spannable.getSpanEnd(span)
// val flags = spannable.getSpanFlags(span)
// spannable.removeSpan(span)
// spannable.setSpan(clickableSpan, start, end, flags)
// }
//
// etNote.text = spannable
// etNote.movementMethod = LinkMovementMethod.getInstance()
etTitle.addTextChangedListener {
note.title = it.toString()
}
etNote.addTextChangedListener {
note.notes = it.toString()
}
}
private fun initializeRecyclerView() {
setContentView(R.layout.activity_main)
// setNavigationDrawer()
setToolbar()
val parentLayout = findViewById<LinearLayout>(R.id.parent_layout)
v = LayoutInflater.from(this).inflate(R.layout.edit_note, parentLayout, false)
parentLayout.addView(v)
etTitle = v.findViewById(R.id.etTitle)
etNote = v.findViewById(R.id.etNote)
notesViewModel = ViewModelProvider(this)[NotesViewModel::class.java]
}
private fun retrieveNote() {
val noteId = intent.getLongExtra("NOTE_ID", -1)
if (noteId == -1L) {
return
}
note.id = intent.getLongExtra("NOTE_ID", 0)
note.dateModified = LocalDateTime.now()
notesViewModel.getNoteById(noteId).observe(this, Observer { retrievedNote ->
if (retrievedNote != null) {
note = retrievedNote
etTitle.setText(note.title)
etNote.setText(note.notes)
}
})
}
override fun onPause() {
super.onPause()
updateNote()
}
private fun updateNote() {
if ((!(etTitle.text.isNullOrEmpty())) || (!(etNote.text.isNullOrEmpty()))) {
note.id = intent.getLongExtra("NOTE_ID", 0)
note.dateModified = LocalDateTime.now()
notesViewModel.update(note)
// Toast.makeText(this, "Your note is Updated successfully", Toast.LENGTH_SHORT).show()
}
}
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
// super.onPrepareOptionsMenu(menu)
// TODO: NavigationIcon
val navigationIcon = ContextCompat.getDrawable(this, R.drawable.ic_baseline_arrow_back_24)
navigationIcon!!.setTint(ContextCompat.getColor(this, toolbarOnBackground))
toolbar.navigationIcon = navigationIcon
menu?.findItem(R.id.menuMain)?.isVisible = false
menu?.findItem(R.id.sort)?.isVisible = false
menu?.findItem(R.id.action_search)?.isVisible = false
val saveIcon = menu?.findItem(R.id.menuSave)
saveIcon!!.isVisible = true
saveIcon.setIcon(R.drawable.ic_baseline_save_24)
saveIcon.setOnMenuItemClickListener {
updateNote()
true
}
val deleteIcon = menu.findItem(R.id.menuDelete)
deleteIcon!!.isVisible = true
deleteIcon.setIcon(R.drawable.ic_baseline_delete_24)
deleteIcon.setOnMenuItemClickListener {
notesViewModel.delete(note)
Toast.makeText(this, "Your note was deleted successfully", Toast.LENGTH_SHORT).show()
val intent = Intent(this@EditNote, RvMain::class.java)
startActivity(intent)
// finish()
// rvMain.deleteNote()
// rvMain.rvAdapter.notifyDataSetChanged()
true
}
return true
}
}
| 0 | Kotlin | 0 | 1 | aaeda7c26db0cde6159fe732057d9efeb20c03fa | 5,244 | MyNotes | Apache License 2.0 |
reaktive/src/commonMain/kotlin/com/badoo/reaktive/disposable/CompositeDisposable.kt | badoo | 174,194,386 | false | null | package com.badoo.reaktive.disposable
/**
* Thread-safe [Disposable] collection
*/
@Suppress("EmptyDefaultConstructor")
expect open class CompositeDisposable() : Disposable {
/**
* Atomically disposes the collection and all its [Disposable]s.
* All future [Disposable]s will be immediately disposed.
*/
override fun dispose()
/**
* Atomically either adds the specified [Disposable] or disposes it if container is already disposed
*
* @param disposable the [Disposable] to add
* @return true if [Disposable] was added to the collection, false otherwise
*/
fun add(disposable: Disposable): Boolean
/**
* Atomically removes the specified [Disposable] from the collection.
*
* @param disposable the [Disposable] to remove
* @param dispose if true then the [Disposable] will be disposed if removed, default value is false
* @return true if [Disposable] was removed, false otherwise
*/
fun remove(disposable: Disposable, dispose: Boolean = false): Boolean
/**
* Atomically clears all the [Disposable]s
*
* @param dispose if true then removed [Disposable]s will be disposed, default value is true
*/
fun clear(dispose: Boolean = true)
/**
* Atomically removes already disposed [Disposable]s
*/
fun purge()
}
| 8 | null | 57 | 956 | c712c70be2493956e7057f0f30199994571b3670 | 1,349 | Reaktive | Apache License 2.0 |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/s3outposts/RulePropertyDsl.kt | F43nd1r | 643,016,506 | false | null | package com.faendir.awscdkkt.generated.services.s3outposts
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.s3outposts.CfnBucket
@Generated
public fun buildRuleProperty(initializer: @AwsCdkDsl CfnBucket.RuleProperty.Builder.() -> Unit):
CfnBucket.RuleProperty = CfnBucket.RuleProperty.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 0 | a1cf8fbfdfef9550b3936de2f864543edb76348b | 411 | aws-cdk-kt | Apache License 2.0 |
src/Greeting.kt | juanicastellan0 | 187,558,900 | false | null | import java.util.*
/**...*/
fun main(args: Array<String>){
println("Hiiiiii")
println(plus(1, 2))
val scan = Scanner(System.`in`)
println("Write two numbers")
println("Number one: ")
val numberOne = scan.nextInt()
println("Number two: ")
val numberTwo = scan.nextInt()
greaterThan(numberOne, numberTwo)
}
fun plus(a : Int, b : Int) = a + b
fun greaterThan(a : Int, b : Int) = if (a > b) print("$a is greater than $b") else print("$a is less than $b") | 0 | Kotlin | 0 | 0 | a3edf06437387098a7c84bc8a51fc04561e3cb70 | 491 | KotlinProgramming | MIT License |
feature/details/src/main/java/dev/enesky/feature/details/DetailsViewModel.kt | enesky | 708,119,546 | false | {"Kotlin": 333239, "Shell": 4890} | package dev.enesky.feature.details
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.cachedIn
import dev.enesky.core.common.delegate.Event
import dev.enesky.core.common.delegate.EventDelegate
import dev.enesky.core.common.delegate.UiState
import dev.enesky.core.common.delegate.UiStateDelegate
import dev.enesky.core.common.result.Result
import dev.enesky.core.common.result.asResult
import dev.enesky.core.domain.usecase.AnimeCharactersUseCase
import dev.enesky.core.domain.usecase.AnimeEpisodesUseCase
import dev.enesky.core.domain.usecase.AnimeRecommendationsUseCase
import dev.enesky.core.domain.usecase.DetailedAnimeUseCase
import dev.enesky.feature.details.helpers.DetailsEvents
import dev.enesky.feature.details.helpers.DetailsUiState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
/**
* Created by <NAME> on 11/11/2023
*/
class DetailsViewModel(
val detailedAnimeUseCase: DetailedAnimeUseCase,
val animeCharactersUseCase: AnimeCharactersUseCase,
val animeRecommendationsUseCase: AnimeRecommendationsUseCase,
val animeEpisodesUseCase: AnimeEpisodesUseCase,
) : ViewModel(),
UiState<DetailsUiState> by UiStateDelegate(initialState = { DetailsUiState() }),
Event<DetailsEvents> by EventDelegate() {
fun getThemAll(animeId: Int) {
getDetailedAnime(animeId)
getAnimeCharacters(animeId)
getAnimeEpisodes(animeId)
getAnimeRecommendations(animeId)
}
private fun getDetailedAnime(animeId: Int) {
viewModelScope.launch(Dispatchers.IO) {
detailedAnimeUseCase(animeId = animeId)
.asResult()
.onEach { resource ->
updateUiState {
when (resource) {
is Result.Loading -> copy(loading = true)
is Result.Success -> copy(
loading = false,
detailedAnime = resource.data,
)
is Result.Error -> copy(
loading = false,
detailedAnime = null,
errorMessage = resource.exception?.message,
)
}
}
}.launchIn(this)
}
}
private fun getAnimeCharacters(animeId: Int) {
viewModelScope.launch(Dispatchers.IO) {
animeCharactersUseCase(animeId = animeId)
.asResult()
.onEach { resource ->
updateUiState {
when (resource) {
is Result.Loading -> copy(loading = true)
is Result.Success -> copy(
loading = false,
characters = resource.data,
)
is Result.Error -> copy(
loading = false,
characters = null,
errorMessage = resource.exception?.message,
)
}
}
}.launchIn(this)
}
}
private fun getAnimeEpisodes(animeId: Int) {
viewModelScope.launch(Dispatchers.IO) {
val popularAnimesFlow = animeEpisodesUseCase(animeId)
.distinctUntilChanged()
.cachedIn(viewModelScope)
updateUiState {
copy(
loading = false,
episodes = popularAnimesFlow,
)
}
}
}
private fun getAnimeRecommendations(animeId: Int) {
viewModelScope.launch(Dispatchers.IO) {
animeRecommendationsUseCase(animeId = animeId)
.asResult()
.onEach { resource ->
updateUiState {
when (resource) {
is Result.Loading -> copy(loading = true)
is Result.Success -> copy(
loading = false,
recommendations = resource.data,
)
is Result.Error -> copy(
loading = false,
recommendations = null,
errorMessage = resource.exception?.message,
)
}
}
}.launchIn(this)
}
}
}
| 26 | Kotlin | 0 | 7 | f306fce0e2df7147c5fe6080aea4452a51baea18 | 4,834 | Doodle | Apache License 2.0 |
androidApp/src/main/java/com/prof18/moneyflow/features/settings/SettingsViewModel.kt | prof18 | 290,316,981 | false | null | package com.prof18.moneyflow.features.settings
import android.net.Uri
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import com.prof18.moneyflow.presentation.settings.SettingsUseCase
import com.prof18.moneyflow.utils.DatabaseImportExport
import kotlinx.coroutines.flow.StateFlow
class SettingsViewModel(
private val databaseImportExport: DatabaseImportExport,
private val settingsUseCase: SettingsUseCase
) : ViewModel() {
var biometricState: Boolean by mutableStateOf(false)
private set
val hideSensitiveDataState: StateFlow<Boolean> = settingsUseCase.sensitiveDataVisibilityState
init {
biometricState = settingsUseCase.isBiometricEnabled()
}
fun performBackup(uri: Uri) {
databaseImportExport.exportToMemory(uri)
}
fun performRestore(uri: Uri) {
databaseImportExport.importFromMemory(uri)
}
fun updateBiometricState(enabled: Boolean) {
settingsUseCase.toggleBiometricStatus(enabled)
biometricState = enabled
}
fun updateHideSensitiveDataState(enabled: Boolean) {
settingsUseCase.toggleHideSensitiveData(enabled)
}
} | 0 | Kotlin | 20 | 157 | 4bba29b0749c27efd2611a54a215dfce928eb70b | 1,259 | MoneyFlow | Apache License 2.0 |
app/src/main/java/com/example/zibook/TocDocumentHandler.kt | flgsercan | 609,108,096 | false | {"Kotlin": 151068} | package com.example.zibook
import com.example.zibook.feature_book.domain.model.EpubManifestModel
import com.example.zibook.EpubConstants.EPUB_MAJOR_VERSION_3
import org.w3c.dom.Document
import java.util.zip.ZipEntry
import javax.xml.parsers.DocumentBuilder
internal class TocDocumentHandler {
private val documentBuilder: DocumentBuilder by lazy { ParserModuleProvider.documentBuilder }
fun createTocDocument(
mainOpfDocument: Document?,
epubEntries: List<ZipEntry>,
epubManifestModel: EpubManifestModel,
zipFile: Map<String, Pair<ZipEntry, ByteArray>>,
epubSpecMajorVersion: Int?
): Document? {
val tocLocation = getTocLocation(epubSpecMajorVersion, epubManifestModel, mainOpfDocument)
val tocFullPath = getTocFullPath(epubEntries, tocLocation)
return tocLocation?.let {
documentBuilder.parse(zipFile[tocFullPath]!!.second.inputStream())
}
}
fun getTocFullFilePath(
mainOpfDocument: Document?,
epubEntries: List<ZipEntry>,
epubManifestModel: EpubManifestModel,
epubSpecMajorVersion: Int?
): String? {
val tocLocation = getTocLocation(epubSpecMajorVersion, epubManifestModel, mainOpfDocument)
return getTocFullPath(epubEntries, tocLocation)
}
private fun getTocLocation(
epubSpecMajorVersion: Int?,
epubManifestModel: EpubManifestModel,
mainOpfDocument: Document?
): String? {
return if (epubSpecMajorVersion == EPUB_MAJOR_VERSION_3) {
Epub3TocLocationFinder().findNcxLocation(epubManifestModel)
} else {
Epub2TocLocationFinder().findNcxLocation(mainOpfDocument, epubManifestModel)
}
}
private fun getTocFullPath(entries: List<ZipEntry>, tocLocation: String?): String? {
return entries
.filter {
tocLocation?.let { toc ->
it.name.endsWith(toc)
} ?: false
}
.map { it.name }
.firstOrNull()
}
} | 0 | Kotlin | 0 | 0 | 33d264760f07dd189ab4ef70117030bfe8ef0be0 | 2,063 | EbookProject | MIT License |
src/main/kotlin/nexos/intellij/reqif/NewFile.kt | nexoscp | 295,518,192 | false | null | package nexos.intellij.reqif
import com.intellij.ide.actions.CreateFileAction
import com.intellij.openapi.application.WriteAction.compute
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import java.util.*
import java.util.UUID.randomUUID
import javax.xml.datatype.DatatypeFactory
import javax.xml.datatype.XMLGregorianCalendar
class NewFile : CreateFileAction(ReqIF.NAME, "Create ${ReqIF.NAME} File", null) {
private val dataTypes by lazy { DatatypeFactory.newInstance() }
override fun getDefaultExtension() = ReqIF.DefaultExtension
override fun create(newName: String, directory: PsiDirectory?): Array<PsiElement> {
val mkdirs = MkDirs(newName, directory!!)
return arrayOf(compute<PsiFile, RuntimeException> {
createFile(mkdirs.directory.createFile(getFileName(mkdirs.newName)), newName)
})
}
private fun now(): XMLGregorianCalendar {
val c = GregorianCalendar()
c.time = Date()
return dataTypes.newXMLGregorianCalendar(c)
}
private fun createFile(file: PsiFile, name: String):PsiFile {
file.virtualFile.getOutputStream(this).use {
it.write(
"""
<REQ-IF xmlns="http://www.omg.org/spec/ReqIF/20110401/reqif.xsd">
<THE-HEADER>
<REQ-IF-HEADER IDENTIFIER="${randomUUID()}">
<CREATION-TIME>${now().toXMLFormat()}</CREATION-TIME>
<REQ-IF-TOOL-ID>IntelliJReqIF</REQ-IF-TOOL-ID>
<REQ-IF-VERSION></REQ-IF-VERSION>
<SOURCE-TOOL-ID></SOURCE-TOOL-ID>
<TITLE>${name}</TITLE>
</REQ-IF-HEADER>
</THE-HEADER>
<CORE-CONTENT>
<REQ-IF-CONTENT></REQ-IF-CONTENT>
</CORE-CONTENT>
</REQ-IF>
""".trimIndent().toByteArray())
}
return file
}
} | 0 | Kotlin | 0 | 0 | 543090fc3bdce5f69580c2bed09069587d93e367 | 2,124 | IntelliJ-ReqIF | Apache License 2.0 |
designer/testSrc/com/android/tools/idea/common/surface/SceneViewErrorsPanelTest.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 2022 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.common.surface
import com.android.tools.adtui.swing.FakeUi
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.testFramework.ApplicationRule
import com.intellij.ui.components.JBLabel
import java.awt.BorderLayout
import java.awt.Dimension
import javax.swing.JPanel
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.ClassRule
import org.junit.Test
class SceneViewErrorsPanelTest {
private lateinit var fakeUi: FakeUi
private lateinit var panelParent: JPanel
companion object {
@JvmField @ClassRule val appRule = ApplicationRule()
}
@Before
fun setUp() {
invokeAndWaitIfNeeded {
panelParent =
JPanel().apply {
layout = BorderLayout()
size = Dimension(1000, 800)
}
fakeUi = FakeUi(panelParent, 1.0, true)
fakeUi.root.validate()
}
}
@Test
fun testVisibilityIsControlledByConstructorParameter() {
var panelStyle = SceneViewErrorsPanel.Style.SOLID
val sceneViewErrorsPanel = SceneViewErrorsPanel { panelStyle }
panelParent.add(sceneViewErrorsPanel, BorderLayout.CENTER)
assertTrue(sceneViewErrorsPanel.isVisible)
panelStyle = SceneViewErrorsPanel.Style.HIDDEN
assertFalse(sceneViewErrorsPanel.isVisible)
}
@Test
fun testPanelComponents() {
val sceneViewErrorsPanel = SceneViewErrorsPanel()
panelParent.add(sceneViewErrorsPanel, BorderLayout.CENTER)
invokeAndWaitIfNeeded { fakeUi.root.validate() }
assertNotNull(fakeUi.findComponent<JBLabel> { it.text.contains("Render problem") })
}
@Test
fun testPreferredAndMinimumSizes() {
val sceneViewErrorsPanel = SceneViewErrorsPanel()
panelParent.add(sceneViewErrorsPanel, BorderLayout.CENTER)
assertEquals(35, sceneViewErrorsPanel.minimumSize.height)
assertEquals(150, sceneViewErrorsPanel.minimumSize.width)
assertEquals(35, sceneViewErrorsPanel.preferredSize.height)
assertEquals(150, sceneViewErrorsPanel.preferredSize.width)
}
}
| 5 | null | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 2,760 | android | Apache License 2.0 |
src/main/kotlin/mar_challenge2023/MinEatingSpeed.kt | yvelianyk | 405,919,452 | false | null | package mar_challenge2023
fun main() {
// val res = MinEatingSpeed().minEatingSpeed(intArrayOf(3,6,7,11), 8)
val res = MinEatingSpeed().minEatingSpeed(intArrayOf(30,11,23,4,20), 6)
println(res)
}
class MinEatingSpeed {
fun minEatingSpeed(piles: IntArray, h: Int): Int {
var left = 1
var right = piles.maxOrNull()!!
while (left < right) {
val mid = left + (right - left) / 2
val hoursToEat = piles.sumOf { (it - 1) / mid + 1 }
if (hoursToEat > h) left = mid + 1 else right = mid
}
return left
}
} | 0 | Kotlin | 0 | 0 | e21ef12ed8ef573a50deb8235854a4511f004b4c | 592 | leetcode-kotlin | MIT License |
app/src/main/java/com/valmiraguiar/wefit/di/MainModule.kt | valmiraguiar | 538,635,080 | false | {"Kotlin": 30416, "Java": 216} | package com.valmiraguiar.wefit.di
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.valmiraguiar.wefit.data.database.GitRepoDatabase
import com.valmiraguiar.wefit.data.repository.GitRepoRepository
import com.valmiraguiar.wefit.data.repository.GitRepoRepositoryImpl
import com.valmiraguiar.wefit.data.service.GitService
import com.valmiraguiar.wefit.domain.usecase.ListGitRepoUseCase
import com.valmiraguiar.wefit.presentation.favorite.FavoriteViewModel
import com.valmiraguiar.wefit.presentation.githubrepo.GitRepoListViewModel
import kotlinx.coroutines.Dispatchers
import org.koin.android.ext.koin.androidContext
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.core.context.loadKoinModules
import org.koin.dsl.bind
import org.koin.dsl.module
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object MainModule {
private const val BASE_URL = "https://api.github.com/users/"
fun load() {
loadKoinModules(
networkModule() +
dataModule() +
daoModule() +
useCaseModule() +
viewModelModule()
)
}
private fun networkModule() = module {
fun gsonProvider() = GsonBuilder().create()
single {
createService<GitService>(BASE_URL, gsonProvider())
}
}
private fun dataModule() = module {
single<GitRepoRepository> {
GitRepoRepositoryImpl(get(), get(), Dispatchers.IO)
}.bind()
}
private fun useCaseModule() = module {
factory {
ListGitRepoUseCase(get())
}
}
private fun daoModule() = module {
single { GitRepoDatabase.getInstance(androidContext()).gitRepoDAO }
}
private fun viewModelModule() = module {
viewModel {
GitRepoListViewModel(get())
}
viewModel {
FavoriteViewModel(get())
}
}
private inline fun <reified T> createService(
baseUrl: String,
gson: Gson
): T {
return Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
.create(T::class.java)
}
} | 0 | Kotlin | 0 | 0 | 521048d9ad8537d9c0099a56c89830efc11bc0ce | 2,271 | wefit-challenge | Apache License 2.0 |
app/src/main/java/com/motondon/driveapidemoapp3/conflict/ConflictResolver.kt | JoaoMotondon | 139,527,425 | false | {"Kotlin": 131180} | package com.motondon.driveapidemoapp3.conflict
import android.content.Context
import android.content.Intent
import android.support.v4.content.LocalBroadcastManager
import android.util.Log
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.drive.*
import com.google.android.gms.drive.events.CompletionEvent
import com.google.android.gms.tasks.Continuation
import com.google.android.gms.tasks.Task
import com.motondon.driveapidemoapp3.model.TaskModel
import java.io.OutputStreamWriter
import java.util.concurrent.ExecutorService
import com.google.android.gms.drive.ExecutionOptions
import com.google.android.gms.drive.DriveContents
import com.google.android.gms.drive.DriveFile
import com.google.android.gms.drive.Drive
/**
* ConflictResolver handles a CompletionEvent with a conflict status.
*
* It will be called by the MyDriveEventsService::onCompletion() callback when Drive detects a conflict during a sync process.
*
*/
class ConflictResolver(private val mConflictedCompletionEvent: CompletionEvent, private val mContext: Context, private val mExecutorService: ExecutorService) {
private var mDriveResourceClient: DriveResourceClient? = null
private var mDriveContents: DriveContents? = null
/**
* Execute the resolution process.
*
* It first signsIn to the Google Drive and extracts from the mConflictedCompletionEvent both local and modified TaskModel lists.
*
* Then it still uses mConflictedCompletionEvent object to open and get server TaskModel list, there is the Drive version of this list.
*
* With all these three lists, it calls TaskConflictUtil.resolveConflict(...) that handles all the conflicts and returns another list with
* the resolution (resolvedContent list).
*
* Last, it calls DriveResourceClient::commitContents() in order to commit resolvedContent list in the Drive.
*
*/
fun resolve() {
Log.d(TAG, "resolve() - Begin")
var localBaseTaskList: ArrayList<TaskModel> = arrayListOf()
var localModifiedTaskList: ArrayList<TaskModel> = arrayListOf()
var serverTaskList: ArrayList<TaskModel> = arrayListOf()
var resolvedContent: ArrayList<TaskModel> = arrayListOf()
val signInOptionsBuilder = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(Drive.SCOPE_FILE)
.requestScopes(Drive.SCOPE_APPFOLDER)
if (mConflictedCompletionEvent.accountName != null) {
signInOptionsBuilder.setAccountName(mConflictedCompletionEvent.accountName)
Log.d(TAG, "resolve() - SetAccountName")
}
val signInClient = GoogleSignIn.getClient(mContext, signInOptionsBuilder.build())
signInClient.silentSignIn()
.continueWith(mExecutorService,
Continuation<GoogleSignInAccount, Void> { signInTask ->
Log.d(TAG, "resolve() - Getting base and modified task list from ConflictedCompletion event...")
mDriveResourceClient = Drive.getDriveResourceClient(
mContext, signInTask.result)
localBaseTaskList = TaskConflictUtil.getTaskListFromInputStream(
mConflictedCompletionEvent.baseContentsInputStream)
localModifiedTaskList = TaskConflictUtil.getTaskListFromInputStream(
mConflictedCompletionEvent.modifiedContentsInputStream)
null
})
.continueWithTask(mExecutorService,
Continuation<Void, Task<DriveContents>> {
Log.d(TAG, "resolve() - Opening Drive file...")
val driveId = mConflictedCompletionEvent.driveId
mDriveResourceClient?.openFile(
driveId.asDriveFile(), DriveFile.MODE_READ_ONLY)
})
.continueWithTask(mExecutorService,
Continuation<DriveContents, Task<DriveContents>> { task ->
Log.d(TAG, "resolve() - Reopening Drive content file for write...")
mDriveContents = task.result
val serverInputStream = task.result.inputStream
serverTaskList = TaskConflictUtil.getTaskListFromInputStream(serverInputStream)
return@Continuation mDriveResourceClient?.reopenContentsForWrite(mDriveContents!!)
})
.continueWithTask(mExecutorService,
Continuation<DriveContents, Task<Void>> { task ->
val contentsForWrite = task.result
Log.d(TAG, "resolve() - Local base task list contains ${localBaseTaskList.size} task(s).")
Log.d(TAG, "resolve() - Local modified task list contains ${localModifiedTaskList.size} task(s).")
Log.d(TAG, "resolve() - Server task list contains ${serverTaskList.size} task(s).")
Log.d(TAG, "resolve() - Calling TaskConflictUtil.resolveConflict() in order to resolve any conflict...")
resolvedContent = TaskConflictUtil.resolveConflict(
localBaseTaskList, localModifiedTaskList, serverTaskList)
Log.d(TAG, "resolve() - TaskConflictUtil.resolveConflict() returned. Preparing to write the resolved list to the Drive...")
val outputStream = contentsForWrite.outputStream
OutputStreamWriter(outputStream).use { writer -> writer.write(TaskConflictUtil.formatStringFromTaskList(resolvedContent)) }
// It is not likely that resolving a conflict will result in another
// conflict, but it can happen if the file changed again while this
// conflict was resolved. Since we already implemented conflict
// resolution and we never want to miss user data, we commit here
// with execution options in conflict-aware mode (otherwise we would
// overwrite server content).
val executionOptions = ExecutionOptions.Builder()
.setNotifyOnCompletion(true)
.setConflictStrategy(
ExecutionOptions
.CONFLICT_STRATEGY_KEEP_REMOTE)
.build()
// Commit resolved contents. Note commitContents returns success when it writes the list content locally. Later, when
// the data is in fact stored in the Drive, a Completion event is fired (which is handled in the MyDriveEventsService)
Log.d(TAG, "resolve() - Committing resolved contents...")
val modifiedMetadataChangeSet = mConflictedCompletionEvent.modifiedMetadataChangeSet
return@Continuation mDriveResourceClient?.commitContents(contentsForWrite,
modifiedMetadataChangeSet, executionOptions)
})
.addOnSuccessListener({ _: Void? ->
Log.d(TAG, "resolve() - Sync process finished successfully")
mConflictedCompletionEvent.dismiss()
// Notify the UI that the list should be updated
sendResult(resolvedContent)
})
.addOnFailureListener({ e: Exception ->
// The contents cannot be reopened at this point, probably due to
// connectivity, so by snoozing the event we will get it again later.
Log.d(TAG, "resolve() - Unable to write resolved content, snoozing completion event.", e)
mConflictedCompletionEvent.snooze()
mDriveContents?.let {
mDriveResourceClient?.discardContents(it)
}
})
}
/**
* Notify the UI that the list should be updated.
*
* @param resolution Resolved TaskModel list.
*/
private fun sendResult(resolution: ArrayList<TaskModel>) {
Log.d(TAG, "sendResult()")
Intent(CONFLICT_RESOLVED).apply {
putExtra(CONFLICT_RESOLVED_DATA, resolution)
LocalBroadcastManager.getInstance(mContext).sendBroadcast(this)
}
}
companion object {
private val TAG = ConflictResolver::class.java.simpleName
const val CONFLICT_RESOLVED = "CONFLICT_RESOLVED"
const val CONFLICT_RESOLVED_DATA = "CONFLICT_RESOLVED_DATA"
}
}
| 2 | Kotlin | 0 | 2 | 193a00cf6cb5b945c6c91bc20b6290c38ab3848e | 8,658 | DriveApiDemoApp | Apache License 2.0 |
app/src/main/java/com/gzaber/keepnote/data/source/room/AppDatabase.kt | gzaber | 690,170,857 | false | {"Kotlin": 239289} | package com.gzaber.keepnote.data.source.room
import androidx.room.Database
import androidx.room.RoomDatabase
import androidx.room.TypeConverter
import androidx.room.TypeConverters
import java.util.Date
@Database(entities = [FolderEntity::class, NoteEntity::class], version = 1, exportSchema = false)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase() {
abstract fun folderDao(): FolderDao
abstract fun noteDao(): NoteDao
}
| 0 | Kotlin | 1 | 0 | 58d4e17785eedda5f0110e0f47b46405b8f47158 | 462 | KeepNote | MIT License |
src/main/kotlin/fl/social/CommandInterpreter.kt | f-lombardo | 271,391,213 | false | null | package fl.social
import java.time.LocalDateTime
typealias TimeSource = () -> LocalDateTime
object StandardTimeSource: TimeSource {
override fun invoke(): LocalDateTime = LocalDateTime.now()
}
class CommandInterpreter (val output: StringDestination, private val timeSource: TimeSource = StandardTimeSource) {
private val timeLine = mutableMapOf<User, MutableList<TimedMessage>>()
private val influencers = mutableMapOf<User, MutableList<User>>()
fun interpret(command: SocialCommand): Unit {
when(command) {
is PostingCommand -> {
val messages = timeLine.getOrPut(command.user) {
mutableListOf<TimedMessage>()
}
messages.add(command.timedMessage)
}
is ReadingCommand -> {
command.user.outputTimeline()
}
is FollowingCommand -> {
val followed = influencers.getOrPut(command.follower) {
mutableListOf<User>()
}
followed.add(command.followed)
}
is WallCommand -> {
val composedTimeLine = timeLine.getOrEmpty(command.user)
val influencersTimeLines = influencers.getOrEmpty(command.user).map {
user -> timeLine[user]?.toList() ?: emptyList()
}.flatten()
(composedTimeLine + influencersTimeLines)
.sortedByDescending { it.dateTime }
.forEach {
output("(${it.user.name}) ${it.displayMessageWithTime(timeSource)}".trimEnd())
}
}
is PrivateMessageCommand -> TODO()
}
}
private fun <T> Map<User, MutableList<T>>.getOrEmpty(user: User) = getOrDefault(user, emptyList<T>())
private fun User.outputTimeline() =
timeLine[this]?.sortedByDescending { it.dateTime }?.forEach {
output(it.displayMessageWithTime(timeSource).trimEnd())
}
}
| 0 | Kotlin | 0 | 0 | 7c41cdcf8a2f65b14c5faab4ec1c54cee8ce925f | 2,029 | social_networking_kata | Apache License 2.0 |
rxpay-api/src/main/java/com/cuieney/sdk/rxpay/alipay/AlipayWay.kt | newPersonKing | 139,582,261 | false | {"Gradle": 9, "Java Properties": 2, "Shell": 2, "Ignore List": 5, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 15, "XML": 17, "Java": 3} | package com.cuieney.sdk.rxpay.alipay
import android.annotation.SuppressLint
import android.app.Activity
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.util.Log
import com.alipay.sdk.app.PayTask
import com.cuieney.sdk.rxpay.PaymentStatus
import java.util.Observable
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.FlowableEmitter
import io.reactivex.FlowableOnSubscribe
import io.reactivex.functions.Function
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.PublishSubject
/**
* Created by cuieney on 18/08/2017.
*/
object AlipayWay {
fun payMoney(activity: Activity, orderInfo: String): Flowable<PaymentStatus> {
return Flowable.create(FlowableOnSubscribe<PayTask> { e ->
val alipay = PayTask(activity)
e.onNext(alipay)
}, BackpressureStrategy.ERROR)
.map { payTask ->
createPaymentStatus(payTask, orderInfo)
}
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
}
private fun createPaymentStatus(payTask: PayTask, orderInfo: String): PaymentStatus {
val result = payTask.payV2(orderInfo, true)
val payResult = PayResult(result)
val resultStatus = payResult.resultStatus
return if (resultStatus.equals("9000")) {
PaymentStatus(true)
} else {
Log.e("Rxpay","${payResult.resultStatus},${payResult.result}")
PaymentStatus(false)
}
}
}
| 1 | null | 1 | 1 | 39c57863fa7f798958e3f96736a757b376abbde3 | 1,591 | RxPay-master | Apache License 2.0 |
app/src/main/java/com/example/compose_tflite/plantsApi_feature/network/ApiService.kt | YadavYashvant | 702,524,655 | false | {"Kotlin": 50160} | package com.example.compose_tflite.plantsApi_feature.network
import com.example.compose_tflite.plantsApi_feature.model.Movie
import com.example.compose_tflite.plantsApi_feature.model.expTrefle.Plant
import com.example.compose_tflite.plantsApi_feature.model.expTrefle.PlantData
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
/*https://trefle.io/api/v1/plants?token=<KEY>*/
interface ApiService {
@GET("movielist.json")
/*@GET("plants?token=<KEY>")*/
suspend fun getMovies() : List<Movie>
companion object {
var apiService: ApiService? = null
fun getInstance() : ApiService {
if (apiService == null) {
apiService = Retrofit.Builder()
.baseUrl("https://howtodoandroid.com/apis/")
/*.baseUrl("https://trefle.io/api/v1/")*/
.addConverterFactory(GsonConverterFactory.create())
.build().create(ApiService::class.java)
}
return apiService!!
}
}
} | 0 | Kotlin | 1 | 1 | c21752f583a8a23fb3ec849f743adb8c6ee4c6bb | 1,073 | CropGuard | MIT License |
mage/src/main/java/mil/nga/giat/mage/location/LocationServerFetch.kt | specopdiv | 358,605,213 | true | {"Java": 645134, "Kotlin": 220311} | package mil.nga.giat.mage.location
import android.content.Context
import android.util.Log
import mil.nga.giat.mage.sdk.datastore.location.LocationHelper
import mil.nga.giat.mage.sdk.datastore.user.EventHelper
import mil.nga.giat.mage.sdk.datastore.user.User
import mil.nga.giat.mage.sdk.datastore.user.UserHelper
import mil.nga.giat.mage.sdk.exceptions.UserException
import mil.nga.giat.mage.sdk.fetch.UserServerFetch
import mil.nga.giat.mage.sdk.http.resource.LocationResource
import java.util.*
class LocationServerFetch(val context: Context) {
companion object {
private val LOG_NAME = mil.nga.giat.mage.location.LocationServerFetch::class.java.name
}
private val userHelper: UserHelper = UserHelper.getInstance(context)
private val userFetch: UserServerFetch = UserServerFetch(context)
private val locationHelper: LocationHelper = LocationHelper.getInstance(context)
private val locationResource: LocationResource = LocationResource(context)
fun fetch() {
var currentUser: User? = null
try {
currentUser = userHelper.readCurrentUser()
} catch (e: UserException) {
Log.e(LOG_NAME, "Error reading current user.", e)
}
val event = EventHelper.getInstance(context).currentEvent
try {
val locations = locationResource.getLocations(event)
for (location in locations) {
// make sure that the user exists and is persisted in the local data-store
var userId: String? = null
val userIdProperty = location.propertiesMap["userId"]
if (userIdProperty != null) {
userId = userIdProperty.value.toString()
}
if (userId != null) {
var user: User? = userHelper.read(userId)
// TODO : test the timer to make sure users are updated as needed!
val sixHoursInMilliseconds = (6 * 60 * 60 * 1000).toLong()
if (user == null || Date().after(Date(user.fetchedDate.time + sixHoursInMilliseconds))) {
// get any users that were not recognized or expired
Log.d(LOG_NAME, "User for location is null or stale, re-pulling")
userFetch.fetch(userId)
user = userHelper.read(userId)
}
location.user = user
// if there is no existing location, create one
val l = locationHelper.read(location.remoteId)
if (l == null) {
// delete old location and create new one
if (user != null) {
// don't pull your own locations
if (user != currentUser) {
userId = user.id.toString()
val newLocation = locationHelper.create(location)
locationHelper.deleteUserLocations(userId, true, newLocation.event)
}
} else {
Log.w(LOG_NAME, "A location with no user was found and discarded. User id: $userId")
}
}
}
}
} catch(e: Exception) {
Log.e(LOG_NAME, "Failed to fetch user locations from server", e)
}
}
}
| 0 | Java | 0 | 0 | bce4f8e0e051c3ca24aabca20f8dd4fc904f9205 | 3,469 | mage-android | Apache License 2.0 |
app/src/main/java/cn/edu/sdu/online/isdu/ui/fragments/me/MePostsFragment.kt | Grapedge | 161,661,122 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 3, "Proguard": 1, "JSON": 1, "Kotlin": 83, "XML": 180, "Java": 127, "HTML": 1} | package cn.edu.sdu.online.isdu.ui.fragments.me
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cn.edu.sdu.online.isdu.R
import cn.edu.sdu.online.isdu.app.LazyLoadFragment
import cn.edu.sdu.online.isdu.bean.Post
import cn.edu.sdu.online.isdu.interfaces.PostViewable
import cn.edu.sdu.online.isdu.net.pack.ServerInfo
import cn.edu.sdu.online.isdu.net.NetworkAccess
import cn.edu.sdu.online.isdu.ui.adapter.PostItemAdapter
import cn.edu.sdu.online.isdu.util.Logger
import com.liaoinstan.springview.widget.SpringView
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException
import kotlin.collections.ArrayList
/**
****************************************************
* @author zsj
* Last Modifier: ZSJ
* Last Modify Time: 2018/7/25
*
* 个人主页我的帖子碎片
****************************************************
*/
class MePostsFragment : LazyLoadFragment(), PostViewable {
private var recyclerView: RecyclerView? = null
private var adapter: PostItemAdapter? = null
private var dataList: MutableList<Post> = ArrayList()
private var pullRefreshLayout: SpringView? = null
private var uid = -1
private var lastId = 0
private var needOffset = false // 是否需要列表位移
fun setUid(uid: Int) {
this.uid = uid
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_me_articles, container, false)
initView(view)
initRecyclerView()
initPullRefreshLayout()
return view
}
override fun onResume() {
super.onResume()
adapter?.notifyDataSetChanged()
}
override fun removeItem(item: Any?) {
var j = 0
for (i in 0 until dataList.size) {
if (dataList[i].postId == item as Int) j = i
}
dataList.removeAt(j)
adapter?.notifyDataSetChanged()
}
private fun initView(view: View) {
recyclerView = view.findViewById(R.id.recycler_view)
pullRefreshLayout = view.findViewById(R.id.pull_refresh_layout)
}
private fun initRecyclerView() {
recyclerView!!.layoutManager = LinearLayoutManager(context)
adapter = PostItemAdapter(activity!!, dataList)
recyclerView!!.adapter = adapter
}
override fun loadData() {
NetworkAccess.buildRequest(ServerInfo.getPostList(uid,
if (dataList.size > 0) dataList[dataList.size - 1].postId - 1 else 0),
object : Callback {
override fun onFailure(call: Call?, e: IOException?) {
Logger.log(e)
activity!!.runOnUiThread {
pullRefreshLayout!!.onFinishFreshAndLoad()
}
}
override fun onResponse(call: Call?, response: Response?) {
activity!!.runOnUiThread {
pullRefreshLayout!!.onFinishFreshAndLoad()
}
try {
val list = ArrayList<Post>()
val str = response?.body()?.string()
val jsonObj = JSONObject(str)
val jsonArr = JSONArray(jsonObj.getString("obj"))
for (i in 0 until jsonArr.length()) {
val obj = jsonArr.getJSONObject(i)
val post = Post()
post.postId = obj.getInt("id")
post.commentsNumbers = obj.getInt("commentNumber")
post.collectNumber = obj.getInt("collectNumber")
post.likeNumber = obj.getInt("likeNumber")
post.uid = obj.getString("uid")
post.title = obj.getString("title")
post.time = obj.getString("time").toLong()
post.content = obj.getString("info")
post.value = obj.getDouble("value")
post.tag = if (obj.has("tag")) obj.getString("tag") else ""
if (!dataList.contains(post))
list.add(post)
}
activity!!.runOnUiThread {
publishLoadData(list)
}
} catch (e: Exception) {
Logger.log(e)
}
}
})
}
fun removeAllItems() {
dataList.clear()
adapter?.notifyDataSetChanged()
}
private fun publishLoadData(list: List<Post>) {
if (list.isNotEmpty()) {
dataList.addAll(list)
adapter!!.notifyDataSetChanged()
if (needOffset)
recyclerView!!.smoothScrollBy(0, 100)
}
}
/**
* 初始化下拉刷新
*/
private fun initPullRefreshLayout() {
// 下拉刷新监听器
pullRefreshLayout!!.setListener(object : SpringView.OnFreshListener {
override fun onLoadmore() {
needOffset = true
loadData()
}
override fun onRefresh() {
dataList.clear()
needOffset = false
loadData()
}
})
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt("uid", uid)
}
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
if (savedInstanceState?.getInt("uid") != null)
uid = savedInstanceState.getInt("uid")
}
companion object {
const val TAG = "MeArticleFragment"
}
} | 0 | Kotlin | 0 | 1 | 580e1cce5f4837644e8366f5e141d2e0f4fbcaf5 | 6,215 | isdu-app | Apache License 2.0 |
styringsinfo/src/test/kotlin/db/migration/V32BehandlingsstatusVedtaksperiodeGodkjentTest.kt | navikt | 342,325,871 | false | {"Kotlin": 692299, "Dockerfile": 168} | package db.migration
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import no.nav.helse.spre.styringsinfo.AbstractDatabaseTest.Companion.dataSource
import no.nav.helse.spre.styringsinfo.teamsak.behandling.Versjon
import no.nav.helse.spre.styringsinfo.teamsak.hendelse.VedtaksperiodeGodkjent
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import java.time.LocalDateTime
import java.util.*
internal class V32BehandlingsstatusVedtaksperiodeGodkjentTest: BehandlingshendelseJsonMigreringTest(
migrering = V32__behandlingsstatus_vedtaksperiode_godkjent(),
dataSource = dataSource
) {
@Test
fun `skal skrive om alle vedtaksperiode_godkjent-hendelser sin behandlingsstatus fra AVSLUTTET til GODKJENT`() {
val hendelseId = UUID.randomUUID()
val korrigertHendelse = leggTilBehandlingshendelse(
UUID.randomUUID(), hendelseId, true, Versjon.of("0.1.0"), false, data = {
it.put("behandlingstatus", "AVSLUTTET")
},
hendelse = VedtaksperiodeGodkjent(
id = hendelseId,
opprettet = LocalDateTime.now(),
data = jacksonObjectMapper().createObjectNode() as JsonNode,
vedtaksperiodeId = UUID.randomUUID(),
saksbehandlerEnhet = "nei",
beslutterEnhet = "nope",
automatiskBehandling = true
)
)
migrer()
assertKorrigert(korrigertHendelse) { _, ny ->
Assertions.assertEquals("GODKJENT", ny.path("behandlingstatus").asText())
}
}
} | 0 | Kotlin | 2 | 0 | 435c80a2006ad7b243544882dbd59b6392b8f2f6 | 1,655 | helse-spre | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.