path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
756M
| is_fork
bool 2
classes | languages_distribution
stringlengths 12
2.44k
⌀ | content
stringlengths 6
6.29M
| issues
float64 0
10k
⌀ | main_language
stringclasses 128
values | forks
int64 0
54.2k
| stars
int64 0
157k
| commit_sha
stringlengths 40
40
| size
int64 6
6.29M
| name
stringlengths 1
100
| license
stringclasses 104
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/kotlin/io/trewartha/positional/ui/ViewModelEvent.kt | mtrewartha | 62,930,438 | false | null | package io.trewartha.positional.ui
abstract class ViewModelEvent {
var handled = false
} | 1 | Kotlin | 2 | 18 | 63f1e5813ae5351459c970f46c1c8dd77f66a8b5 | 94 | positional | MIT License |
demo-app/src/main/java/com/zero/xera/parcelable/demo/LargeData.kt | 0xera | 746,013,123 | false | {"Kotlin": 30604, "Java": 19845} | package com.zero.xera.parcelable.demo
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import java.io.Serializable
import java.util.UUID
internal interface LargeData {
val list: List<String>
}
private val genData = MutableList(50_000) {
UUID.randomUUID().toString()
}
data class SerializableLargeData(override val list: List<String>) : LargeData, Serializable {
companion object {
// 1950,84 kb
val instance = SerializableLargeData(genData)
}
}
@Parcelize
data class ParcelableLargeData(override val list: List<String>) : LargeData, Parcelable {
companion object {
// 4000,676 kb
val instance = ParcelableLargeData(genData)
}
} | 0 | Kotlin | 0 | 8 | f1be77798e430e91c07b21e181c71c6b6c544216 | 704 | parcelable | MIT License |
app/src/main/kotlin/org/mifos/mobile/cn/ui/adapter/DebtIncomeReportAdapter.kt | openMF | 133,982,000 | false | null | package org.mifos.mobile.cn.ui.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.item_debt_income_report.view.*
import org.mifos.mobile.cn.R
import org.mifos.mobile.cn.data.models.accounts.loan.CreditWorthinessFactor
import java.util.ArrayList
import javax.inject.Inject
class DebtIncomeReportAdapter @Inject constructor() : RecyclerView.Adapter<DebtIncomeReportAdapter.ViewHolder>() {
private var creditWorthinessFactors: List<CreditWorthinessFactor> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DebtIncomeReportAdapter.ViewHolder {
val view: View = LayoutInflater.from(parent.context).inflate(R.layout.item_debt_income_report,parent,false)
return ViewHolder(view);
}
override fun getItemCount(): Int {
return creditWorthinessFactors.size
}
fun setCreditWorthinessFactors(creditWorthinessFactors: List<CreditWorthinessFactor>) {
this.creditWorthinessFactors = creditWorthinessFactors
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val creditWorthinessFactor = creditWorthinessFactors[position]
holder.tvAmount.text =creditWorthinessFactor.amount.toString()
holder.tvDescription.text = creditWorthinessFactor.description
}
class ViewHolder constructor(v:View): RecyclerView.ViewHolder(v){
var tvAmount = v.tv_amount
var tvDescription = v.tv_description
}
} | 66 | Kotlin | 65 | 37 | 2dd8750cb34e62e9458469da09c3fb55a258b067 | 1,574 | mifos-mobile-cn | Apache License 2.0 |
attribouter/src/main/java/me/jfenn/attribouter/wedges/PlayStoreLinkWedge.kt | fennifith | 124,246,346 | false | null | package me.jfenn.attribouter.wedges
import android.content.Context
import android.view.View
import me.jfenn.attribouter.utils.UrlClickListener
class PlayStoreLinkWedge @JvmOverloads constructor(url: String? = null, priority: Int = 0) : LinkWedge(
id = "playStore",
name = "@string/attribouter_title_play_store",
url = url,
icon = "@drawable/attribouter_ic_play_store",
priority = priority
) {
override fun getListener(context: Context): View.OnClickListener? {
return UrlClickListener(url ?: run {
"https://play.google.com/store/apps/details?id=${context.applicationInfo.packageName}"
})
}
}
| 5 | Kotlin | 13 | 118 | bfa65610b55a1b88673a321dd3bdd9ac409cf6a0 | 671 | Attribouter | Apache License 2.0 |
app/src/main/java/com/razi/booking/BookingHistoryActivity.kt | alokrathava | 352,985,296 | false | {"Java": 67727, "Kotlin": 34757} | package com.razi.booking
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.adapters.OrderAdapter
import com.data.Order
import com.network.ApiService
import com.network.RetroClass
import com.razi.furnitar.databinding.ActivityBookingHistoryBinding
import com.utils.Config
import com.utils.toast
import kotlinx.coroutines.launch
class BookingHistoryActivity : AppCompatActivity(), OrderAdapter.OrderInterface {
companion object {
private const val TAG = "BookingActivity"
}
private lateinit var binding: ActivityBookingHistoryBinding
private val context = this
private val bookingHistoryAdapter = OrderAdapter(this)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityBookingHistoryBinding.inflate(layoutInflater)
setContentView(binding.root)
handleToolbar()
init()
getOrders()
}
/*--------------------------------- Handle Toolbar --------------------------------*/
private fun handleToolbar() {
binding.includedToolbar.title.text = "Order History"
binding.includedToolbar.backBtn.setOnClickListener { finish() }
}
private fun init() {
binding.recyclerView.adapter = bookingHistoryAdapter
}
private fun getOrders() {
lifecycleScope.launch {
try {
val apiInterface: ApiService = RetroClass.createService(ApiService::class.java)
val response = apiInterface.getOrderHistory(Config.user_id)
Log.d(TAG, "getRestaurantDetails: $response")
bookingHistoryAdapter.submitList(response.orders)
} catch (exception: Exception) {
toast(exception.message.toString())
}
}
}
override fun onClick(order: Order) {
}
} | 1 | Java | 0 | 0 | bc3377154c39207afa1a0d39ac7dcf8c7c9b6cfa | 1,949 | ARCLONE | MIT License |
src/main/kotlin/net/sportsday/routes/v1/UsersRouter.kt | Sports-day | 589,245,462 | false | {"Kotlin": 220880, "Dockerfile": 330} | package net.sportsday.routes.v1
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.plugins.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import net.sportsday.models.LogEvents
import net.sportsday.models.OmittedUser
import net.sportsday.plugins.Role
import net.sportsday.plugins.UserPrincipal
import net.sportsday.plugins.withRole
import net.sportsday.services.UsersService
import net.sportsday.utils.DataMessageResponse
import net.sportsday.utils.DataResponse
import net.sportsday.utils.MessageResponse
import net.sportsday.utils.logger.Logger
import net.sportsday.utils.respondOrInternalError
/**
* Created by testusuke on 2023/03/10
* @author testusuke
*/
fun Route.usersRouter() {
route("/users") {
/**
* Get all users
*/
get {
val users = UsersService.getAll()
call.respond(HttpStatusCode.OK, DataResponse(users.getOrDefault(listOf())))
}
withRole(Role.ADMIN) {
/**
* create user
*/
post {
val omittedUser = call.receive<OmittedUser>()
UsersService
.create(omittedUser)
.respondOrInternalError {
call.respond(
DataMessageResponse(
"created user",
it,
),
)
// Logger
Logger.commit(
"[UsersRouter] created user: ${it.name}",
LogEvents.CREATE,
call.authentication.principal<UserPrincipal>()?.microsoftAccount,
)
}
}
}
route("/{id?}") {
/**
* Get user
*/
get {
val id = call.parameters["id"]?.toIntOrNull() ?: throw BadRequestException("invalid id parameter")
UsersService
.getById(id)
.respondOrInternalError {
call.respond(HttpStatusCode.OK, DataResponse(it))
}
}
withRole(Role.ADMIN) {
/**
* update user
*/
put {
val id = call.parameters["id"]?.toIntOrNull() ?: throw BadRequestException("invalid id parameter")
val omittedUser = call.receive<OmittedUser>()
UsersService
.update(id, omittedUser)
.respondOrInternalError {
call.respond(
HttpStatusCode.OK,
DataMessageResponse(
"updated user",
it,
),
)
// Logger
Logger.commit(
"[UsersRouter] updated user: ${it.name}",
LogEvents.UPDATE,
call.authentication.principal<UserPrincipal>()?.microsoftAccount,
)
}
}
/**
* delete user
*/
delete {
val id = call.parameters["id"]?.toIntOrNull() ?: throw BadRequestException("invalid id parameter")
UsersService
.deleteById(id)
.respondOrInternalError {
call.respond(HttpStatusCode.OK, MessageResponse("deleted user"))
// Logger
Logger.commit(
"[UsersRouter] deleted user: $id",
LogEvents.DELETE,
call.authentication.principal<UserPrincipal>()?.microsoftAccount,
)
}
}
route("/microsoft-accounts") {
/**
* Get user what linked by microsoft account
*/
get {
val id = call.parameters["id"]?.toIntOrNull() ?: throw BadRequestException("invalid id parameter")
UsersService
.getLinkedMicrosoftAccount(id)
.respondOrInternalError {
call.respond(HttpStatusCode.OK, DataResponse(it))
}
}
}
}
route("/teams") {
/**
* Get all teams what user belong
*/
get {
val id = call.parameters["id"]?.toIntOrNull() ?: throw BadRequestException("invalid id parameter")
UsersService
.getTeams(id)
.respondOrInternalError {
call.respond(HttpStatusCode.OK, DataResponse(it))
}
}
}
}
}
}
| 9 | Kotlin | 0 | 0 | 368f79670b349e93c5ff03c81d8e38433672e6b7 | 5,436 | SportsDayAPI | Apache License 2.0 |
compiler/fir/raw-fir/psi2fir/testData/rawBuilder/declarations/secondaryConstructor.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // MEMBER_CLASS_FILTER: org.jetbrains.kotlin.fir.symbols.impl.FirConstructorSymbol
// BODY_RESOLVE
package util
@Target(AnnotationTarget.TYPE)
annotation class Anno(val position: String)
const val prop = "str"
abstract class AbstractClass<T>
class <caret>MyClass() : @Anno("super type call $prop") AbstractClass<@Anno("nested super type ref $prop") List<@Anno("nested nested super type ref $prop") Int>>() | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 409 | kotlin | Apache License 2.0 |
agp-7.1.0-alpha01/tools/base/build-system/gradle-core/src/test/java/com/android/build/gradle/internal/services/AsyncResourceProcessorTest.kt | jomof | 374,736,765 | false | {"Java": 35519326, "Kotlin": 22849138, "C++": 2171001, "HTML": 1377915, "Starlark": 915536, "C": 141955, "Shell": 110207, "RenderScript": 58853, "Python": 25635, "CMake": 18109, "Batchfile": 12180, "Perl": 9310, "Dockerfile": 5690, "Makefile": 4535, "CSS": 4148, "JavaScript": 3488, "PureBasic": 2359, "GLSL": 1628, "AIDL": 1117, "Prolog": 277} | /*
* Copyright (C) 2020 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.build.gradle.internal.services
import com.android.build.gradle.internal.fixtures.FakeNoOpAnalyticsService
import com.android.build.gradle.options.SyncOptions
import com.android.builder.tasks.BooleanLatch
import com.android.testutils.concurrency.OnDemandExecutorService
import com.google.common.io.Closer
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import org.junit.After
import org.junit.Test
import java.io.Closeable
import java.util.concurrent.ForkJoinPool
import java.util.concurrent.atomic.AtomicInteger
class AsyncResourceProcessorTest {
private val closer = Closer.create()
private val executor = OnDemandExecutorService()
val forkJoinPool: ForkJoinPool by lazy {
ForkJoinPool(2).also { closer.register(Closeable { it.shutdown() }) }
}
@After
fun close() {
closer.close()
}
@Test
fun smokeTest() {
val counter = AtomicInteger()
createAsyncResourceProcessor(counter).use { processor ->
processor.submit(FakeNoOpAnalyticsService()) {
it.incrementAndGet()
}
assertThat(counter.get()).isEqualTo(0)
executor.run(1)
assertThat(counter.get()).isEqualTo(1)
}
}
/** This test simulates what the verify library resources task does */
@Test
fun testCloseAwaitsExecutionCompletion() {
val counter = AtomicInteger()
// Steps for the processor to go through.
val compileSubmitted = BooleanLatch()
val awaitComplete = BooleanLatch()
val linkSubmitted = BooleanLatch()
val processorClosed = BooleanLatch()
forkJoinPool.submit {
createAsyncResourceProcessor(counter).use { processor ->
processor.submit(FakeNoOpAnalyticsService()) {
it.incrementAndGet()
}
compileSubmitted.signal()
Thread.yield()
processor.await()
awaitComplete.signal()
Thread.yield()
processor.submit(FakeNoOpAnalyticsService()) {
it.incrementAndGet()
}
linkSubmitted.signal()
Thread.yield()
}
processorClosed.signal()
Thread.yield()
}
compileSubmitted.await()
assertWithMessage("processor await should be blocked on executor running").that(
awaitComplete.isSignalled
).isFalse()
assertThat(counter.get()).isEqualTo(0)
executor.runAll()
assertThat(counter.get()).isEqualTo(1)
awaitComplete.await()
assertThat(counter.get()).isEqualTo(1)
linkSubmitted.await()
assertThat(counter.get()).isEqualTo(1)
executor.runAll()
assertThat(counter.get()).isEqualTo(2)
processorClosed.await()
assertThat(counter.get()).isEqualTo(2)
}
private fun createAsyncResourceProcessor(counter: AtomicInteger): AsyncResourceProcessor<AtomicInteger> {
return AsyncResourceProcessor(
projectName = "testProject",
owner = "testTask",
executor = executor,
service = counter,
errorFormatMode = SyncOptions.ErrorFormatMode.HUMAN_READABLE
)
}
} | 1 | Java | 1 | 0 | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | 3,990 | CppBuildCacheWorkInProgress | Apache License 2.0 |
paper/src/main/kotlin/net/prosavage/factionsx/manager/ConfigFileManager.kt | ryderbelserion | 669,875,997 | false | null | package net.prosavage.factionsx.manager
import net.prosavage.factionsx.FactionsX
import net.prosavage.factionsx.persist.IConfigFile
import net.prosavage.factionsx.persist.Message
import net.prosavage.factionsx.persist.config.*
import net.prosavage.factionsx.persist.config.gui.AccessGUIConfig
import net.prosavage.factionsx.persist.config.gui.PermsGUIConfig
import net.prosavage.factionsx.persist.config.gui.UpgradesGUIConfig
import org.bukkit.plugin.java.JavaPlugin
object ConfigFileManager {
private val plugin = JavaPlugin.getPlugin(FactionsX::class.java)
fun setup() {
register(Config)
register(EconConfig)
register(RoleConfig)
register(PermsGUIConfig)
register(AccessGUIConfig)
register(ProtectionConfig)
register(UpgradesConfig)
register(UpgradesGUIConfig)
register(MapConfig)
register(FlyConfig)
register(ScoreboardConfig)
register(Message)
}
val files = hashSetOf<IConfigFile>()
fun register(configurableFile: IConfigFile) {
files.add(configurableFile)
}
fun load() {
files.forEach { it.load(this.plugin) }
}
fun save() {
files.forEach {
// Load changes first, then save.
it.load(this.plugin)
it.save(this.plugin)
}
}
} | 0 | Kotlin | 0 | 0 | 2d3ed828660aa9b9f35ca55edbda519a11ed7756 | 1,339 | Factions | MIT License |
lib/src/test/java/com/sha/bulletin/toast/StandardToastTest.kt | ShabanKamell | 228,855,441 | false | null | package com.sha.bulletin.toast
import com.sha.bulletin.DefaultDuplicateStrategy
import org.junit.Before
import org.junit.Test
class StandardToastTest {
lateinit var options: StandardToast.Options.Builder
@Before
fun setup() {
options = StandardToast.Options.Builder()
}
@Test
fun content() {
options.content("content")
assert(options.build().content == "content")
}
@Test
fun duplicateStrategy() {
val strategy = DefaultDuplicateStrategy()
options.duplicateStrategy(strategy)
assert(options.build().duplicateStrategy == strategy)
}
} | 0 | Kotlin | 0 | 5 | 16dcc2b867ae362830b9249e84bb911af7e8a82d | 626 | Bulletin | Apache License 2.0 |
kt/godot-library/src/main/kotlin/godot/gen/godot/OpenXRInterface.kt | utopia-rise | 289,462,532 | false | {"Kotlin": 1464908, "GDScript": 492843, "C++": 484675, "C#": 10278, "C": 8523, "Shell": 8429, "Java": 2136, "CMake": 939, "Python": 75} | // THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY!
@file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier",
"UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST",
"RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT",
"RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate")
package godot
import godot.`annotation`.GodotBaseType
import godot.core.Quaternion
import godot.core.TypeManager
import godot.core.VariantArray
import godot.core.VariantType.ARRAY
import godot.core.VariantType.BOOL
import godot.core.VariantType.DOUBLE
import godot.core.VariantType.LONG
import godot.core.VariantType.NIL
import godot.core.VariantType.QUATERNION
import godot.core.VariantType.STRING
import godot.core.VariantType.VECTOR3
import godot.core.Vector3
import godot.core.memory.TransferContext
import godot.signals.Signal0
import godot.signals.signal
import godot.util.VoidPtr
import kotlin.Any
import kotlin.Boolean
import kotlin.Double
import kotlin.Float
import kotlin.Int
import kotlin.Long
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
import kotlin.jvm.JvmInline
@GodotBaseType
public open class OpenXRInterface : XRInterface() {
public val sessionBegun: Signal0 by signal()
public val sessionStopping: Signal0 by signal()
public val sessionFocussed: Signal0 by signal()
public val sessionVisible: Signal0 by signal()
public val poseRecentered: Signal0 by signal()
public var displayRefreshRate: Float
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getDisplayRefreshRatePtr, DOUBLE)
return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat()
}
set(`value`) {
TransferContext.writeArguments(DOUBLE to value.toDouble())
TransferContext.callMethod(rawPtr, MethodBindings.setDisplayRefreshRatePtr, NIL)
}
public var renderTargetSizeMultiplier: Double
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getRenderTargetSizeMultiplierPtr, DOUBLE)
return (TransferContext.readReturnValue(DOUBLE, false) as Double)
}
set(`value`) {
TransferContext.writeArguments(DOUBLE to value)
TransferContext.callMethod(rawPtr, MethodBindings.setRenderTargetSizeMultiplierPtr, NIL)
}
public var foveationLevel: Int
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getFoveationLevelPtr, LONG)
return (TransferContext.readReturnValue(LONG, false) as Long).toInt()
}
set(`value`) {
TransferContext.writeArguments(LONG to value.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.setFoveationLevelPtr, NIL)
}
public var foveationDynamic: Boolean
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getFoveationDynamicPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
set(`value`) {
TransferContext.writeArguments(BOOL to value)
TransferContext.callMethod(rawPtr, MethodBindings.setFoveationDynamicPtr, NIL)
}
public override fun new(scriptIndex: Int): Boolean {
callConstructor(ENGINECLASS_OPENXRINTERFACE, scriptIndex)
return true
}
public fun isFoveationSupported(): Boolean {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.isFoveationSupportedPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
public fun isActionSetActive(name: String): Boolean {
TransferContext.writeArguments(STRING to name)
TransferContext.callMethod(rawPtr, MethodBindings.isActionSetActivePtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
public fun setActionSetActive(name: String, active: Boolean): Unit {
TransferContext.writeArguments(STRING to name, BOOL to active)
TransferContext.callMethod(rawPtr, MethodBindings.setActionSetActivePtr, NIL)
}
public fun getActionSets(): VariantArray<Any?> {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getActionSetsPtr, ARRAY)
return (TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>)
}
public fun getAvailableDisplayRefreshRates(): VariantArray<Any?> {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getAvailableDisplayRefreshRatesPtr, ARRAY)
return (TransferContext.readReturnValue(ARRAY, false) as VariantArray<Any?>)
}
public fun setMotionRange(hand: Hand, motionRange: HandMotionRange): Unit {
TransferContext.writeArguments(LONG to hand.id, LONG to motionRange.id)
TransferContext.callMethod(rawPtr, MethodBindings.setMotionRangePtr, NIL)
}
public fun getMotionRange(hand: Hand): HandMotionRange {
TransferContext.writeArguments(LONG to hand.id)
TransferContext.callMethod(rawPtr, MethodBindings.getMotionRangePtr, LONG)
return OpenXRInterface.HandMotionRange.from(TransferContext.readReturnValue(LONG) as Long)
}
public fun getHandJointFlags(hand: Hand, joint: HandJoints): HandJointFlags {
TransferContext.writeArguments(LONG to hand.id, LONG to joint.id)
TransferContext.callMethod(rawPtr, MethodBindings.getHandJointFlagsPtr, LONG)
return HandJointFlagsValue(TransferContext.readReturnValue(LONG) as Long)
}
public fun getHandJointRotation(hand: Hand, joint: HandJoints): Quaternion {
TransferContext.writeArguments(LONG to hand.id, LONG to joint.id)
TransferContext.callMethod(rawPtr, MethodBindings.getHandJointRotationPtr, QUATERNION)
return (TransferContext.readReturnValue(QUATERNION, false) as Quaternion)
}
public fun getHandJointPosition(hand: Hand, joint: HandJoints): Vector3 {
TransferContext.writeArguments(LONG to hand.id, LONG to joint.id)
TransferContext.callMethod(rawPtr, MethodBindings.getHandJointPositionPtr, VECTOR3)
return (TransferContext.readReturnValue(VECTOR3, false) as Vector3)
}
public fun getHandJointRadius(hand: Hand, joint: HandJoints): Float {
TransferContext.writeArguments(LONG to hand.id, LONG to joint.id)
TransferContext.callMethod(rawPtr, MethodBindings.getHandJointRadiusPtr, DOUBLE)
return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat()
}
public fun getHandJointLinearVelocity(hand: Hand, joint: HandJoints): Vector3 {
TransferContext.writeArguments(LONG to hand.id, LONG to joint.id)
TransferContext.callMethod(rawPtr, MethodBindings.getHandJointLinearVelocityPtr, VECTOR3)
return (TransferContext.readReturnValue(VECTOR3, false) as Vector3)
}
public fun getHandJointAngularVelocity(hand: Hand, joint: HandJoints): Vector3 {
TransferContext.writeArguments(LONG to hand.id, LONG to joint.id)
TransferContext.callMethod(rawPtr, MethodBindings.getHandJointAngularVelocityPtr, VECTOR3)
return (TransferContext.readReturnValue(VECTOR3, false) as Vector3)
}
public fun isHandTrackingSupported(): Boolean {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.isHandTrackingSupportedPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
public fun isEyeGazeInteractionSupported(): Boolean {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.isEyeGazeInteractionSupportedPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
public enum class Hand(
id: Long,
) {
HAND_LEFT(0),
HAND_RIGHT(1),
HAND_MAX(2),
;
public val id: Long
init {
this.id = id
}
public companion object {
public fun from(`value`: Long) = entries.single { it.id == `value` }
}
}
public enum class HandMotionRange(
id: Long,
) {
HAND_MOTION_RANGE_UNOBSTRUCTED(0),
HAND_MOTION_RANGE_CONFORM_TO_CONTROLLER(1),
HAND_MOTION_RANGE_MAX(2),
;
public val id: Long
init {
this.id = id
}
public companion object {
public fun from(`value`: Long) = entries.single { it.id == `value` }
}
}
public enum class HandJoints(
id: Long,
) {
HAND_JOINT_PALM(0),
HAND_JOINT_WRIST(1),
HAND_JOINT_THUMB_METACARPAL(2),
HAND_JOINT_THUMB_PROXIMAL(3),
HAND_JOINT_THUMB_DISTAL(4),
HAND_JOINT_THUMB_TIP(5),
HAND_JOINT_INDEX_METACARPAL(6),
HAND_JOINT_INDEX_PROXIMAL(7),
HAND_JOINT_INDEX_INTERMEDIATE(8),
HAND_JOINT_INDEX_DISTAL(9),
HAND_JOINT_INDEX_TIP(10),
HAND_JOINT_MIDDLE_METACARPAL(11),
HAND_JOINT_MIDDLE_PROXIMAL(12),
HAND_JOINT_MIDDLE_INTERMEDIATE(13),
HAND_JOINT_MIDDLE_DISTAL(14),
HAND_JOINT_MIDDLE_TIP(15),
HAND_JOINT_RING_METACARPAL(16),
HAND_JOINT_RING_PROXIMAL(17),
HAND_JOINT_RING_INTERMEDIATE(18),
HAND_JOINT_RING_DISTAL(19),
HAND_JOINT_RING_TIP(20),
HAND_JOINT_LITTLE_METACARPAL(21),
HAND_JOINT_LITTLE_PROXIMAL(22),
HAND_JOINT_LITTLE_INTERMEDIATE(23),
HAND_JOINT_LITTLE_DISTAL(24),
HAND_JOINT_LITTLE_TIP(25),
HAND_JOINT_MAX(26),
;
public val id: Long
init {
this.id = id
}
public companion object {
public fun from(`value`: Long) = entries.single { it.id == `value` }
}
}
public sealed interface HandJointFlags {
public val flag: Long
public infix fun or(other: HandJointFlags): HandJointFlags =
HandJointFlagsValue(flag.or(other.flag))
public infix fun or(other: Long): HandJointFlags = HandJointFlagsValue(flag.or(other))
public infix fun xor(other: HandJointFlags): HandJointFlags =
HandJointFlagsValue(flag.xor(other.flag))
public infix fun xor(other: Long): HandJointFlags = HandJointFlagsValue(flag.xor(other))
public infix fun and(other: HandJointFlags): HandJointFlags =
HandJointFlagsValue(flag.and(other.flag))
public infix fun and(other: Long): HandJointFlags = HandJointFlagsValue(flag.and(other))
public operator fun plus(other: HandJointFlags): HandJointFlags =
HandJointFlagsValue(flag.plus(other.flag))
public operator fun plus(other: Long): HandJointFlags = HandJointFlagsValue(flag.plus(other))
public operator fun minus(other: HandJointFlags): HandJointFlags =
HandJointFlagsValue(flag.minus(other.flag))
public operator fun minus(other: Long): HandJointFlags = HandJointFlagsValue(flag.minus(other))
public operator fun times(other: HandJointFlags): HandJointFlags =
HandJointFlagsValue(flag.times(other.flag))
public operator fun times(other: Long): HandJointFlags = HandJointFlagsValue(flag.times(other))
public operator fun div(other: HandJointFlags): HandJointFlags =
HandJointFlagsValue(flag.div(other.flag))
public operator fun div(other: Long): HandJointFlags = HandJointFlagsValue(flag.div(other))
public operator fun rem(other: HandJointFlags): HandJointFlags =
HandJointFlagsValue(flag.rem(other.flag))
public operator fun rem(other: Long): HandJointFlags = HandJointFlagsValue(flag.rem(other))
public fun unaryPlus(): HandJointFlags = HandJointFlagsValue(flag.unaryPlus())
public fun unaryMinus(): HandJointFlags = HandJointFlagsValue(flag.unaryMinus())
public fun inv(): HandJointFlags = HandJointFlagsValue(flag.inv())
public infix fun shl(bits: Int): HandJointFlags = HandJointFlagsValue(flag shl bits)
public infix fun shr(bits: Int): HandJointFlags = HandJointFlagsValue(flag shr bits)
public infix fun ushr(bits: Int): HandJointFlags = HandJointFlagsValue(flag ushr bits)
public companion object {
public val HAND_JOINT_NONE: HandJointFlags = HandJointFlagsValue(0)
public val HAND_JOINT_ORIENTATION_VALID: HandJointFlags = HandJointFlagsValue(1)
public val HAND_JOINT_ORIENTATION_TRACKED: HandJointFlags = HandJointFlagsValue(2)
public val HAND_JOINT_POSITION_VALID: HandJointFlags = HandJointFlagsValue(4)
public val HAND_JOINT_POSITION_TRACKED: HandJointFlags = HandJointFlagsValue(8)
public val HAND_JOINT_LINEAR_VELOCITY_VALID: HandJointFlags = HandJointFlagsValue(16)
public val HAND_JOINT_ANGULAR_VELOCITY_VALID: HandJointFlags = HandJointFlagsValue(32)
}
}
@JvmInline
internal value class HandJointFlagsValue internal constructor(
public override val flag: Long,
) : HandJointFlags
public companion object
internal object MethodBindings {
public val getDisplayRefreshRatePtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_display_refresh_rate")
public val setDisplayRefreshRatePtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "set_display_refresh_rate")
public val getRenderTargetSizeMultiplierPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_render_target_size_multiplier")
public val setRenderTargetSizeMultiplierPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "set_render_target_size_multiplier")
public val isFoveationSupportedPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "is_foveation_supported")
public val getFoveationLevelPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_foveation_level")
public val setFoveationLevelPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "set_foveation_level")
public val getFoveationDynamicPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_foveation_dynamic")
public val setFoveationDynamicPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "set_foveation_dynamic")
public val isActionSetActivePtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "is_action_set_active")
public val setActionSetActivePtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "set_action_set_active")
public val getActionSetsPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_action_sets")
public val getAvailableDisplayRefreshRatesPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_available_display_refresh_rates")
public val setMotionRangePtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "set_motion_range")
public val getMotionRangePtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_motion_range")
public val getHandJointFlagsPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_hand_joint_flags")
public val getHandJointRotationPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_hand_joint_rotation")
public val getHandJointPositionPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_hand_joint_position")
public val getHandJointRadiusPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_hand_joint_radius")
public val getHandJointLinearVelocityPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_hand_joint_linear_velocity")
public val getHandJointAngularVelocityPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "get_hand_joint_angular_velocity")
public val isHandTrackingSupportedPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "is_hand_tracking_supported")
public val isEyeGazeInteractionSupportedPtr: VoidPtr =
TypeManager.getMethodBindPtr("OpenXRInterface", "is_eye_gaze_interaction_supported")
}
}
public infix fun Long.or(other: godot.OpenXRInterface.HandJointFlags): Long = this.or(other.flag)
public infix fun Long.xor(other: godot.OpenXRInterface.HandJointFlags): Long = this.xor(other.flag)
public infix fun Long.and(other: godot.OpenXRInterface.HandJointFlags): Long = this.and(other.flag)
public operator fun Long.plus(other: godot.OpenXRInterface.HandJointFlags): Long =
this.plus(other.flag)
public operator fun Long.minus(other: godot.OpenXRInterface.HandJointFlags): Long =
this.minus(other.flag)
public operator fun Long.times(other: godot.OpenXRInterface.HandJointFlags): Long =
this.times(other.flag)
public operator fun Long.div(other: godot.OpenXRInterface.HandJointFlags): Long =
this.div(other.flag)
public operator fun Long.rem(other: godot.OpenXRInterface.HandJointFlags): Long =
this.rem(other.flag)
| 61 | Kotlin | 33 | 445 | 1dfa11d5c43fc9f85de2260b8e88f4911afddcb9 | 16,527 | godot-kotlin-jvm | MIT License |
app/src/main/java/ru/dronelektron/investmentcalculator/di/module/PresentationModule.kt | dronelektron | 294,493,925 | false | null | package ru.dronelektron.investmentcalculator.di.module
import androidx.lifecycle.ViewModelProvider
import dagger.Module
import dagger.Provides
import ru.dronelektron.investmentcalculator.di.annotation.InvestForm
import ru.dronelektron.investmentcalculator.domain.usecase.CalculateProfitUseCase
import ru.dronelektron.investmentcalculator.presentation.investform.InvestFormViewModelFactory
@Module
class PresentationModule {
@Provides
@InvestForm
fun provideInvestFormViewModelFactory(
calculateProfitUseCase: CalculateProfitUseCase
): ViewModelProvider.Factory = InvestFormViewModelFactory(calculateProfitUseCase)
}
| 0 | Kotlin | 0 | 0 | 5108e1a2e11f9dade739a277610ff3be9d7f85af | 642 | investment-calculator | MIT License |
app/src/main/java/com/example/inventory/ui/item/ItemEditViewModel.kt | sagargupta35 | 722,047,338 | false | {"Kotlin": 67521} | /*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.inventory.ui.item
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.inventory.data.ItemsRepository
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
/**
* ViewModel to retrieve and update an item from the [ItemsRepository]'s data source.
*/
class ItemEditViewModel(
savedStateHandle: SavedStateHandle,
private val itemsRepository: ItemsRepository
) : ViewModel() {
/**
* Holds current item ui state
*/
var itemUiState by mutableStateOf(ItemUiState())
private set
init {
// viewModelScope.launch{
// Log.d("TAG", itemId.toString())
// itemsRepository.getItemStream(itemId)
// .collect{
// itemUiState = it?.toItemUiState(true) ?: ItemUiState(
// itemDetails = ItemDetails(name = "Test", price = "23", quantity = "69")
// )
// }
// }
updateUiState()
}
private val itemId: Int = checkNotNull(savedStateHandle[ItemEditDestination.itemIdArg])
private fun updateUiState(){
viewModelScope.launch {
itemUiState = itemsRepository.getItemStream(ItemDetailsDestination.itemId)
.filterNotNull()
.first()
.toItemUiState(true)
}
}
fun updateUiState(itemDetails: ItemDetails) {
itemUiState =
ItemUiState(itemDetails = itemDetails, isEntryValid = validateInput(itemDetails))
}
private fun validateInput(uiState: ItemDetails = itemUiState.itemDetails): Boolean {
return with(uiState) {
name.isNotBlank() && price.isNotBlank() && quantity.isNotBlank()
}
}
suspend fun updateItem(){
if(validateInput(itemUiState.itemDetails)){
itemsRepository.updateItem(itemUiState.itemDetails.toItem())
}
}
}
| 0 | Kotlin | 0 | 0 | 0422029f18ecf3d41592280596bbb88bae09d634 | 3,003 | Inventory | Apache License 2.0 |
common/src/main/kotlin/io/liquidsoftware/common/logging/Logging.kt | edreyer | 445,325,795 | false | {"Kotlin": 197484, "Procfile": 119} | package io.liquidsoftware.common.logging
import org.slf4j.Logger
import org.slf4j.LoggerFactory.getLogger
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
import kotlin.reflect.full.companionObject
class LoggerDelegate<in R : Any> : ReadOnlyProperty<R, Logger> {
override fun getValue(thisRef: R, property: KProperty<*>): Logger =
getLogger(getClassForLogging(thisRef.javaClass))
}
fun <T : Any> getClassForLogging(javaClass: Class<T>): Class<*> {
return javaClass.enclosingClass?.takeIf {
it.kotlin.companionObject?.java == javaClass
} ?: javaClass
}
| 13 | Kotlin | 9 | 28 | 1cb7199d8aee3d534f9b3369555eb399a613eb64 | 594 | modulith | MIT License |
app/src/main/java/com/blockeq/stellarwallet/models/SelectionModel.kt | Block-Equity | 128,590,362 | false | null | package com.blockeq.stellarwallet.models
import org.stellar.sdk.Asset
open class SelectionModel(var label: String, var value: Int, var holdings: Double, var asset : Asset?) {
override fun toString(): String {
return label
}
} | 14 | Kotlin | 24 | 32 | 7996e9c75f4af6dc49241e918494155d0b82493e | 243 | stellar-android-wallet | MIT License |
app/src/main/java/org/simple/clinic/contactpatient/ContactPatientUi.kt | simpledotorg | 132,515,649 | false | {"Kotlin": 5970450, "Shell": 1660, "HTML": 545} | package org.simple.clinic.contactpatient
import org.simple.clinic.overdue.TimeToAppointment
import java.time.LocalDate
interface ContactPatientUi {
fun showProgress()
fun hideProgress()
/**
* Call patient view
*/
fun switchToCallPatientView()
fun switchToSetAppointmentReminderView()
fun renderPatientDetails(patientDetails: PatientDetails)
fun showSecureCallUi()
fun hideSecureCallUi()
fun showNormalCallButtonText()
fun showCallButtonText()
fun showPatientWithNoPhoneNumberUi()
fun hidePatientWithNoPhoneNumberUi()
fun showPatientWithPhoneNumberUi()
fun hidePatientWithPhoneNumberUi()
fun setResultOfCallLabelText()
fun setResultLabelText()
fun setRegisterAtLabelText()
fun setTransferredFromLabelText()
fun showPatientWithPhoneNumberCallResults()
fun hidePatientWithPhoneNumberCallResults()
fun showPatientWithNoPhoneNumberResults()
fun showDeadPatientStatus()
fun hideDeadPatientStatus()
/**
* Select reminder view
*/
fun renderSelectedAppointmentDate(
selectedAppointmentReminderPeriod: TimeToAppointment,
selectedDate: LocalDate
)
fun disablePreviousReminderDateStepper()
fun enablePreviousReminderDateStepper()
fun disableNextReminderDateStepper()
fun enableNextReminderDateStepper()
fun showCallResult()
fun hideCallResult()
fun setupAgreedToVisitCallResultOutcome()
fun setupRemindToCallLaterCallResultOutcome(appointmentReminderDate: LocalDate)
fun setupRemovedFromListCallResultOutcome(removeReasonStringRes: Int)
fun setCallResultUpdatedAtDate(callResultUpdatedAt: LocalDate)
}
| 4 | Kotlin | 73 | 223 | 58d14c702db2b27b9dc6c1298c337225f854be6d | 1,603 | simple-android | MIT License |
app/src/main/java/com/example/quotidian/repo/data/Quotes.kt | lssarao | 579,010,205 | false | {"Kotlin": 19016} | package com.example.quotidian.repo.data
import android.os.Parcelable
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize
import kotlinx.serialization.Serializable
@Serializable
@Parcelize
@Entity(tableName = "Daily_Quotes")
data class Quotes(
@SerializedName("q") val quote: String?,
@SerializedName("a") val author: String,
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "ID") val id: Int = 0,
) : Parcelable | 0 | Kotlin | 0 | 1 | aff9d2bebb0eaa763f6a92c2aa36ae48d238c577 | 554 | jetpack-compose-quotidian | MIT License |
libraries/report/src/commonMain/kotlin/com/zegreatrob/testmints/report/MintReporterConfig.kt | robertfmurdock | 172,112,213 | false | {"Kotlin": 170915, "JavaScript": 796, "Batchfile": 697, "Dockerfile": 282} | package com.zegreatrob.testmints.report
import kotlin.native.concurrent.ThreadLocal
@ThreadLocal
object MintReporterConfig : ReporterProvider {
override var reporter: MintReporter = PlaceholderMintReporter
}
| 0 | Kotlin | 2 | 6 | 9044806e7f09bb6365b1854a69a8cf67f2404587 | 214 | testmints | MIT License |
algorithms/src/main/kotlin/org/baichuan/sample/algorithms/leetcode/simple/RemoveDuplicates.kt | scientificCommunity | 352,868,267 | false | {"Java": 154453, "Kotlin": 69817} | package org.baichuan.sample.algorithms.leetcode.simple
/**
* https://leetcode.cn/problems/remove-duplicates-from-sorted-array/
* 26. 删除有序数组中的重复项
*/
class RemoveDuplicates {
fun removeDuplicates(nums: IntArray): Int {
var pre: Int? = null
var end = 0
var i = 0
while (true) {
if (i > nums.size - 1 - end) {
break
}
if (nums[i] == pre) {
reRange(i, nums, end)
end++
i--
} else {
pre = nums[i]
}
i++
}
return nums.size - end
}
private fun reRange(start: Int, nums: IntArray, end: Int) {
for (i in start until nums.size - end - 1) {
nums[i] = nums[i + 1]
}
}
}
fun main() {
RemoveDuplicates().removeDuplicates(arrayOf(0, 0, 1, 1, 1, 2, 2, 3, 3, 4).toIntArray())
} | 1 | Java | 0 | 8 | 36e291c0135a06f3064e6ac0e573691ac70714b6 | 935 | blog-sample | Apache License 2.0 |
Chapter07/Journaler API/api/src/main/kotlin/com/journaler/api/reactor/NotesCountNotificationServiceImpl.kt | PacktPublishing | 102,436,360 | false | null | package com.journaler.api.reactor
import com.journaler.api.mail.MailMessage
import com.journaler.api.mail.MailService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
@Service
class NotesCountNotificationServiceImpl : NotesCountNotificationService {
@Autowired
private lateinit var mailService: MailService
override fun notify(notification: NotesCountNotification) {
val to = "<EMAIL>"
val subject = "Notes count notification"
val text = "Notes reached ${notification.notesCount} count."
val message = MailMessage(to, subject, text)
mailService.sendMessage(message)
}
} | 0 | Kotlin | 12 | 22 | 914a9d5d336e3563c3a12b6ad7b8e3321f3ec46d | 720 | Building-Applications-with-Spring-5-and-Kotlin | MIT License |
src/main/kotlin/com/notify/scheduler/ScheduledTasks.kt | u-verma | 288,201,627 | false | null | package com.notify.scheduler
import com.notify.api.user.repository.UserProfileRepository
import com.notify.client.email.service.EmailService
import org.slf4j.LoggerFactory
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component
import java.text.SimpleDateFormat
@Component
class ScheduledTasks(val emailService: EmailService,
val userProfileRepository: UserProfileRepository) {
private val logger = LoggerFactory.getLogger(ScheduledTasks::class.java)
private val dateFormat = SimpleDateFormat("HH:mm:ss")
@Scheduled(cron = "0 * * ? * *")
fun reportCurrentTime() {
val userList = userProfileRepository.getUsersForSchedulingEmail()
logger.info("The User List for scheduling email: ${userList.isEmpty()}")
if (userList.isNotEmpty()) {
emailService.execute(userList)
run { userProfileRepository.updateLastEmailSentTs(userList) }
}
}
} | 0 | Kotlin | 0 | 0 | c739d5712d03349722c417eefbae348a256a6b4a | 983 | notification | Apache License 2.0 |
archimedes-data-jdbc/src/main/kotlin/io/archimedesfw/data/EntityVersionedString.kt | archimedes-projects | 362,401,748 | false | null | package io.archimedesfw.data
interface EntityVersionedString : EntityVersioned<String>, EntityString
| 0 | Kotlin | 4 | 25 | 000669e868c4d2a1ee84f9007ca9d291b64521b2 | 102 | archimedes-jvm | Apache License 2.0 |
compiler/backend/src/org/jetbrains/kotlin/codegen/optimization/fixStack/BasicTypeInterpreter.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.codegen.optimization.fixStack
import org.jetbrains.kotlin.codegen.inline.insnOpcodeText
import org.jetbrains.kotlin.resolve.jvm.AsmTypes
import org.jetbrains.org.objectweb.asm.Handle
import org.jetbrains.org.objectweb.asm.Opcodes.*
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.tree.*
import org.jetbrains.org.objectweb.asm.tree.analysis.AnalyzerException
import org.jetbrains.org.objectweb.asm.tree.analysis.Interpreter
import org.jetbrains.org.objectweb.asm.tree.analysis.Value
abstract class BasicTypeInterpreter<V : Value> : Interpreter<V>(API_VERSION) {
protected abstract fun uninitializedValue(): V
protected abstract fun booleanValue(): V
protected abstract fun charValue(): V
protected abstract fun byteValue(): V
protected abstract fun shortValue(): V
protected abstract fun intValue(): V
protected abstract fun longValue(): V
protected abstract fun floatValue(): V
protected abstract fun doubleValue(): V
protected abstract fun nullValue(): V
protected abstract fun objectValue(type: Type): V
protected abstract fun arrayValue(type: Type): V
protected abstract fun methodValue(type: Type): V
protected abstract fun handleValue(handle: Handle): V
protected abstract fun typeConstValue(typeConst: Type): V
protected abstract fun aaLoadValue(arrayValue: V): V
override fun newValue(type: Type?): V? =
if (type == null)
uninitializedValue()
else when (type.sort) {
Type.VOID -> null
Type.BOOLEAN -> booleanValue()
Type.CHAR -> charValue()
Type.BYTE -> byteValue()
Type.SHORT -> shortValue()
Type.INT -> intValue()
Type.FLOAT -> floatValue()
Type.LONG -> longValue()
Type.DOUBLE -> doubleValue()
Type.ARRAY -> arrayValue(type)
Type.OBJECT -> objectValue(type)
Type.METHOD -> methodValue(type)
else -> throw AssertionError("Unexpected type: $type")
}
override fun newEmptyValue(local: Int): V {
return uninitializedValue()
}
override fun newOperation(insn: AbstractInsnNode): V? =
when (insn.opcode) {
ACONST_NULL ->
nullValue()
ICONST_M1, ICONST_0, ICONST_1, ICONST_2, ICONST_3, ICONST_4, ICONST_5 ->
intValue()
LCONST_0, LCONST_1 ->
longValue()
FCONST_0, FCONST_1, FCONST_2 ->
floatValue()
DCONST_0, DCONST_1 ->
doubleValue()
BIPUSH, SIPUSH ->
intValue()
LDC -> {
when (val cst = (insn as LdcInsnNode).cst) {
is Int -> intValue()
is Float -> floatValue()
is Long -> longValue()
is Double -> doubleValue()
is String -> objectValue(AsmTypes.JAVA_STRING_TYPE)
is Handle -> handleValue(cst)
is Type -> typeConstValue(cst)
else -> throw IllegalArgumentException("Illegal LDC constant $cst")
}
}
GETSTATIC ->
newValue(Type.getType((insn as FieldInsnNode).desc))
NEW ->
newValue(Type.getObjectType((insn as TypeInsnNode).desc))
else ->
throw IllegalArgumentException("Unexpected instruction: " + insn.insnOpcodeText)
}
override fun binaryOperation(insn: AbstractInsnNode, value1: V, value2: V): V? =
when (insn.opcode) {
IALOAD, BALOAD, CALOAD, SALOAD, IADD, ISUB, IMUL, IDIV, IREM, ISHL, ISHR, IUSHR, IAND, IOR, IXOR ->
intValue()
FALOAD, FADD, FSUB, FMUL, FDIV, FREM ->
floatValue()
LALOAD, LADD, LSUB, LMUL, LDIV, LREM, LSHL, LSHR, LUSHR, LAND, LOR, LXOR ->
longValue()
DALOAD, DADD, DSUB, DMUL, DDIV, DREM ->
doubleValue()
AALOAD ->
aaLoadValue(value1)
LCMP, FCMPL, FCMPG, DCMPL, DCMPG ->
intValue()
IF_ICMPEQ, IF_ICMPNE, IF_ICMPLT, IF_ICMPGE, IF_ICMPGT, IF_ICMPLE, IF_ACMPEQ, IF_ACMPNE, PUTFIELD ->
null
else ->
throw IllegalArgumentException("Unexpected instruction: " + insn.insnOpcodeText)
}
override fun ternaryOperation(insn: AbstractInsnNode, value1: V, value2: V, value3: V): V? =
null
override fun naryOperation(insn: AbstractInsnNode, values: List<V>): V? =
when (insn.opcode) {
MULTIANEWARRAY ->
newValue(Type.getType((insn as MultiANewArrayInsnNode).desc))
INVOKEDYNAMIC ->
newValue(Type.getReturnType((insn as InvokeDynamicInsnNode).desc))
else ->
newValue(Type.getReturnType((insn as MethodInsnNode).desc))
}
override fun returnOperation(insn: AbstractInsnNode, value: V?, expected: V?) {
}
override fun unaryOperation(insn: AbstractInsnNode, value: V): V? =
when (insn.opcode) {
INEG, IINC, L2I, F2I, D2I, I2B, I2C, I2S ->
intValue()
FNEG, I2F, L2F, D2F ->
floatValue()
LNEG, I2L, F2L, D2L ->
longValue()
DNEG, I2D, L2D, F2D ->
doubleValue()
IFEQ, IFNE, IFLT, IFGE, IFGT, IFLE, TABLESWITCH, LOOKUPSWITCH, IRETURN, LRETURN, FRETURN, DRETURN, ARETURN, PUTSTATIC ->
null
GETFIELD ->
newValue(Type.getType((insn as FieldInsnNode).desc))
NEWARRAY ->
when ((insn as IntInsnNode).operand) {
T_BOOLEAN -> newValue(Type.getType("[Z"))
T_CHAR -> newValue(Type.getType("[C"))
T_BYTE -> newValue(Type.getType("[B"))
T_SHORT -> newValue(Type.getType("[S"))
T_INT -> newValue(Type.getType("[I"))
T_FLOAT -> newValue(Type.getType("[F"))
T_DOUBLE -> newValue(Type.getType("[D"))
T_LONG -> newValue(Type.getType("[J"))
else -> throw AnalyzerException(insn, "Invalid array type")
}
ANEWARRAY ->
newValue(Type.getType("[" + Type.getObjectType((insn as TypeInsnNode).desc)))
ARRAYLENGTH ->
intValue()
ATHROW ->
null
CHECKCAST ->
newValue(Type.getObjectType((insn as TypeInsnNode).desc))
INSTANCEOF ->
intValue()
MONITORENTER, MONITOREXIT, IFNULL, IFNONNULL ->
null
else ->
throw IllegalArgumentException("Unexpected instruction: " + insn.insnOpcodeText)
}
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 7,187 | kotlin | Apache License 2.0 |
compiler/tests-spec/testData/diagnostics/linked/expressions/constant-literals/the-types-for-integer-literals/p-1/neg/2.3.fir.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // SKIP_TXT
/*
* KOTLIN DIAGNOSTICS SPEC TEST (NEGATIVE)
*
* SPEC VERSION: 0.1-100
* MAIN LINK: expressions, constant-literals, the-types-for-integer-literals -> paragraph 1 -> sentence 2
* NUMBER: 3
* DESCRIPTION: Type checking (comparison with invalid types) of various integer literals.
* HELPERS: checkType
*/
// TESTCASE NUMBER: 1
fun case_1() {
0 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
0 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
0 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
}
// TESTCASE NUMBER: 2
fun case_2() {
127 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
127 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
127 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>128<!>)
128 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
128 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
128 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
-128 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
-128 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
-128 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>-129<!>)
-129 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
-129 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
-129 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
}
// TESTCASE NUMBER: 3
fun case_3() {
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>32767<!>)
32767 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
32767 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
32767 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>32768<!>)
checkSubtype<Short>(<!ARGUMENT_TYPE_MISMATCH!>32768<!>)
32768 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
32768 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
32768 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>-32768<!>)
-32768 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
-32768 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
-32768 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>-32769<!>)
checkSubtype<Short>(<!ARGUMENT_TYPE_MISMATCH!>-32769<!>)
-32769 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
-32769 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
-32769 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
}
// TESTCASE NUMBER: 4
fun case_4() {
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>2147483647<!>)
checkSubtype<Short>(<!ARGUMENT_TYPE_MISMATCH!>2147483647<!>)
2147483647 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
2147483647 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
2147483647 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>2147483648<!>)
checkSubtype<Short>(<!ARGUMENT_TYPE_MISMATCH!>2147483648<!>)
checkSubtype<Int>(<!ARGUMENT_TYPE_MISMATCH!>2147483648<!>)
2147483648 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
2147483648 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
2147483648 checkType { <!NONE_APPLICABLE!>check<!><Int>() }
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>-2147483648<!>)
checkSubtype<Short>(<!ARGUMENT_TYPE_MISMATCH!>-2147483648<!>)
-2147483648 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
-2147483648 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
-2147483648 checkType { <!NONE_APPLICABLE!>check<!><Long>() }
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>-2147483649<!>)
checkSubtype<Short>(<!ARGUMENT_TYPE_MISMATCH!>-2147483649<!>)
checkSubtype<Int>(<!ARGUMENT_TYPE_MISMATCH!>-2147483649<!>)
-2147483649 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
-2147483649 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
-2147483649 checkType { <!NONE_APPLICABLE!>check<!><Int>() }
}
// TESTCASE NUMBER: 5
fun case_5() {
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>9223372036854775807<!>)
checkSubtype<Short>(<!ARGUMENT_TYPE_MISMATCH!>9223372036854775807<!>)
checkSubtype<Int>(<!ARGUMENT_TYPE_MISMATCH!>9223372036854775807<!>)
9223372036854775807 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
9223372036854775807 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
9223372036854775807 checkType { <!NONE_APPLICABLE!>check<!><Int>() }
checkSubtype<Byte>(<!ARGUMENT_TYPE_MISMATCH!>-9223372036854775807<!>)
checkSubtype<Short>(<!ARGUMENT_TYPE_MISMATCH!>-9223372036854775807<!>)
checkSubtype<Int>(<!ARGUMENT_TYPE_MISMATCH!>-9223372036854775807<!>)
-9223372036854775807 checkType { <!NONE_APPLICABLE!>check<!><Byte>() }
-9223372036854775807 checkType { <!NONE_APPLICABLE!>check<!><Short>() }
-9223372036854775807 checkType { <!NONE_APPLICABLE!>check<!><Int>() }
}
// TESTCASE NUMBER: 6
fun case_6() {
checkSubtype<Byte>(<!OVERLOAD_RESOLUTION_AMBIGUITY!>-<!><!INT_LITERAL_OUT_OF_RANGE!>100000000000000000000000000000000<!>)
checkSubtype<Short>(<!OVERLOAD_RESOLUTION_AMBIGUITY!>-<!><!INT_LITERAL_OUT_OF_RANGE!>100000000000000000000000000000000<!>)
checkSubtype<Int>(<!OVERLOAD_RESOLUTION_AMBIGUITY!>-<!><!INT_LITERAL_OUT_OF_RANGE!>100000000000000000000000000000000<!>)
checkSubtype<Long>(<!OVERLOAD_RESOLUTION_AMBIGUITY!>-<!><!INT_LITERAL_OUT_OF_RANGE!>100000000000000000000000000000000<!>)
<!OVERLOAD_RESOLUTION_AMBIGUITY!>-<!><!INT_LITERAL_OUT_OF_RANGE!>100000000000000000000000000000000<!> <!UNRESOLVED_REFERENCE_WRONG_RECEIVER!>checkType<!> { <!INAPPLICABLE_CANDIDATE!>check<!><<!CANNOT_INFER_PARAMETER_TYPE!>Byte<!>>() }
<!OVERLOAD_RESOLUTION_AMBIGUITY!>-<!><!INT_LITERAL_OUT_OF_RANGE!>100000000000000000000000000000000<!> <!UNRESOLVED_REFERENCE_WRONG_RECEIVER!>checkType<!> { <!INAPPLICABLE_CANDIDATE!>check<!><<!CANNOT_INFER_PARAMETER_TYPE!>Short<!>>() }
<!OVERLOAD_RESOLUTION_AMBIGUITY!>-<!><!INT_LITERAL_OUT_OF_RANGE!>100000000000000000000000000000000<!> <!UNRESOLVED_REFERENCE_WRONG_RECEIVER!>checkType<!> { <!INAPPLICABLE_CANDIDATE!>check<!><<!CANNOT_INFER_PARAMETER_TYPE!>Int<!>>() }
<!OVERLOAD_RESOLUTION_AMBIGUITY!>-<!><!INT_LITERAL_OUT_OF_RANGE!>100000000000000000000000000000000<!> <!UNRESOLVED_REFERENCE_WRONG_RECEIVER!>checkType<!> { <!INAPPLICABLE_CANDIDATE!>check<!><<!CANNOT_INFER_PARAMETER_TYPE!>Long<!>>() }
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 6,435 | kotlin | Apache License 2.0 |
analysis/low-level-api-fir/testData/lazyResolveTypeAnnotations/destructuringDeclaration/scriptStatementLevelAsLastStatement.kts | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // RESOLVE_SCRIPT
// BODY_RESOLVE
package util
annotation class Anno(val str: String)
const val constant = "s"
data class Pair(val a: @Anno("a type $constant") List<@Anno("a nested type $constant") Collection<@Anno("a nested nested type $constant") String>>?, val b: @Anno("b type $constant") Array<@Anno("b nested type $constant") List<@Anno("b nested nested type $constant") Int>>?)
const val prop = "str"
if (true) {
@Anno("destr 1 $prop")
val (@Anno("a $prop") a, @Anno("b $prop") b) = Pair(null, null)
@Anno("destr 1 $prop")
val (@Anno("c $prop") c, @Anno("d $prop") d) = Pair(null, null)
}
fun foo() {} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 628 | kotlin | Apache License 2.0 |
app/src/main/java/com/vshyrochuk/topcharts/data/datasource/ChartsRemoteDataSource.kt | Mc231 | 524,970,692 | false | null | package com.vshyrochuk.topcharts.data.datasource
import com.vshyrochuk.topcharts.BuildConfig
import com.vshyrochuk.topcharts.data.network.ChartsApi
import com.vshyrochuk.topcharts.data.network.mapping.toDomain
import com.vshyrochuk.topcharts.domain.domain.ChartsDataSource
import com.vshyrochuk.topcharts.domain.model.ChartEntity
class ChartsRemoteDataSource(private val api: ChartsApi) : ChartsDataSource {
override suspend fun load(): List<ChartEntity> {
return api.getCharts(BuildConfig.COUNTRY, BuildConfig.LOAD_LIMIT).toDomain()
}
} | 0 | Kotlin | 0 | 0 | 8b9f6ae00d38e69b81cc466adb14bb7d2b48c20f | 556 | Top-Charts | MIT License |
nitrozen-android-lib/src/main/java/com/fynd/nitrozen/components/button/text/TextButton.kt | gofynd | 238,860,720 | false | null | package com.fynd.nitrozen.components.button.text
import androidx.compose.foundation.layout.heightIn
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.tooling.preview.Preview
import com.fynd.nitrozen.components.button.NitrozenButtonConfiguration
import com.fynd.nitrozen.components.button.NitrozenButtonConfiguration.Default
import com.fynd.nitrozen.components.button.NitrozenButtonStyle
import com.fynd.nitrozen.components.button.NitrozenButtonStyle.Default
import com.fynd.nitrozen.theme.NitrozenTheme
@Preview(showBackground = true)
@Composable
private fun NitrozenTextButton_Enabled() {
NitrozenTheme {
NitrozenTextButton(
text = "Text Button Enabled",
onClick = {},
enabled = true
)
}
}
@Preview(showBackground = true)
@Composable
private fun NitrozenTextButton_Disabled() {
NitrozenTheme {
NitrozenTextButton(
text = "Text Button Disabled",
onClick = {},
enabled = false
)
}
}
@Preview(showBackground = true)
@Composable
private fun NitrozenTextButton_Underlined() {
NitrozenTheme {
NitrozenTextButton(
text = "Text Button Underlined",
onClick = {},
enabled = true,
style = NitrozenButtonStyle.Text.Default.copy(
textDecoration = TextDecoration.Underline,
),
)
}
}
@Composable
fun NitrozenTextButton(
modifier: Modifier = Modifier,
text: String,
onClick: () -> Unit,
enabled: Boolean = true,
style: NitrozenButtonStyle.Text = NitrozenButtonStyle.Text.Default,
configuration: NitrozenButtonConfiguration.Text = NitrozenButtonConfiguration.Text.Default,
) {
val textColor =
if (enabled)
style.textColorEnabled
else
style.textColorDisabled
TextButton(
onClick = onClick,
colors = ButtonDefaults.textButtonColors(),
modifier = modifier
.heightIn(min = configuration.minHeight),
shape = configuration.shape,
enabled = enabled,
contentPadding = configuration.contentPadding,
) {
Text(
text = text,
style = style.textStyle,
color = textColor,
textDecoration = style.textDecoration,
)
}
} | 1 | Kotlin | 4 | 5 | 2e0506c5ddd9bd0ebd45814ca1c8fef232db336f | 2,554 | nitrozen-android | MIT License |
common/src/commonMain/kotlin/drop/DropEvaluator.kt | alexsocha | 181,845,813 | false | {"Kotlin": 429248, "Dockerfile": 861, "JavaScript": 402, "Shell": 114} | package mod.lucky.common.drop
import mod.lucky.common.*
import mod.lucky.common.attribute.*
import mod.lucky.common.attribute.evalAttr
import kotlin.math.pow
const val DEBUG = false
private var debugDropFilters = listOf<String>()
private var debugDropIndexRange = 0..1000
private var debugDropIndex = debugDropIndexRange.first
class DropError(msg: String) : Exception("Error performing Lucky Block function: $msg")
data class DropContext(
val world: World,
val pos: Vec3d,
val player: PlayerEntity? = null,
val hitEntity: Entity? = null,
val bowPower: Double = 1.0,
val sourceId: String,
) { companion object }
fun createDropEvalContext(dropContext: DropContext, drop: SingleDrop? = null): EvalContext {
return EvalContext(LuckyRegistry.templateVarFns, DropTemplateContext(drop, dropContext, random=KotlinRandom()))
}
fun createVecSpec(baseName: String, partNames: Triple<String, String, String>, type: AttrType? = null): Array<Pair<String, AttrSpec>> {
return arrayOf(
partNames.first to ValueSpec(type),
partNames.second to ValueSpec(type),
partNames.third to ValueSpec(type),
baseName to ListSpec(listOf(ValueSpec(type), ValueSpec(type), ValueSpec(type)))
)
}
fun evalDrop(template: BaseDrop, context: EvalContext): List<SingleDrop> {
if (template is WeightedDrop) {
return evalDrop(template.drop, context)
}
if (template is GroupDrop) {
val shuffledDrops = if (template.shuffle) template.drops.shuffled() else template.drops
val groupAmount = (evalAttr(template.amount, context) as ValueAttr).value as Int
return (0 until groupAmount).map {
evalDrop(shuffledDrops[it], context)
}.flatten().toList()
}
if (template is SingleDrop) {
val contextWithDrop = if (context.templateContext is DropTemplateContext) {
context.copy(templateContext=context.templateContext.copy(drop=template))
} else context
val drop = template.eval(contextWithDrop)
val repeatAmount: Int = drop["amount"]
val evalOnRepeat: Boolean = drop["reinitialize"]
val evalAfterDelay: Boolean = drop["postDelayInit"]
if ("delay" in template) {
// Evaluation conditions for delayed drops:
// evalAfterDelay & evalOnRepeat: add N templates, evaluate each later
// evalAfterDelay & not evalOnRepeat: add one template, evaluate later
// not evalAfterDelay & evalOnRepeat: add N differently evaluated drops
// not evalAfterDelay & not evalOnRepeat: add one evaluated drop
if (evalOnRepeat) {
return (0 until repeatAmount).map {
if (evalAfterDelay) template.evalKeys(listOf("delay"), contextWithDrop)
else if (it == 0) drop else template.eval(contextWithDrop)
}.toList()
}
return listOf(if (evalAfterDelay) template.copy(props = template.props.with(mapOf("delay" to drop["delay"]))) else drop)
}
return (0 until repeatAmount).map {
if (it == 0) drop else if (evalOnRepeat) template.eval(contextWithDrop) else drop
}.toList()
}
return emptyList()
}
fun evalDropAfterDelay(dropOrTemplate: SingleDrop, context: EvalContext): List<SingleDrop> {
val evalAfterDelay: Boolean = dropOrTemplate["postDelayInit"]
val drop = if (evalAfterDelay) dropOrTemplate.eval(context) else dropOrTemplate
// if buildOnRepeat is true, this must be one of N delayed drops, each with amount=1
val evalOnRepeat: Boolean = drop["reinitialize"]
if (evalOnRepeat) return listOf(drop)
return (0 until drop["amount"]).map { drop }.toList()
}
private fun getDropIndexByWeight(weightPoints: ArrayList<Double>, randomIndex: Double): Int {
for (i in weightPoints.indices) {
if (randomIndex >= weightPoints[i] && randomIndex < weightPoints[i + 1]) return i
}
return 0
}
private fun chooseRandomDrop(drops: List<WeightedDrop>, luck: Int): WeightedDrop {
if (drops.isEmpty()) throw DropError("No drops found")
var lowestLuck = 0
var heighestLuck = 0
for (i in drops.indices) {
if (drops[i].luck < lowestLuck) lowestLuck = drops[i].luck
if (drops[i].luck > heighestLuck) heighestLuck = drops[i].luck
}
heighestLuck += lowestLuck * -1 + 1
val levelIncrease = 1.0 / (1.0 - (if (luck < 0) luck * -1 else luck) * 0.77 / 100.0)
var weightTotal = 0.0
val weightPoints = ArrayList<Double>()
weightPoints.add(0.0)
for (drop in drops) {
val dropLuck = drop.luck + lowestLuck * -1 + 1
val newLuck =
if (luck >= 0) levelIncrease.pow(dropLuck.toDouble()).toFloat() else levelIncrease
.pow(heighestLuck + 1 - dropLuck.toDouble()).toFloat()
val newChance = (drop.chance ?: 1.0) * newLuck * 100
weightTotal += newChance
weightPoints.add(weightTotal)
}
val randomIndex = DEFAULT_RANDOM.randDouble(0.0, 1.0) * weightTotal
return drops[getDropIndexByWeight(weightPoints, randomIndex)]
}
fun runEvaluatedDrop(drop: SingleDrop, context: DropContext) {
if ("delay" in drop && drop.get<Double>("delay") > 0.0) {
GAME_API.scheduleDrop(drop, context, drop["delay"])
} else {
val fn = LuckyRegistry.dropActions[drop.type]!!
fn(drop, context)
}
}
fun runDrop(drop: WeightedDrop, context: DropContext, showOutput: Boolean) {
if (showOutput) GAME_API.logInfo("Chosen Lucky Drop: ${drop.dropString}")
val singleDrops = evalDrop(drop, createDropEvalContext(context))
singleDrops.forEach { runEvaluatedDrop(it, context) }
}
fun runDropAfterDelay(delayedDrop: SingleDrop, context: DropContext) {
val evalContext = createDropEvalContext(context)
val singleDrops = evalDropAfterDelay(delayedDrop, evalContext)
for (drop in singleDrops) {
val fn = LuckyRegistry.dropActions[drop.type]!!
fn(drop, context)
}
}
fun nextDebugDrop(drops: List<WeightedDrop>): WeightedDrop {
// during hot reloading, edit the values here
val newFilters: List<String> = debugDropFilters
val newIndexRange = debugDropIndexRange
if (newIndexRange != debugDropIndexRange || newFilters != debugDropFilters) {
debugDropIndexRange = newIndexRange
debugDropFilters = newFilters
debugDropIndex = debugDropIndexRange.first
}
val filteredDrops = if (debugDropFilters.isNotEmpty()) drops.filter { d -> debugDropFilters.any { it in d.dropString } } else drops
if (debugDropIndex > debugDropIndexRange.last || debugDropIndex >= filteredDrops.size) debugDropIndex = debugDropIndexRange.first
if (debugDropIndex >= filteredDrops.size) debugDropIndex = 0
val index = debugDropIndex
debugDropIndex += 1
return filteredDrops[index]
}
fun runRandomDrop(customDrops: List<WeightedDrop>? = null, luck: Int, context: DropContext, showOutput: Boolean) {
val drops = customDrops ?: LuckyRegistry.drops[context.sourceId] ?: emptyList()
val drop = if (DEBUG && customDrops == null) nextDebugDrop(drops) else chooseRandomDrop(drops, luck)
runDrop(drop, context, showOutput)
}
| 24 | Kotlin | 19 | 32 | ecccf2ae066b6c511bce35f16c0b1e06519c31c0 | 7,204 | luckyblock | FSF All Permissive License |
command/src/main/kotlin/com/amarcolini/joos/command/SequentialCommand.kt | 19279-M1C2 | 477,597,033 | true | {"Kotlin": 541606, "Java": 1396} | package com.amarcolini.joos.command
/**
* A command that runs commands in sequence.
*/
class SequentialCommand @JvmOverloads constructor(
override val isInterruptable: Boolean = true,
vararg val commands: Command
) : CommandGroup(false, *commands) {
private var index = -1
override fun init() {
index = 0
commands[index].init()
}
override fun execute() {
if (index < 0 || index >= commands.size) return
commands[index].execute()
if (commands[index].isFinished()) {
commands[index].end(false)
index++
if (index < commands.size) commands[index].init()
}
}
override fun isFinished() = index >= commands.size
override fun end(interrupted: Boolean) {
if (index < 0) return
if (interrupted) commands[index].end(interrupted)
super.end(interrupted)
}
} | 0 | Kotlin | 0 | 0 | 9e65a6ac51025627c837e697fe648ab4f95c5169 | 901 | joos | MIT License |
projects/execution/src/main/kotlin/silentorb/imp/execution/Types.kt | silentorb | 235,929,224 | false | {"Kotlin": 189044} | package silentorb.imp.execution
import silentorb.imp.core.*
data class CompleteFunction(
val path: PathKey,
val signature: CompleteSignature,
val implementation: FunctionImplementation
)
data class TypeAlias(
val path: TypeHash,
val alias: TypeHash? = null,
val numericConstraint: NumericTypeConstraint? = null
)
data class ExecutionStep(
val node: PathKey,
val execute: NodeImplementation
)
data class ExecutionUnit(
val steps: List<ExecutionStep>,
val values: OutputValues,
val output: PathKey
)
| 3 | Kotlin | 0 | 1 | ca465c2b0a9864ded53114120d8b98dad44551dd | 547 | imp-kotlin | MIT License |
src/main/kotlin/com/ort/howlingwolf/domain/service/ability/DivineDomainService.kt | h-orito | 176,481,255 | false | null | package com.ort.howlingwolf.domain.service.ability
import com.ort.dbflute.allcommon.CDef
import com.ort.howlingwolf.domain.model.ability.AbilityType
import com.ort.howlingwolf.domain.model.charachip.Chara
import com.ort.howlingwolf.domain.model.charachip.Charas
import com.ort.howlingwolf.domain.model.daychange.DayChange
import com.ort.howlingwolf.domain.model.message.Message
import com.ort.howlingwolf.domain.model.village.Village
import com.ort.howlingwolf.domain.model.village.ability.VillageAbilities
import com.ort.howlingwolf.domain.model.village.ability.VillageAbility
import com.ort.howlingwolf.domain.model.village.participant.VillageParticipant
import org.springframework.stereotype.Service
@Service
class DivineDomainService : IAbilityDomainService {
override fun getAbilityType(): AbilityType = AbilityType(CDef.AbilityType.占い)
override fun getSelectableTargetList(
village: Village,
participant: VillageParticipant?
): List<VillageParticipant> {
participant ?: return listOf()
// 自分以外の生存者全員
return village.participant.memberList.filter {
it.id != participant.id && it.isAlive()
}
}
override fun getSelectingTarget(
village: Village,
participant: VillageParticipant?,
villageAbilities: VillageAbilities
): VillageParticipant? {
participant ?: return null
val targetVillageParticipantId = villageAbilities
.filterLatestday(village)
.filterByType(getAbilityType()).list
.find { it.myselfId == participant.id }
?.targetId
targetVillageParticipantId ?: return null
return village.participant.member(targetVillageParticipantId)
}
override fun createSetMessage(myChara: Chara, targetChara: Chara?): String {
return "${myChara.charaName.fullName()}が占い対象を${targetChara?.charaName?.fullName() ?: "なし"}に設定しました。"
}
override fun getDefaultAbilityList(
village: Village,
villageAbilities: VillageAbilities
): List<VillageAbility> {
// 進行中のみ
if (!village.status.isProgress()) return listOf()
// 生存している占い能力持ちごとに
return village.participant.filterAlive().memberList.filter {
it.skill!!.toCdef().isHasDivineAbility
}.mapNotNull { seer ->
// 対象は自分以外の生存者からランダム
village.participant
.filterAlive()
.findRandom { it.id != seer.id }
?.let {
VillageAbility(
villageDayId = village.day.latestDay().id,
myselfId = seer.id,
targetId = it.id,
abilityType = getAbilityType()
)
}
}
}
override fun processDayChangeAction(dayChange: DayChange, charas: Charas): DayChange {
val latestDay = dayChange.village.day.latestDay()
var messages = dayChange.messages.copy()
var village = dayChange.village.copy()
dayChange.village.participant.memberList.filter {
it.isAlive() && it.skill!!.toCdef().isHasDivineAbility
}.forEach { seer ->
dayChange.abilities.filterYesterday(village).list.find {
it.myselfId == seer.id
}?.let { ability ->
messages = messages.add(createDivineMessage(dayChange.village, charas, ability, seer))
// 呪殺対象なら死亡
if (isDivineKill(dayChange, ability.targetId!!)) village = village.divineKillParticipant(ability.targetId, latestDay)
}
}
return dayChange.copy(
messages = messages,
village = village
).setIsChange(dayChange)
}
override fun isAvailableNoTarget(village: Village): Boolean = false
override fun isUsable(village: Village, participant: VillageParticipant): Boolean {
// 生存していたら行使できる
return participant.isAlive()
}
// ===================================================================================
// Assist Logic
// ============
private fun createDivineMessage(
village: Village,
charas: Charas,
ability: VillageAbility,
seer: VillageParticipant
): Message {
val myself = village.participant.member(ability.myselfId)
val myChara = charas.chara(myself.charaId)
val targetChara = charas.chara(village.participant, ability.targetId!!)
val isWolf = village.participant.member(ability.targetId).skill!!.toCdef().isDivineResultWolf
val text = createDivineMessageString(myChara, targetChara, isWolf)
return Message.createSeerPrivateMessage(text, village.day.latestDay().id, seer)
}
private fun createDivineMessageString(chara: Chara, targetChara: Chara, isWolf: Boolean): String =
"${chara.charaName.fullName()}は、${targetChara.charaName.fullName()}を占った。\n${targetChara.charaName.fullName()}は人狼${if (isWolf) "の" else "ではない"}ようだ。"
private fun isDivineKill(dayChange: DayChange, targetId: Int): Boolean {
// 対象が既に死亡していたら呪殺ではない
if (!dayChange.village.participant.member(targetId).isAlive()) return false
// 対象が呪殺対象でなければ呪殺ではない
return dayChange.village.participant.member(targetId).skill!!.toCdef().isDeadByDivine
}
} | 0 | Kotlin | 1 | 3 | 7ef6d01ade6cfeb96935d6430a1a404bd67ae54e | 5,763 | howling-wolf-api | MIT License |
compiler/testData/diagnostics/nativeTests/specialBackendChecks/objCInterop/t33.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FIR_IDENTICAL
// WITH_PLATFORM_LIBS
import kotlinx.cinterop.*
import platform.darwin.*
import platform.Foundation.*
class Zzz : NSString {
<!CONSTRUCTOR_OVERRIDES_ALREADY_OVERRIDDEN_OBJC_INITIALIZER!>@OptIn(kotlinx.cinterop.BetaInteropApi::class)
@OverrideInit
constructor(coder: NSCoder) { }<!>
@Suppress("OVERRIDE_DEPRECATION")
override fun initWithCoder(coder: NSCoder): String? = "zzz"
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 417 | kotlin | Apache License 2.0 |
idea/testData/findUsages/kotlin/findClassUsages/kotlinNestedClassAllUsages.1.kt | android | 263,405,600 | true | null | package b
import a.Outer
public class X(bar: String? = Outer.A.bar): Outer.A() {
var next: Outer.A? = Outer.A()
val myBar: String? = Outer.A.bar
init {
Outer.A.bar = ""
Outer.A.foo()
}
fun foo(a: Outer.A) {
val aa: Outer.A = a
aa.bar = ""
}
fun getNext(): Outer.A? {
return next
}
public override fun foo() {
super<Outer.A>.foo()
}
companion object: Outer.A() {
}
}
object O: Outer.A() {
}
fun X.bar(a: Outer.A = Outer.A()) {
}
fun Any.toA(): Outer.A? {
return if (this is Outer.A) this as Outer.A else null
} | 17 | Kotlin | 65 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 622 | kotlin | Apache License 2.0 |
intellij.tools.ide.starter/src/com/intellij/ide/starter/golang.kt | JetBrains | 499,194,001 | false | {"Kotlin": 426021, "C++": 3610, "Makefile": 713} | package com.intellij.ide.starter
import com.intellij.ide.starter.path.GlobalPaths
import com.intellij.openapi.util.SystemInfo
import com.intellij.ide.starter.utils.FileSystem
import com.intellij.ide.starter.utils.HttpClient
import java.nio.file.Path
fun downloadGoSdk(version: String): Path {
val os = when {
SystemInfo.isWindows -> "windows"
SystemInfo.isLinux -> "linux"
SystemInfo.isMac -> "darwin"
else -> error("Unknown OS")
}
val arch = if (SystemInfo.isAarch64) "arm64" else "amd64"
val extension = if (SystemInfo.isWindows) ".zip" else ".tar.gz"
val sdkFileName = "go$version.$os-$arch$extension"
val url = "https://cache-redirector.jetbrains.com/dl.google.com/go/$sdkFileName"
val dirToDownload = GlobalPaths.instance.getCacheDirectoryFor("go-sdk/$version")
val downloadedFile = dirToDownload.resolve(sdkFileName)
val goRoot = dirToDownload.resolve("go-roots")
if (goRoot.toFile().exists()) {
return goRoot.resolve("go")
}
HttpClient.download(url, downloadedFile)
FileSystem.unpack(downloadedFile, goRoot)
return goRoot.resolve("go")
} | 0 | Kotlin | 2 | 8 | 79dad83d28351750817d8e0c49ec516941b7c248 | 1,095 | intellij-ide-starter | Apache License 2.0 |
analysis/analysis-api-standalone/tests/org/jetbrains/kotlin/analysis/api/standalone/fir/test/configurators/AnalysisApiFirStandaloneModeTestConfiguratorFactory.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.api.standalone.fir.test.configurators
import org.jetbrains.kotlin.analysis.test.framework.test.configurators.*
object AnalysisApiFirStandaloneModeTestConfiguratorFactory : AnalysisApiTestConfiguratorFactory() {
override fun createConfigurator(data: AnalysisApiTestConfiguratorFactoryData): AnalysisApiTestConfigurator {
requireSupported(data)
return when (data.moduleKind) {
TestModuleKind.Source -> when (data.analysisSessionMode) {
AnalysisSessionMode.Normal -> StandaloneModeConfigurator
AnalysisSessionMode.Dependent -> unsupportedModeError(data)
}
TestModuleKind.LibraryBinary -> when (data.analysisSessionMode) {
AnalysisSessionMode.Normal -> StandaloneModeLibraryBinaryTestConfigurator
AnalysisSessionMode.Dependent -> unsupportedModeError(data)
}
else -> {
unsupportedModeError(data)
}
}
}
override fun supportMode(data: AnalysisApiTestConfiguratorFactoryData): Boolean {
return when {
data.frontend != FrontendKind.Fir -> false
data.analysisSessionMode != AnalysisSessionMode.Normal -> false
data.analysisApiMode != AnalysisApiMode.Standalone -> false
else -> when (data.moduleKind) {
TestModuleKind.Source,
TestModuleKind.LibraryBinary,
-> true
TestModuleKind.ScriptSource,
TestModuleKind.LibrarySource
-> false
}
}
}
} | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 1,847 | kotlin | Apache License 2.0 |
idea/testData/intentions/addForLoopIndices/explicitParamType.kt | android | 263,405,600 | true | null | // WITH_RUNTIME
fun a() {
val b = listOf(1,2,3,4,5)
for (<caret>c : Int in b) {
}
} | 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 96 | kotlin | Apache License 2.0 |
src/test/kotlin/com/dprint/services/editorservice/process/EditorProcessTest.kt | dprint | 419,904,216 | false | {"Kotlin": 130008} | package com.dprint.services.editorservice.process
import com.dprint.config.UserConfiguration
import com.dprint.utils.getValidConfigPath
import com.dprint.utils.getValidExecutablePath
import com.dprint.utils.infoLogWithConsole
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.openapi.project.Project
import io.kotest.core.spec.style.FunSpec
import io.mockk.EqMatcher
import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkConstructor
import io.mockk.mockkStatic
import io.mockk.verify
import java.io.File
import java.util.concurrent.CompletableFuture
class EditorProcessTest : FunSpec({
mockkStatic(ProcessHandle::current)
mockkStatic(::infoLogWithConsole)
mockkStatic("com.dprint.utils.FileUtilsKt")
val project = mockk<Project>()
val processHandle = mockk<ProcessHandle>()
val process = mockk<Process>()
val userConfig = mockk<UserConfiguration>()
val editorProcess = EditorProcess(project, userConfig)
beforeEach {
every { infoLogWithConsole(any(), project, any()) } returns Unit
}
afterEach {
clearAllMocks()
}
test("it creates a process with the correct args") {
val execPath = "/bin/dprint"
val configPath = "./dprint.json"
val workingDir = "/working/dir"
val parentProcessId = 1L
mockkConstructor(GeneralCommandLine::class)
mockkConstructor(File::class)
mockkConstructor(StdErrListener::class)
every { getValidExecutablePath(project) } returns execPath
every { getValidConfigPath(project) } returns configPath
every { ProcessHandle.current() } returns processHandle
every { processHandle.pid() } returns parentProcessId
every { userConfig.state } returns UserConfiguration.State()
every { constructedWith<File>(EqMatcher(configPath)).parent } returns workingDir
every { process.pid() } returns 2L
every { process.onExit() } returns CompletableFuture.completedFuture(process)
every { anyConstructed<StdErrListener>().listen() } returns Unit
val expectedArgs =
listOf(
execPath,
"editor-service",
"--config",
configPath,
"--parent-pid",
parentProcessId.toString(),
"--verbose",
)
// This essentially tests the correct args are passed in.
every { constructedWith<GeneralCommandLine>(EqMatcher(expectedArgs)).createProcess() } returns process
editorProcess.initialize()
verify(
exactly = 1,
) { constructedWith<GeneralCommandLine>(EqMatcher(expectedArgs)).withWorkDirectory(workingDir) }
verify(exactly = 1) { constructedWith<GeneralCommandLine>(EqMatcher(expectedArgs)).createProcess() }
}
})
| 4 | Kotlin | 2 | 7 | 191ab01e4eb5b0fa941c6f807ccf40915d007257 | 2,889 | dprint-intellij | MIT License |
src/main/kotlin/app/quiz/images/ImageRepository.kt | waterlink | 150,397,627 | false | null | package app.quiz.images
interface ImageRepository {
fun upload(image: ByteArray): String
}
| 13 | Kotlin | 3 | 10 | e4968ba369ce40258e9d3c069d918430fef015c0 | 96 | kotlin-spring-boot-mvc-starter | MIT License |
app/src/main/java/com/davismiyashiro/expenses/model/localrepo/TabDbSchema.kt | DavisJP | 109,140,022 | false | null | /*
* MIT License
*
* Copyright (c) 2019 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.davismiyashiro.expenses.model.localrepo
/**
* Class that defines the tables attributes
*/
class TabDbSchema {
object TabTable {
const val TABLE_NAME = "tabs"
const val UUID = "uuid"
const val GROUPNAME = "groupName"
}
object ParticipantTable {
const val TABLE_NAME = "participants"
const val UUID = "uuid"
const val NAME = "name"
const val EMAIL = "email"
const val NUMBER = "number"
const val TAB_ID = "tab_id"
}
object ExpenseTable {
const val TABLE_NAME = "expenses"
const val UUID = "uuid"
const val DESCRIPTION = "description"
const val VALUE = "value"
const val TAB_ID = "tab_id"
}
object SplitTable {
const val TABLE_NAME = "splits"
const val UUID = "uuid"
const val PARTICIPANT_ID = "participantId"
const val EXPENSE_ID = "expenseId"
const val SPLIT_VAL = "valueByParticipant"
const val TAB_ID = "tabId"
}
}
| 0 | Kotlin | 0 | 0 | e88daf146151fa7ff3d2d4cc0a378af480dc48aa | 2,164 | Expenses | MIT License |
imagepicker/src/main/java/com/shz/imagepicker/imagepicker/model/PickedResult.kt | ShiftHackZ | 418,227,897 | false | {"Kotlin": 61367} | package com.shz.imagepicker.imagepicker.model
import java.io.Serializable
import com.shz.imagepicker.imagepicker.ImagePickerCallback
/**
* Describes all available business logic pick-operation result.
*
* Implements [Serializable].
*
* @see ImagePickerCallback
*/
sealed class PickedResult : Serializable {
/**
* Member of [PickedResult].
* Determines that nothing was selected during pick-operation.
*/
object Empty : PickedResult()
/**
* Member of [PickedResult].
* Determines that only one image was selected during pick-operation.
*
* @param image instance of selected [PickedImage].
*
* @see PickedImage
*/
data class Single(val image: PickedImage) : PickedResult()
/**
* Member of [PickedResult].
* Determines that only multiple images were selected during pick-operation.
*
* @param images collection of selected [PickedImage].
*
* @see PickedImage
*/
data class Multiple(val images: List<PickedImage>) : PickedResult()
/**
* Member of [PickedResult].
* Determines that some error occurred during pick-operation.
*
* @param throwable issue that happened with operation.
*
* @see Throwable
*/
data class Error(val throwable: Throwable) : PickedResult()
}
| 0 | Kotlin | 4 | 8 | 5fff8486c1dc3c4a6ad4a60bdb9505593f9f980c | 1,324 | ImagePicker | Apache License 2.0 |
ktor-client/ktor-client-java/build.gradle.kts | ddadon10 | 378,281,313 | true | {"Kotlin": 5244117, "Python": 948, "JavaScript": 775, "HTML": 88, "Mustache": 77} | val coroutines_version: String by project.extra
kotlin.sourceSets {
val jvmMain by getting {
dependencies {
api(project(":ktor-client:ktor-client-core"))
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:$coroutines_version")
}
}
val jvmTest by getting {
dependencies {
api(project(":ktor-client:ktor-client-tests"))
}
}
}
| 6 | null | 1 | 1 | 425fc32d020317f6b6b8aa30f2182904270919ec | 420 | ktor | Apache License 2.0 |
app/src/main/kotlin/com/rayfantasy/icode/model/ICodeTheme.kt | RayFantasyStudio | 50,503,759 | false | null | /*
* Copyright 2016 <NAME> aka. ztc1997
*
* 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.rayfantasy.icode.model
import android.content.Context
import android.databinding.ObservableInt
import com.rayfantasy.icode.R
import com.rayfantasy.icode.extension.colorAnim
import org.jetbrains.anko.defaultSharedPreferences
object ICodeTheme {
const val PREF_ICODE_THEME = "pref_icode_theme"
const val THEME_BLUE = 0
const val THEME_RED = 1
const val THEME_PURPLE = 2
const val THEME_GRAY = 3
const val THEME_YELLOW = 4
const val THEME_DEEPBLUE = 5
const val THEME_DEFAULT = THEME_RED
internal val colorPrimaryRes = intArrayOf(R.color.colorPrimary_blue, R.color.colorPrimary_red,
R.color.colorPrimary_purple, R.color.colorPrimary_gray, R.color.colorPrimary_yellow, R.color.colorPrimary_deepblue)
internal val colorPrimaryDarkRes = intArrayOf(R.color.colorPrimaryDark_blue, R.color.colorPrimaryDark_red,
R.color.colorPrimaryDark_purple, R.color.colorPrimaryDark_gray, R.color.colorPrimaryDark_yellow, R.color.colorPrimaryDark_deepblue)
internal val colorAccentRes = intArrayOf(R.color.colorAccent_blue, R.color.colorAccent_red,
R.color.colorAccent_purple, R.color.colorAccent_gray, R.color.colorAccent_yellow, R.color.colorAccent_deepblue)
internal val colorHighLightRes = intArrayOf(R.color.high_light_blue, R.color.high_light_red,
R.color.high_light_purple, R.color.high_light_gray, R.color.high_light_yellow, R.color.high_light_deepblue)
fun init(ctx: Context) {
val theme = ctx.defaultSharedPreferences.getInt(PREF_ICODE_THEME, THEME_DEFAULT)
ctx.changeTheme(theme)
}
val colorPrimary = ObservableInt()
val colorPrimaryDark = ObservableInt()
val colorAccent = ObservableInt()
val colorHighLight = ObservableInt()
val icon = ObservableInt()
}
fun Context.changeTheme(theme: Int) = with(ICodeTheme) {
changeColor(colorPrimary, resources.getColor(colorPrimaryRes[theme]))
changeColor(colorPrimaryDark, resources.getColor(colorPrimaryDarkRes[theme]))
changeColor(colorAccent, resources.getColor(colorAccentRes[theme]))
changeColor(colorHighLight, resources.getColor(colorHighLightRes[theme]))
defaultSharedPreferences.edit().putInt(PREF_ICODE_THEME, theme).apply()
}
private fun changeColor(observableInt: ObservableInt, color: Int) {
val i = observableInt.get()
if (i == color) return
if (i != 0) {
colorAnim(i, color, 300, { observableInt.set(it) })
} else
observableInt.set(color)
}
| 6 | Kotlin | 7 | 12 | 9751ec05a22f333e66cb0dccb013108127320f58 | 3,116 | iCode-Android | Apache License 2.0 |
src/test/java/tech/sirwellington/cs/MainTest.kt | SirWellington | 172,366,874 | false | {"Java": 9509, "Kotlin": 2162} | package tech.sirwellington.cs
import org.junit.runner.RunWith
import tech.sirwellington.alchemy.test.junit.runners.*
@RunWith(AlchemyTestRunner::class)
class MainTest
{
@org.junit.Before
fun setup()
{
}
} | 0 | Java | 0 | 0 | fc8e2c3850eaaf6d5db042471f6588f281bf5ff3 | 224 | CS-Fundamentals | MIT License |
app/src/main/java/com/dkmkknub/villtech/component/PostingField.kt | fahmigutawan | 510,392,118 | false | {"Kotlin": 197257} | package com.dkmkknub.villtech.component
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.ub.villtech.R
import com.dkmkknub.villtech.rootViewModel
import com.dkmkknub.villtech.ui.theme.Dark
import com.dkmkknub.villtech.ui.theme.GreenMint
import com.dkmkknub.villtech.ui.theme.Light
import com.dkmkknub.villtech.ui.theme.Typography
import com.dkmkknub.villtech.utils.LoginChecker
import com.dkmkknub.villtech.viewmodel.AdminHomeViewModel
import org.koin.androidx.compose.get
import org.koin.androidx.compose.getViewModel
@Composable
fun PostingTextField(
modifier: Modifier = Modifier,
titleValueState: MutableState<String>,
descriptionValueState: MutableState<String>
) {
val viewModel = getViewModel<AdminHomeViewModel>()
val context = LocalContext.current
val loginChecker = get<LoginChecker>()
val vidPicker = rememberLauncherForActivityResult(
contract = ActivityResultContracts.GetContent(),
onResult = {
if (it != null) {
if (viewModel.isVideoIsFit(context, it)) {
viewModel.videoUri = it
if (viewModel.videoUri != null) {
viewModel.uploadVideoEnabled = false
viewModel.uploadPhotoEnabled = false
viewModel.uploadPhotoColor = Color.Gray
viewModel.uploadVideoColor = Color.Gray
} else {
viewModel.uploadVideoEnabled = true
viewModel.uploadPhotoEnabled = true
viewModel.uploadPhotoColor = Dark
viewModel.uploadVideoColor = Dark
}
} else {
rootViewModel.showSnackbar("Gagal. Pastikan Ukuran File Di bawah 250MB")
}
}
}
)
val imgPicker = rememberLauncherForActivityResult(
contract = ActivityResultContracts.GetMultipleContents(),
onResult = {
it.forEach { uri ->
viewModel.photoUri.add(uri)
}
if (viewModel.photoUri.isNotEmpty()) {
viewModel.uploadVideoEnabled = false
viewModel.uploadVideoColor = Color.Gray
} else {
viewModel.uploadVideoEnabled = true
viewModel.uploadPhotoEnabled = true
viewModel.uploadPhotoColor = Dark
viewModel.uploadVideoColor = Dark
}
})
//Composable
val profilePictureWidth = LocalConfiguration.current.screenWidthDp / 7
val imageWithProfilePicture: @Composable () -> Unit = {
AsyncImage(
modifier = Modifier
.size(profilePictureWidth.dp)
.clip(CircleShape),
model = loginChecker.adminInfo.image_url,
contentDescription = "PROFILE PICTURE"
)
}
val imageWithNoPicture: @Composable () -> Unit = {
AsyncImage(
modifier = Modifier
.size(profilePictureWidth.dp)
.clip(CircleShape),
model = R.drawable.ic_no_picture,
contentDescription = "PROFILE PICTURE"
)
}
/**CONTENT*/
LazyColumn(modifier = Modifier, horizontalAlignment = Alignment.CenterHorizontally) {
/**PREVIEW*/
item {
//IF VIDEO
if (viewModel.videoUri != null)
AdminPostingMediaPreviewVideo(
uri = viewModel.videoUri!!,
modifier = Modifier.padding(start = 16.dp, end = 16.dp)
)
else if (viewModel.photoUri.isNotEmpty()) {
Box(
modifier = Modifier
.fillMaxWidth()
.padding(start = 16.dp, end = 16.dp),
contentAlignment = Alignment.BottomCenter
) {
LazyRow(horizontalArrangement = Arrangement.Center) {
items(viewModel.photoUri) { uri ->
AdminPostingMediaPreviewImage(
modifier = Modifier.padding(end = 8.dp),
uri = uri
)
}
}
}
} else {
/**DO SOMETHING WHEN NO MEDIA PICKED*/
/**DO SOMETHING WHEN NO MEDIA PICKED*/
}
}
/**TITLE*/
item {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
//Profile picture
if (loginChecker.adminInfo.image_url != "null") imageWithProfilePicture()
else imageWithNoPicture()
//Space 16dp
Spacer(modifier = Modifier.width(16.dp))
//Title field
OutlinedTextField(
value = titleValueState.value,
onValueChange = { titleValueState.value = it },
shape = RoundedCornerShape(CornerSize(14.dp)),
colors = TextFieldDefaults
.outlinedTextFieldColors(
textColor = Dark,
backgroundColor = Light,
focusedBorderColor = Dark,
unfocusedBorderColor = Dark
),
placeholder = { Text(text = "Tulis judul di sini...", color = Color.Gray) }
)
}
}
/**DESCRIPTION*/
item {
Card(
modifier = modifier
.padding(start = 16.dp, end = 16.dp)
.fillMaxWidth(),
shape = RoundedCornerShape(CornerSize(14.dp)),
border = BorderStroke(width = 1.dp, color = Color.DarkGray)
) {
Column(
modifier = modifier
.padding(8.dp)
) {
/**Select media buttons*/
/**Select media buttons*/
/**Select media buttons*/
/**Select media buttons*/
/**Select media buttons*/
/**Select media buttons*/
/**Select media buttons*/
/**Select media buttons*/
Row(verticalAlignment = Alignment.CenterVertically) {
//Image
IconButton(
onClick = { imgPicker.launch("image/jpeg") },
enabled = viewModel.uploadPhotoEnabled
) {
Icon(
painter = painterResource(id = R.drawable.ic_add_image),
contentDescription = "Photo",
tint = viewModel.uploadPhotoColor
)
}
//Video
IconButton(
onClick = { vidPicker.launch("video/mp4") },
enabled = viewModel.uploadVideoEnabled
) {
Icon(
painter = painterResource(id = R.drawable.ic_add_video),
contentDescription = "Video",
tint = viewModel.uploadVideoColor
)
}
}
/**TextField*/
/**TextField*/
/**TextField*/
/**TextField*/
/**TextField*/
/**TextField*/
/**TextField*/
/**TextField*/
BasicTextField(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
value = descriptionValueState.value,
onValueChange = { descriptionValueState.value = it },
decorationBox = { innerTextField ->
if (descriptionValueState.value == "") {
Text(text = "Tulis deskripsi di sini...", color = Color.Gray)
}
innerTextField()
})
}
}
}
/**FILE CONSTRAINT*/
item {
Column(modifier = Modifier.padding(start = 16.dp, top = 8.dp)) {
Text(
modifier = Modifier.fillMaxWidth(),
text = "* Hanya gunakan file .JPEG atau .MP4",
color = Color.Black,
style = Typography.body2,
textAlign = TextAlign.Start
)
Text(
modifier = Modifier.fillMaxWidth(),
text = "* Untuk .MP4 maksimal sebesar 250 MB",
color = Color.Black,
style = Typography.body2,
textAlign = TextAlign.Start
)
}
}
/**CATEGORY*/
item {
Text(
modifier = Modifier
.fillMaxWidth()
.padding(top = 16.dp, start = 16.dp, end = 16.dp),
textAlign = TextAlign.Start,
text = "Pilih Kategori",
fontFamily = FontFamily(Font(R.font.poppins_semibold)),
color = Dark
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
selected = viewModel.isCategoryInfografisSelected,
onClick = {
if (!viewModel.category.contains("infografis")) {
viewModel.category += "infografis,"
}
viewModel.isCategoryInfografisSelected =
!viewModel.isCategoryInfografisSelected
}
)
Text(text = "Infografis", style = Typography.body2)
}
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
selected = viewModel.isCategoryVideoSelected,
onClick = {
if (!viewModel.category.contains("video")) {
viewModel.category += "video,"
}
viewModel.isCategoryVideoSelected =
!viewModel.isCategoryVideoSelected
}
)
Text(text = "Video", style = Typography.body2)
}
}
/**UPLOAD PROGRESS*/
item {
LinearProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
.height(5.dp),
progress = viewModel.uploadProgress.toFloat(),
color = GreenMint
)
}
/**BUTTON*/
item {
val loginChecker = get<LoginChecker>()
Spacer(modifier = Modifier.height(8.dp))
GreenButton(
onClick = { uploadContent(viewModel, loginChecker) },
text = "Upload",
enabled = viewModel.isUploadButtonEnabled
)
}
}
}
private fun uploadContent(viewModel: AdminHomeViewModel, loginChecker: LoginChecker) {
val isVideoUriNotNull = viewModel.videoUri != null
val isPhotoUriNotEmpty = viewModel.photoUri.isNotEmpty()
val onFailed: () -> Unit = { rootViewModel.showSnackbar("Terjadi kesalahan coba lagi nanti") }
val onMediaJpegUploaded: (Int) -> Unit = { contentId ->
viewModel.uploadPostWithImage(
contentId = contentId,
loginChecker = loginChecker,
onSuccess = {
rootViewModel.showSnackbar("Postingan berhasil diupload")
viewModel.resetPostData()
viewModel.updateCount(contentId)
},
onFailed = onFailed
)
}
val onMediaVideoUploaded: (Int) -> Unit = { contentId ->
viewModel.uploadPostWithVideo(
contentId = contentId,
loginChecker = loginChecker,
onSuccess = {
rootViewModel.showSnackbar("Postingan berhasil diupload")
viewModel.resetPostData()
viewModel.updateCount(contentId)
},
onFailed = onFailed
)
}
val onCountRetrieved: (Int) -> Unit = { contentId ->
if(viewModel.isDataNotFulfilled()) {
rootViewModel.showSnackbar("Harap isi semua data!")
}else{
if (isVideoUriNotNull) {
viewModel.uploadMp4(
contentId = contentId,
onSuccess = { onMediaVideoUploaded(contentId) },
onFailed = onFailed
)
}
else if (isPhotoUriNotEmpty) {
viewModel.uploadJpeg(
contentId = contentId,
onSuccess = { onMediaJpegUploaded(contentId) },
onFailed = onFailed
)
}
else {
rootViewModel.showSnackbar("Harap pilih Gambar atau Video terlebih dahulu")
}
}
}
/**UPLOAD LOGIC START HERE*/
viewModel
.getContentCount()
.addOnSuccessListener {
val count = if(it.value.toString()=="null") 0 else Integer.parseInt(it.value.toString())
onCountRetrieved(count + 1)
}.addOnFailureListener {
onFailed()
}
} | 0 | Kotlin | 0 | 0 | 899205eef1d12aa40a04a0603d4b4af0540e2673 | 15,439 | Jetpack-VillTech | MIT License |
core/descriptors/src/org/jetbrains/kotlin/resolve/sam/SamConstructorDescriptor.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.resolve.sam
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.SimpleFunctionDescriptor
import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl
import org.jetbrains.kotlin.descriptors.synthetic.FunctionInterfaceConstructorDescriptor
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindExclude
interface SamConstructorDescriptor : SimpleFunctionDescriptor, FunctionInterfaceConstructorDescriptor {
fun getSingleAbstractMethod(): CallableMemberDescriptor
}
class SamConstructorDescriptorImpl(
containingDeclaration: DeclarationDescriptor,
private val samInterface: ClassDescriptor
) : SimpleFunctionDescriptorImpl(
containingDeclaration,
null,
samInterface.annotations,
samInterface.name,
CallableMemberDescriptor.Kind.SYNTHESIZED,
samInterface.source
), SamConstructorDescriptor {
override val baseDescriptorForSynthetic: ClassDescriptor
get() = samInterface
override fun getSingleAbstractMethod(): CallableMemberDescriptor =
getAbstractMembers(samInterface).single()
}
object SamConstructorDescriptorKindExclude : DescriptorKindExclude() {
override fun excludes(descriptor: DeclarationDescriptor) = descriptor is SamConstructorDescriptor
override val fullyExcludedDescriptorKinds: Int get() = 0
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 1,705 | kotlin | Apache License 2.0 |
app/src/main/java/com/agenda/up/listeners/telamain/VerificarCurrentUser.kt | Araujo-Alisson | 596,383,449 | false | null | package com.agenda.up.listeners.telamain
interface VerificarCurrentUser {
fun onSucesso()
fun onFailure()
}
| 1 | Kotlin | 0 | 0 | 1a74801e3a82982d024fb85defa664396ade2eb9 | 125 | Up | Apache License 2.0 |
src/main/kotlin/com/kotlinHSE/sergey/tinkoff_api/schemas/Candles.kt | SergeyHSE7 | 333,788,653 | false | null | package com.kotlinHSE.sergey.tinkoff_api.schemas
import kotlinx.serialization.Serializable
@Serializable
data class Candles(
val figi: String,
val interval: String,
val candles: Array<Candle>
)
| 0 | Kotlin | 0 | 0 | 97c3e66ed96e70f54c7cdaadf60ae810e840b191 | 220 | kotlin_fin-assistant | Apache License 2.0 |
src/test/java/com/kimen/Tester.kt | Kimentanm | 331,475,192 | false | {"Vue": 23918, "JavaScript": 16804, "Kotlin": 15560, "HTML": 804, "Dockerfile": 677, "Java": 592, "Shell": 180} | package com.kimen
import org.junit.runner.RunWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.annotation.Rollback
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
@SpringBootTest
@Rollback
abstract class Tester {
} | 0 | Vue | 2 | 2 | 75e4015c5b2d03fba83415250ff0cb7ee418f5f6 | 305 | whale-photos | MIT License |
compiler/fir/analysis-tests/testData/resolveWithStdlib/functionAndFunctionN.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | fun takeAnyFun(function: Function<*>) {}
fun test(block: () -> Unit) {
takeAnyFun(block)
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 96 | kotlin | Apache License 2.0 |
app/src/main/java/com/newsapp/models/news/Article.kt | Anasmirza20 | 428,017,744 | false | {"Kotlin": 26961} | package com.newsapp.models.news
data class Article(
val author: String,
val content: String?,
val description: String?,
val publishedAt: String,
val source: Source,
val title: String,
val url: String?,
val urlToImage: String?,
var isAlreadyLike: Boolean = false,
var isAlreadyDislike: Boolean = false,
) | 0 | Kotlin | 0 | 0 | c6314f04244aa638321b836d8208c2731a612c1d | 344 | News-App | Apache License 2.0 |
compiler/testData/diagnostics/tests/modifiers/annotations.fir.kt | android | 263,405,600 | true | null | annotation class My(
public val x: Int,
protected val y: Int,
internal val z: Int,
private val w: Int
)
open class Your {
open val x: Int = 0
}
annotation class His(override val x: Int): Your() | 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 215 | kotlin | Apache License 2.0 |
RateBottomSheet/app/src/main/java/com/timac/ratebottomsheet/MainActivity.kt | HenryMacharia254 | 327,206,499 | false | {"Kotlin": 23971} | package com.timac.ratebottomsheet
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.mikhaellopez.ratebottomsheet.AskRateBottomSheet
import com.mikhaellopez.ratebottomsheet.RateBottomSheet
import com.mikhaellopez.ratebottomsheet.RateBottomSheetManager
import com.timac.ratebottomsheet.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btnRateMe.setOnClickListener {
showRateBottomSheet()
}
}
private fun showRateBottomSheet() {
RateBottomSheetManager(this)
.setInstallDays(1) // 3 by default
.setLaunchTimes(2) // 5 by default
.setRemindInterval(1) // 2 by default
.setShowAskBottomSheet(true) // True by default
.setShowLaterButton(true) // True by default
.setShowCloseButtonIcon(true) // True by default
.setDebugForceOpenEnable(true) // to show bottom sheet without conditions check. False by Default
.monitor()
// Show bottom sheet if meets conditions
// With AppCompatActivity or Fragment
RateBottomSheet.showRateBottomSheetIfMeetsConditions(this, // Optional Listeners after context
listener = object : AskRateBottomSheet.ActionListener {
override fun onDislikeClickListener() {
Toast.makeText(this@MainActivity, "OnDislike", Toast.LENGTH_SHORT).show()
}
override fun onRateClickListener() {
Toast.makeText(this@MainActivity, "onRate", Toast.LENGTH_SHORT).show()
}
override fun onNoClickListener() {
Toast.makeText(this@MainActivity, "onNoClick", Toast.LENGTH_SHORT).show()
}
})
}
} | 0 | Kotlin | 0 | 0 | e69d7b4f9bbf62fb9b7d84ef5e084544e7448c28 | 2,201 | Android-UI--Implementations | MIT License |
sphinx/screens-detail/contact/edit-contact/src/main/java/chat/sphinx/edit_contact/ui/EditContactFragment.kt | stakwork | 340,103,148 | false | {"Kotlin": 4002503, "Java": 403469, "JavaScript": 4745, "HTML": 4706, "Shell": 2453} | package chat.sphinx.edit_contact.ui
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import by.kirich1409.viewbindingdelegate.viewBinding
import chat.sphinx.concept_user_colors_helper.UserColorsHelper
import chat.sphinx.contact.databinding.LayoutContactBinding
import chat.sphinx.contact.databinding.LayoutContactDetailScreenHeaderBinding
import chat.sphinx.contact.databinding.LayoutContactSaveBinding
import chat.sphinx.contact.ui.ContactFragment
import chat.sphinx.edit_contact.R
import chat.sphinx.edit_contact.databinding.FragmentEditContactBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.inject.Inject
@AndroidEntryPoint
internal class EditContactFragment : ContactFragment<
FragmentEditContactBinding,
EditContactFragmentArgs,
EditContactViewModel
>(R.layout.fragment_edit_contact)
{
@Inject
lateinit var userColorsHelperInj: UserColorsHelper
override val userColorsHelper: UserColorsHelper
get() = userColorsHelperInj
override val viewModel: EditContactViewModel by viewModels()
override val binding: FragmentEditContactBinding by viewBinding(FragmentEditContactBinding::bind)
override val headerBinding: LayoutContactDetailScreenHeaderBinding by viewBinding(
LayoutContactDetailScreenHeaderBinding::bind, R.id.include_edit_contact_header
)
override val contactBinding: LayoutContactBinding by viewBinding(
LayoutContactBinding::bind, R.id.include_edit_contact_layout
)
override val contactSaveBinding: LayoutContactSaveBinding by viewBinding(
LayoutContactSaveBinding::bind, R.id.include_edit_contact_layout_save
)
override fun getHeaderText(): String = getString(R.string.edit_contact_header_name)
override fun getSaveButtonText(): String = getString(R.string.save_contact_button)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
headerBinding.apply {
textViewDetailScreenSubscribe.setOnClickListener {
lifecycleScope.launch(viewModel.mainImmediate) {
viewModel.toSubscriptionDetailScreen()
}
}
}
}
}
| 96 | Kotlin | 8 | 18 | 4fd9556a4a34f14126681535558fe1e39747b323 | 2,345 | sphinx-kotlin | MIT License |
src/test/kotlin/io/github/trustedshops_public/spring_boot_starter_keycloak_path_based_resolver/keycloak/NoPathMatcherExceptionTest.kt | trustedshops-public | 524,078,409 | false | {"Kotlin": 22803} | package io.github.trustedshops_public.spring_boot_starter_keycloak_path_based_resolver.keycloak
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
class NoPathMatcherExceptionTest {
@Test
fun `Verify that error message can be built`() {
assertEquals(
NoPathMatcherException(DummyFacadeRequest("/test")).message,
"No path configured for request path '/test'"
)
}
}
| 2 | Kotlin | 0 | 0 | 451885d836f596ae1423b78d9a7a873552b42e18 | 443 | spring-boot-starter-keycloak-path-based-resolver | MIT License |
src/commonMain/kotlin/de/tfr/game/util/Timer.kt | TobseF | 172,265,691 | false | {"Kotlin": 34687, "Shell": 1210} | package de.tfr.game.util
class Timer(var actionTime: Double, private val timerAction: () -> Unit) : Time {
override var time = 0.0
private var pause = false
fun update(deltaTime: Double) {
time += deltaTime
if (!pause && time >= actionTime) {
time = 0.0
timerAction.invoke()
}
}
fun togglePause() {
pause = !pause
}
fun reset() {
time = 0.0
}
}
| 1 | Kotlin | 5 | 24 | a378d865d06ddd7455343ee899b0531565b2f768 | 448 | HitKlack | MIT License |
app/src/main/kotlin/io/orangebuffalo/simpleaccounting/domain/documents/storage/noop/NoopDocumentsStorage.kt | orange-buffalo | 154,902,725 | false | {"Kotlin": 915625, "TypeScript": 536700, "Vue": 256779, "SCSS": 30586, "JavaScript": 6806, "HTML": 633, "CSS": 10} | package io.orangebuffalo.simpleaccounting.domain.documents.storage.noop
import io.orangebuffalo.simpleaccounting.domain.documents.storage.DocumentsStorage
import io.orangebuffalo.simpleaccounting.domain.documents.storage.DocumentsStorageStatus
import io.orangebuffalo.simpleaccounting.domain.documents.storage.SaveDocumentRequest
import io.orangebuffalo.simpleaccounting.domain.documents.storage.SaveDocumentResponse
import io.orangebuffalo.simpleaccounting.services.persistence.entities.Workspace
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.reactive.asFlow
import org.springframework.core.io.buffer.DataBuffer
import org.springframework.core.io.buffer.DataBufferUtils
import org.springframework.core.io.buffer.DefaultDataBufferFactory
import org.springframework.security.util.InMemoryResource
import org.springframework.stereotype.Service
import java.util.concurrent.ThreadLocalRandom
import kotlin.math.max
@Service
class NoopDocumentsStorage : DocumentsStorage {
private val bufferFactory = DefaultDataBufferFactory()
override suspend fun saveDocument(request: SaveDocumentRequest): SaveDocumentResponse {
val filename = request.fileName
if (filename.contains("fail")) {
throw RuntimeException("Upload failed")
}
return SaveDocumentResponse(filename, getFakeContent(filename).contentLength())
}
private fun getFakeContent(filename:String) : InMemoryResource {
return InMemoryResource(
"START-// ${filename.repeat(
ThreadLocalRandom.current().nextInt(20_000, 30_000)
)} //-END"
)
}
override fun getId(): String = "noop"
override suspend fun getDocumentContent(workspace: Workspace, storageLocation: String): Flow<DataBuffer> {
val resource = getFakeContent(storageLocation)
val contentLength = resource.contentLength()
val bufferSize = max(1, contentLength / 30)
return DataBufferUtils
.read(
resource,
bufferFactory,
bufferSize.toInt()
)
.asFlow()
// simulate some storage delay
.map { dataBuffer ->
delay(100)
dataBuffer
}
}
override suspend fun getCurrentUserStorageStatus() = DocumentsStorageStatus(true)
}
| 67 | Kotlin | 0 | 1 | bec32d609ecb678203f5ab1afecb9b7e627858ef | 2,426 | simple-accounting | Creative Commons Attribution 3.0 Unported |
the.orm.itest/src/test/kotlin/io/the/orm/test/functional/ExamplesTest.kt | christophsturm | 260,202,802 | false | {"Kotlin": 221994} | package io.the.orm.test.functional
import failgood.Test
import io.the.orm.ConnectedRepo
import io.the.orm.test.DBS
import io.the.orm.test.describeOnAllDbs
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
/** examples for standard use-cases. they run as part of the test suite to make sure they work. */
@Test
object ExamplesTest {
val context =
describeOnAllDbs("examples", DBS.databases, USERS_SCHEMA) { connectionProvider ->
test("throttled bulk inserts") {
val user = User(name = "a user", email = "with email")
val repo = ConnectedRepo.create<User>(connectionProvider)
val channel = Channel<Deferred<User>>(capacity = 40)
val entries = 1000
coroutineScope {
launch {
connectionProvider.transaction {
repeat(entries) {
channel.send(
async {
repo.create(
user.copy(
email = java.util.UUID.randomUUID().toString()
)
)
}
)
}
}
}
repeat(entries) { channel.receive().await() }
}
}
}
}
| 11 | Kotlin | 0 | 0 | 198962eaa510e50fb0790c147fb88440ed26f587 | 1,677 | the.orm | MIT License |
src/main/kotlin/no/nav/arbeidsgiver/min_side/services/ereg/EregService.kt | navikt | 170,528,339 | false | {"Kotlin": 271228, "Dockerfile": 85} | package no.nav.arbeidsgiver.min_side.services.ereg
import com.fasterxml.jackson.databind.JsonNode
import com.github.benmanes.caffeine.cache.Caffeine
import no.nav.arbeidsgiver.min_side.clients.retryInterceptor
import no.nav.arbeidsgiver.min_side.models.Organisasjon
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.web.client.RestTemplateBuilder
import org.springframework.cache.annotation.Cacheable
import org.springframework.cache.caffeine.CaffeineCache
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Component
import org.springframework.web.client.RestClientResponseException
import java.util.*
@Component
class EregService(
@Value("\${ereg-services.baseUrl}") eregBaseUrl: String?,
restTemplateBuilder: RestTemplateBuilder
) {
private val restTemplate = restTemplateBuilder
.rootUri(eregBaseUrl)
.additionalInterceptors(
retryInterceptor(
3,
250L,
org.apache.http.NoHttpResponseException::class.java,
java.net.SocketException::class.java,
javax.net.ssl.SSLHandshakeException::class.java,
)
)
.build()
@Cacheable(EREG_CACHE_NAME)
fun hentUnderenhet(virksomhetsnummer: String): Organisasjon? {
return try {
val json = restTemplate.getForEntity(
"/v1/organisasjon/{virksomhetsnummer}?inkluderHierarki=true",
JsonNode::class.java,
mapOf("virksomhetsnummer" to virksomhetsnummer)
).body
underenhet(json)
} catch (e: RestClientResponseException) {
if (e.statusCode == HttpStatus.NOT_FOUND) {
return null
}
throw e
}
}
@Cacheable(EREG_CACHE_NAME)
fun hentOverenhet(orgnummer: String): Organisasjon? {
return try {
val json = restTemplate.getForEntity(
"/v1/organisasjon/{orgnummer}",
JsonNode::class.java,
mapOf("orgnummer" to orgnummer)
).body
overenhet(json)
} catch (e: RestClientResponseException) {
if (e.statusCode == HttpStatus.NOT_FOUND) {
return null
}
throw e
}
}
fun underenhet(json: JsonNode?): Organisasjon? {
if (json == null || json.isEmpty) {
return null
}
val juridiskOrgnummer = json.at("/inngaarIJuridiskEnheter/0/organisasjonsnummer").asText()
val orgleddOrgnummer = json.at("/bestaarAvOrganisasjonsledd/0/organisasjonsledd/organisasjonsnummer").asText()
val orgnummerTilOverenhet = orgleddOrgnummer.ifBlank { juridiskOrgnummer }
return Organisasjon(
samletNavn(json),
"Business",
orgnummerTilOverenhet,
json.at("/organisasjonsnummer").asText(),
json.at("/organisasjonDetaljer/enhetstyper/0/enhetstype").asText(),
"Active"
)
}
fun overenhet(json: JsonNode?): Organisasjon? {
return if (json == null) {
null
} else Organisasjon(
samletNavn(json),
"Enterprise",
null,
json.at("/organisasjonsnummer").asText(),
json.at("/organisasjonDetaljer/enhetstyper/0/enhetstype").asText(),
"Active"
)
}
companion object {
private fun samletNavn(json: JsonNode) = listOf(
json.at("/navn/navnelinje1").asText(null),
json.at("/navn/navnelinje2").asText(null),
json.at("/navn/navnelinje3").asText(null),
json.at("/navn/navnelinje4").asText(null),
json.at("/navn/navnelinje5").asText(null)
)
.filter(Objects::nonNull)
.joinToString(" ")
}
}
const val EREG_CACHE_NAME = "ereg_cache"
@Configuration
class EregCacheConfig {
@Bean
fun eregCache() = CaffeineCache(
EREG_CACHE_NAME,
Caffeine.newBuilder()
.maximumSize(600000)
.recordStats()
.build()
)
} | 0 | Kotlin | 0 | 0 | e625f3abc5d915bdbe5aa1861d25e29aabe2dc0e | 4,269 | min-side-arbeidsgiver-api | MIT License |
spigot-core/src/main/kotlin/ru/astrainteractive/astralibs/serialization/KyoriComponentSerializerType.kt | Astra-Interactive | 422,588,271 | false | {"Kotlin": 110093} | package ru.astrainteractive.astralibs.serialization
import kotlinx.serialization.Serializable
@Serializable
enum class KyoriComponentSerializerType {
Json, Gson, Plain, MiniMessage, Legacy
}
| 1 | Kotlin | 0 | 3 | 047f85e57d853166d1aec64ea52e0a956197e711 | 197 | AstraLibs | MIT License |
app/src/main/kotlin/useless/android/app/module/app/Colors.kt | kepocnhh | 543,966,743 | false | {"Kotlin": 34319} | package useless.android.app.module.app
import androidx.compose.runtime.Immutable
import androidx.compose.ui.graphics.Color
@Immutable
internal class Colors private constructor(
val background: Color,
val foreground: Color,
) {
companion object {
val dark = Colors(
background = Color.Black,
foreground = Color.White,
)
val light = Colors(
background = Color.White,
foreground = Color.Black,
)
}
}
| 0 | Kotlin | 0 | 0 | 22c2325164b49a592e027991ed34700073f601fe | 495 | AndroidAppUseless | MIT License |
compiler/testData/diagnostics/tests/generics/wrongNumberOfTypeArgumentsDiagnostic.kt | android | 263,405,600 | true | null | // !WITH_NEW_INFERENCE
// !DIAGNOSTICS: -UNUSED_PARAMETER, -UNUSED_VARIABLE
fun myFun(i : String) {}
fun myFun(i : Int) {}
fun test1() {
<!NI;NONE_APPLICABLE!>myFun<!><!OI;WRONG_NUMBER_OF_TYPE_ARGUMENTS!><Int><!>(3)
<!NONE_APPLICABLE!>myFun<!><String>('a')
}
fun test2() {
val m0 = java.util.<!NI;NEW_INFERENCE_NO_INFORMATION_FOR_PARAMETER, OI;TYPE_INFERENCE_NO_INFORMATION_FOR_PARAMETER!>HashMap<!>()
val m1 = java.util.HashMap<!WRONG_NUMBER_OF_TYPE_ARGUMENTS!><String, String, String><!>()
val m2 = java.util.HashMap<!WRONG_NUMBER_OF_TYPE_ARGUMENTS!><String><!>()
} | 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 590 | kotlin | Apache License 2.0 |
compiler/testData/codegen/box/properties/backingField/independentBackingFieldType.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // TARGET_BACKEND: JVM_IR
// TARGET_BACKEND: JS_IR
// TARGET_BACKEND: JS_IR_ES6
// TARGET_BACKEND: WASM
// IGNORE_BACKEND_K1: JVM_IR, JS_IR, JS_IR_ES6, WASM
fun createString() = "AAA" + "BBB"
class A {
var it: Int
field = 3.14
get() = (field + 10).toInt()
set(value) {
field = (value - 10).toDouble()
if (field < -3 || -1 < field) {
throw Exception("fail: value = $value, field = $field")
}
}
var that: Int
field = createString() + "!"
get() = field.length
set(value) {
field = value.toString()
if (field != "17") {
throw Exception("fail: value = $value, field = $field")
}
}
}
fun box(): String {
try {
val a = A()
val it: Int = A().it and 10
a.it = it
val that: Int = a.that
a.that = that + 10
} catch (e: Exception) {
return e.message ?: "fail"
}
return "OK"
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 1,012 | kotlin | Apache License 2.0 |
android/room/src/main/java/com/example/splitandpay/room/di/RoomModule.kt | timatifey | 718,057,019 | false | {"Kotlin": 116639, "TypeScript": 52420, "Swift": 26466, "CSS": 24361, "HTML": 9914, "JavaScript": 1425, "Dockerfile": 404} | package com.example.splitandpay.room.di
import com.example.splitandpay.room.RoomModelMapper
import com.example.splitandpay.room.RoomViewModel
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
val roomModule = module {
single { RoomModelMapper() }
viewModel {
RoomViewModel(get(), get(), get())
}
} | 0 | Kotlin | 0 | 3 | 3e24e188d15308b67d1eae1169072c67fb11c403 | 345 | split-and-pay | MIT License |
js/js.translator/testData/box/coroutines/dynamicSuspendReturnWithArrayAccess.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // IGNORE_BACKEND: JS
// WITH_STDLIB
// EXPECTED_REACHABLE_NODES: 1292
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
suspend fun foo(): dynamic {
return js("[1, 2, 3]")
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(object : Continuation<Unit> {
override val context = EmptyCoroutineContext
override fun resumeWith(result: Result<Unit>) {}
})
}
fun box(): String {
var result: dynamic = 0
val count = 0;
builder {
result += foo()[count + 0] + foo()[count + 1] * foo()[count + 2]
}
return if (result == 7) "OK" else "fail: the wrong answer. Expect to have 7 but got $result"
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 666 | kotlin | Apache License 2.0 |
mpdomain/src/main/java/com/jpp/mpdomain/usecase/GetCreditsUseCase.kt | perettijuan | 156,444,935 | false | null | package com.jpp.mpdomain.usecase
import com.jpp.mpdomain.CastCharacter
import com.jpp.mpdomain.Connectivity
import com.jpp.mpdomain.Credits
import com.jpp.mpdomain.ImagesConfiguration
import com.jpp.mpdomain.repository.ConfigurationRepository
import com.jpp.mpdomain.repository.ConnectivityRepository
import com.jpp.mpdomain.repository.CreditsRepository
/**
* Use case to retrieve the [Credits] of a particular movie.
*/
class GetCreditsUseCase(
private val creditsRepository: CreditsRepository,
private val configurationRepository: ConfigurationRepository,
private val connectivityRepository: ConnectivityRepository
) {
suspend fun execute(movieId: Double): Try<Credits> {
return when (connectivityRepository.getCurrentConnectivity()) {
is Connectivity.Disconnected -> Try.Failure(Try.FailureCause.NoConnectivity)
is Connectivity.Connected -> creditsRepository.getCreditsForMovie(movieId)
?.let { credits ->
Try.Success(credits.copy(cast = credits.cast.map { character ->
configureCharacterProfilePath(
character
)
}))
} ?: Try.Failure(Try.FailureCause.Unknown)
}
}
private suspend fun configureCharacterProfilePath(castCharacter: CastCharacter): CastCharacter {
return configurationRepository.getAppConfiguration()?.let { appConfiguration ->
castCharacter.configureProfilePath(appConfiguration.images)
} ?: castCharacter
}
private fun CastCharacter.configureProfilePath(imagesConfig: ImagesConfiguration): CastCharacter {
return copy(
profile_path = profile_path.createUrlForPath(
imagesConfig.base_url,
imagesConfig.profile_sizes.last()
)
)
}
}
| 9 | Kotlin | 7 | 46 | 7921806027d5a9b805782ed8c1cad447444f476b | 1,879 | moviespreview | Apache License 2.0 |
app/src/main/java/ru/mail/march/sample/PresenterImpl.kt | mailru | 263,284,417 | false | null | package ru.mail.march.sample
import ru.mail.march.interactor.InteractorObtainer
class PresenterImpl(view: Presenter.View, interactorObtainer: InteractorObtainer): Presenter {
private val interactor = interactorObtainer.obtain(SampleInteractor::class.java) {
SampleInteractor()
}
init {
interactor.errorChannel.observe { view.showError(it) }
interactor.wordChannel.observe { view.showText(it) }
interactor.timeChannel.observe { view.showTime(it) }
}
override fun onButtonClick() {
interactor.request()
}
} | 2 | Kotlin | 1 | 11 | 74522ab9e1cc2b07763a3ee240c727155d45f194 | 572 | March | MIT License |
feature-staking-api/src/main/java/jp/co/soramitsu/feature_staking_api/domain/model/StakingAccount.kt | izhestkov | 346,603,452 | true | {"Kotlin": 1066068} | package jp.co.soramitsu.feature_staking_api.domain.model
import jp.co.soramitsu.core.model.CryptoType
import jp.co.soramitsu.core.model.Network
data class StakingAccount(
val address: String,
val name: String?,
val cryptoType: CryptoType,
val network: Network
) | 0 | null | 0 | 0 | f63b80c711d17b9f07e8632260b69029dea6e517 | 279 | fearless-Android | Apache License 2.0 |
pubsub/src/main/kotlin/glitch/pubsub/events/json/moderation.kt | GlitchLib | 146,582,041 | false | {"Java": 236506, "Kotlin": 125095} | package glitch.pubsub.events.json
import com.google.gson.annotations.JsonAdapter
import com.google.gson.annotations.SerializedName
import glitch.api.objects.json.interfaces.IDObject
import glitch.pubsub.`object`.adapters.ModerationActionAdapter
import java.util.*
/**
*
* @author <NAME> [<EMAIL>]
* @version %I%, %G%
* @since 1.0
*/
data class Timeout(
override val moderatorName: String,
override val moderatorId: Long,
override val targetName: String,
override val targetId: Long,
val duration: Int,
val reason: String?
) : IModerator, ITarget {
constructor(data: ModerationData) : this(
data.createdBy,
data.createdById,
data.args[0],
data.targetId,
data.args[1].toInt(),
if (data.args.size > 2) data.args[2] else null
)
}
data class Ban(
override val moderatorName: String,
override val moderatorId: Long,
override val targetName: String,
override val targetId: Long,
val reason: String?
) : IModerator, ITarget {
constructor(data: ModerationData) : this(
data.createdBy,
data.createdById,
data.args[0],
data.targetId,
if (data.args.size > 1) data.args[1] else null
)
}
data class Host(
override val moderatorName: String,
override val moderatorId: Long,
override val targetName: String,
override val targetId: Long
) : IModerator, ITarget {
constructor(data: ModerationData) : this(
data.createdBy,
data.createdById,
data.args[0],
data.targetId
)
}
data class MessageDelete(
override val id: UUID,
override val moderatorName: String,
override val moderatorId: Long,
override val targetName: String,
override val targetId: Long,
val message: String
) : IDObject<UUID>, IModerator, ITarget {
constructor(data: ModerationData) : this(
UUID.fromString(data.args[2]),
data.createdBy,
data.createdById,
data.args[0],
data.targetId,
data.args[1]
)
}
data class ModerationData(
val type: String,
@JsonAdapter(ModerationActionAdapter::class)
val moderationAction: Action,
val args: List<String>,
val createdBy: String,
@SerializedName("created_by_user_id")
val createdById: Long,
@SerializedName("target_user_id")
val targetId: Long
) {
enum class Action {
TIMEOUT,
BAN,
UNBAN,
UNTIMEOUT,
HOST,
SUBSCRIBERS,
SUBSCRIBERSOFF,
CLEAR,
EMOTEONLY,
EMOTEONLYOFF,
R9KBETA,
R9KBETAOFF,
DELETE
}
}
data class Moderator(
override val moderatorName: String,
override val moderatorId: Long
) : IModerator {
constructor(data: ModerationData) : this(
data.createdBy,
data.createdById
)
}
data class ActivationByMod(
override val moderatorName: String,
override val moderatorId: Long,
@get:SerializedName("active")
val isActive: Boolean
) : IModerator {
constructor(data: ModerationData, isActive: Boolean) : this(
data.createdBy,
data.createdById,
isActive
)
}
data class Unban(
override val moderatorName: String,
override val moderatorId: Long,
override val targetName: String,
override val targetId: Long
) : IModerator, ITarget {
constructor(data: ModerationData) : this(
data.createdBy,
data.createdById,
data.args[0],
data.targetId
)
} | 15 | Java | 3 | 11 | 81283227ee6c3b63866fe1371959a72f8b0d2640 | 3,812 | glitch | MIT License |
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/MusicNote2.kt | Konyaco | 574,321,009 | false | {"Kotlin": 11029508, "Java": 256912} |
package com.konyaco.fluent.icons.regular
import androidx.compose.ui.graphics.vector.ImageVector
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.fluentIcon
import com.konyaco.fluent.icons.fluentPath
public val Icons.Regular.MusicNote2: ImageVector
get() {
if (_musicNote2 != null) {
return _musicNote2!!
}
_musicNote2 = fluentIcon(name = "Regular.MusicNote2") {
fluentPath {
moveTo(19.7f, 2.15f)
curveToRelative(0.19f, 0.14f, 0.3f, 0.36f, 0.3f, 0.6f)
lineTo(20.0f, 16.5f)
arcToRelative(3.5f, 3.5f, 0.0f, true, true, -1.5f, -2.87f)
lineTo(18.5f, 7.76f)
lineTo(10.0f, 10.3f)
verticalLineToRelative(8.19f)
arcToRelative(3.5f, 3.5f, 0.0f, true, true, -1.5f, -2.87f)
lineTo(8.5f, 5.75f)
curveToRelative(0.0f, -0.33f, 0.22f, -0.62f, 0.53f, -0.72f)
lineToRelative(10.0f, -3.0f)
arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.67f, 0.12f)
close()
moveTo(10.0f, 8.75f)
lineToRelative(8.5f, -2.56f)
lineTo(18.5f, 3.76f)
lineTo(10.0f, 6.3f)
verticalLineToRelative(2.43f)
close()
moveTo(6.5f, 16.5f)
arcToRelative(2.0f, 2.0f, 0.0f, true, false, 0.0f, 4.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, 0.0f, -4.0f)
close()
moveTo(14.5f, 16.5f)
arcToRelative(2.0f, 2.0f, 0.0f, true, false, 4.0f, 0.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, -4.0f, 0.0f)
close()
}
}
return _musicNote2!!
}
private var _musicNote2: ImageVector? = null
| 4 | Kotlin | 4 | 155 | 9e86d93bf1f9ca63a93a913c990e95f13d8ede5a | 1,872 | compose-fluent-ui | Apache License 2.0 |
src/main/kotlin/fp/kotlin/example/chapter11/exercise/11_2_writeMonad_gcd.kt | funfunStory | 101,662,895 | false | null | package fp.kotlin.example.chapter11.exercise
import fp.kotlin.example.chapter10.Maybe
import fp.kotlin.example.chapter10.Nothing
import fp.kotlin.example.chapter10.exercise.FunStream
import fp.kotlin.example.chapter10.exercise.funStreamOf
import fp.kotlin.example.chapter11.logging.WriterMonad
/**
*
* 연습문제 11-2
*
* 최대공약수를 구하는 유클리드 알고리즘(Euclidean algorithm)의 동작 로그를 살펴볼 수 있는 함수 ``gcd``를 WriterMonad를 사용해서 만들어보자.
*
* 힌트 : ``gcd(60, 48)``를 호출했을때 아래와 같이 출력되어야 한다.
* [60 mod 48 = 12, 48 mod 12 = 0, Finished with 12]
*
*/
fun main() {
require(gcd(60, 48) == funStreamOf("60 mod 48 = 12", "48 mod 12 = 0", "Finished with 12"))
require(gcd2(60, 48) == funStreamOf("60 mod 48 = 12", "48 mod 12 = 0", "Finished with 12"))
require(gcd(48, 60) == funStreamOf("48 mod 60 = 48", "60 mod 48 = 12", "48 mod 12 = 0", "Finished with 12"))
require(gcd2(48, 60) == funStreamOf("48 mod 60 = 48", "60 mod 48 = 12", "48 mod 12 = 0", "Finished with 12"))
require(gcd(60, 5) == funStreamOf("60 mod 5 = 0", "Finished with 5"))
require(gcd2(60, 5) == funStreamOf("60 mod 5 = 0", "Finished with 5"))
require(gcd(61, 3) == funStreamOf("61 mod 3 = 1", "3 mod 1 = 0", "Finished with 1"))
require(gcd2(61, 3) == funStreamOf("61 mod 3 = 1", "3 mod 1 = 0", "Finished with 1"))
require(gcd(63, 24) == funStreamOf("63 mod 24 = 15", "24 mod 15 = 9", "15 mod 9 = 6", "9 mod 6 = 3", "6 mod 3 = 0",
"Finished with 3"))
require(gcd2(63, 24) == funStreamOf("63 mod 24 = 15", "24 mod 15 = 9", "15 mod 9 = 6", "9 mod 6 = 3", "6 mod 3 = 0",
"Finished with 3"))
}
fun gcd(x: Int, y: Int,
maybeWriteMonad: Maybe<WriterMonad<Pair<Int, Int>>> = Nothing): FunStream<String> = TODO()
fun gcd2(x: Int, y: Int, writeMonad: WriterMonad<Pair<Int, Int>>? = null): FunStream<String> = TODO()
private infix fun <T> T.withLog(log: String): WriterMonad<T> = TODO() | 1 | Kotlin | 23 | 39 | bb10ea01d9f0e1b02b412305940c1bd270093cb6 | 2,014 | fp-kotlin-example | MIT License |
ee-design/src/main/kotlin/ee/design/gen/DesignGeneratorFactory.kt | eugeis | 80,671,314 | false | null | package ee.design.gen
import ee.design.*
import ee.design.gen.go.*
import ee.design.gen.kt.DesignKotlinContextFactory
import ee.design.gen.kt.DesignKotlinTemplates
import ee.design.gen.swagger.DesignSwaggerContextFactory
import ee.design.gen.swagger.DesignSwaggerTemplates
import ee.design.gen.ts.DesignTsContextFactory
import ee.design.gen.ts.DesignTsTemplates
import ee.design.gen.angular.DesignAngularContextFactory
import ee.design.gen.angular.DesignAngularTemplates
import ee.lang.*
import ee.lang.gen.LangGeneratorFactory
import ee.lang.gen.common.LangCommonContextFactory
import ee.lang.gen.go.itemAndTemplateNameAsGoFileName
import ee.lang.gen.go.itemNameAsGoFileName
import ee.lang.gen.itemNameAsKotlinFileName
import ee.lang.gen.swagger.itemNameAsSwaggerFileName
import ee.lang.gen.ts.*
open class DesignGeneratorFactory(targetAsSingleModule: Boolean = true) : LangGeneratorFactory(targetAsSingleModule) {
override fun buildKotlinContextFactory() = DesignKotlinContextFactory(targetAsSingleModule)
override fun buildKotlinTemplates() = DesignKotlinTemplates(itemNameAsKotlinFileName)
override fun buildGoContextFactory() = DesignGoContextFactory(targetAsSingleModule)
override fun buildGoTemplates() = DesignGoTemplates(itemNameAsGoFileName)
override fun buildTsContextFactory() = DesignTsContextFactory()
override fun buildTsTemplates() = DesignTsTemplates(itemNameAsTsFileName)
fun buildAngularContextFactory() = DesignAngularContextFactory()
fun buildAngularTemplates() = DesignAngularTemplates(itemNameAsTsFileName)
override fun buildSwaggerContextFactory() = DesignSwaggerContextFactory()
fun buildSwaggerTemplates() = DesignSwaggerTemplates(itemNameAsSwaggerFileName)
open fun go(fileNamePrefix: String = ""): GeneratorContexts<StructureUnitI<*>> {
val goTemplates = buildGoTemplates()
val contextFactory = buildGoContextFactory()
val goContextBuilderIfcOrImplOnly = contextFactory.buildForImplOnly()
val goContextBuilderIfcAndImpl = contextFactory.buildForIfcAndImpl()
val components: StructureUnitI<*>.() -> List<CompI<*>> = {
if (this is CompI<*>) listOf(this) else findDownByType(CompI::class.java)
}
val modules: StructureUnitI<*>.() -> List<ModuleI<*>> = {
val ret = if (this is ModuleI<*>) listOf(this) else findDownByType(ModuleI::class.java)
ret
}
val enums: StructureUnitI<*>.() -> List<EnumTypeI<*>> = {
val ret = findDownByType(EnumTypeI::class.java).filter {
it.parent() is StructureUnitI<*> && it.derivedAsType().isEmpty()
}.sortedBy { it.name() }
ret
}
val interfaces: StructureUnitI<*>.() -> List<CompilationUnitI<*>> = {
findDownByType(CompilationUnitI::class.java).filter { it.isIfc() }
}
val values: StructureUnitI<*>.() -> List<ValuesI<*>> = {
val ret = findDownByType(ValuesI::class.java).filter {
!it.isIfc() && it.derivedAsType().isEmpty()
}.sortedBy { "${it.javaClass.simpleName} ${name()}" }
ret
}
val basics: StructureUnitI<*>.() -> List<BasicI<*>> = {
val ret = findDownByType(BasicI::class.java).filter {
!it.isIfc() && it.derivedAsType().isEmpty()
}.sortedBy { "${it.javaClass.simpleName} ${name()}" }
ret
}
val entities: StructureUnitI<*>.() -> List<EntityI<*>> = {
val ret = findDownByType(EntityI::class.java).filter {
!it.isIfc() && it.derivedAsType().isEmpty()
}.sortedBy { "${it.javaClass.simpleName} ${name()}" }
ret
}
val states: StructureUnitI<*>.() -> List<StateI<*>> = {
findDownByType(StateI::class.java).filter {
!it.isIfc() && it.derivedAsType().isEmpty()
}.sortedBy { "${it.javaClass.simpleName} ${name()}" }
}
val controllersWithOutOps: StructureUnitI<*>.() -> List<ControllerI<*>> = {
val ret = findDownByType(ControllerI::class.java).filter {
!it.isIfc() && it.derivedAsType().isEmpty() && it.operations().isEmpty()
}.sortedBy { "${it.javaClass.simpleName} ${name()}" }
ret
}
val controllersWithOps: StructureUnitI<*>.() -> List<ControllerI<*>> = {
val ret = findDownByType(ControllerI::class.java).filter {
!it.isIfc() && it.derivedAsType().isEmpty() && it.operations().isNotEmpty()
}.sortedBy { "${it.javaClass.simpleName} ${name()}" }
ret
}
registerGoMacros(contextFactory)
val moduleGenerators = mutableListOf<GeneratorI<StructureUnitI<*>>>()
val generator = GeneratorGroup(
"go", listOf(
GeneratorGroupItems(
"modulesGenerators",
items = modules, generators = moduleGenerators
)
)
)
moduleGenerators.addAll(
listOf(
GeneratorSimple(
"ifc_base", contextBuilder = goContextBuilderIfcOrImplOnly,
template = FragmentsTemplate(name = "${fileNamePrefix}ifc_base",
nameBuilder = itemAndTemplateNameAsGoFileName, fragments = {
listOf(ItemsFragment(items = interfaces, fragments = {
listOf(goTemplates.ifc())
}))
})
),
GeneratorSimple(
"_api_base", contextBuilder = goContextBuilderIfcOrImplOnly,
template = FragmentsTemplate(name = "${fileNamePrefix}api_base",
nameBuilder = itemAndTemplateNameAsGoFileName, fragments = {
listOf(
ItemsFragment(items = entities, fragments = { listOf(goTemplates.entity()) }),
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = values,
fragments = { listOf(goTemplates.pojo()) }),
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = basics,
fragments = { listOf(goTemplates.pojo()) }),
ItemsFragment(items = enums, fragments = { listOf(goTemplates.enum()) }),
ItemsFragment(items = controllersWithOutOps, fragments = { listOf(goTemplates.pojo()) })
)
})
),
GeneratorSimple(
"ifc_api_base", contextBuilder = goContextBuilderIfcAndImpl,
template = FragmentsTemplate(name = "${fileNamePrefix}ifc_api_base",
nameBuilder = itemAndTemplateNameAsGoFileName, fragments = {
listOf(
ItemsFragment(items = controllersWithOps, fragments = {
listOf(goTemplates.ifc())
}),
ItemsFragment(items = controllersWithOps, fragments = {
listOf(goTemplates.pojo())
})
)
})
),
GeneratorSimple(
"_test_base", contextBuilder = goContextBuilderIfcOrImplOnly,
template = FragmentsTemplate(name = "${fileNamePrefix}test_base",
nameBuilder = itemAndTemplateNameAsGoFileName, fragments = {
listOf(
ItemsFragment(items = entities, fragments = { listOf(goTemplates.newTestInstance()) }),
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = values,
fragments = { listOf(goTemplates.newTestInstance()) }),
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = basics,
fragments = { listOf(goTemplates.newTestInstance()) })
)
})
)
)
)
//val derivedTypes = mutableListOf(DesignDerivedType.Aggregate, DesignDerivedType.Query, DesignDerivedType.Http,
// DesignDerivedType.Client, DesignDerivedType.Cli, DesignDerivedType.StateMachine)
val derivedTypes: List<String> = emptyList()
val derivedTypesGenerators = derivedTypes.map { derivedType ->
GeneratorSimple(
"${derivedType}_base", contextBuilder = goContextBuilderIfcOrImplOnly,
template = FragmentsTemplate(name = "${fileNamePrefix}${derivedType}_base",
nameBuilder = itemAndTemplateNameAsGoFileName, fragments = {
listOf(
ItemsFragment(items = {
findDownByType(ControllerI::class.java).filter {
it.derivedAsType().equals(derivedType, true)
}.sortedBy { "${it.javaClass.simpleName} ${name()}" }
}, fragments = { listOf(goTemplates.ifcOrPojo()) }),
ItemsFragment(items = {
findDownByType(ValuesI::class.java).filter {
it.derivedAsType().equals(derivedType, true)
}.sortedBy { "${it.javaClass.simpleName} ${name()}" }
}, fragments = { listOf(goTemplates.ifcOrPojo()) }),
ItemsFragment(items = {
findDownByType(BasicI::class.java).filter {
it.derivedAsType().equals(derivedType, true)
}.sortedBy { "${it.javaClass.simpleName} ${name()}" }
}, fragments = { listOf(goTemplates.ifcOrPojo()) }),
ItemsFragment(items = {
findDownByType(EnumTypeI::class.java).filter {
it.derivedAsType().equals(derivedType, true)
}.sortedBy { "${it.javaClass.simpleName} ${name()}" }
}, fragments = { listOf(goTemplates.enum()) })
)
})
)
}
moduleGenerators.addAll(derivedTypesGenerators)
return GeneratorContexts(generator, goContextBuilderIfcOrImplOnly)
}
open fun goEventDriven(fileNamePrefix: String = ""): GeneratorContexts<StructureUnitI<*>> {
val swaggerTemplates = buildSwaggerTemplates()
val swaggerContextFactory = buildSwaggerContextFactory()
val swaggerContextBuilder = swaggerContextFactory.build()
val goTemplates = buildGoTemplates()
val contextFactory = buildGoContextFactory()
val goContextBuilder = contextFactory.buildForImplOnly()
val components: StructureUnitI<*>.() -> List<CompI<*>> = {
if (this is CompI<*>) listOf(this) else findDownByType(CompI::class.java)
}
val modules: StructureUnitI<*>.() -> List<ModuleI<*>> = {
if (this is ModuleI<*>) listOf(this) else findDownByType(ModuleI::class.java)
}
registerGoMacros(contextFactory)
val moduleGenerators = mutableListOf<GeneratorI<StructureUnitI<*>>>()
val generator = GeneratorGroup(
"eventDrivenGo", listOf(
GeneratorGroupItems(
"modulesGenerators",
items = modules, generators = moduleGenerators
),
Generator("swaggerComponent", contextBuilder = swaggerContextBuilder, items = components,
templates = { listOf(swaggerTemplates.model()) })
)
)
moduleGenerators.addAll(
listOf(
)
)
val derivedTypes = mutableListOf(
"",
DesignDerivedType.Aggregate,
DesignDerivedType.AggregateEvents,
DesignDerivedType.AggregateCommands,
DesignDerivedType.Query,
DesignDerivedType.Http,
DesignDerivedType.Client,
DesignDerivedType.Cli,
DesignDerivedType.StateMachine,
DesignDerivedType.StateMachineEvents,
DesignDerivedType.StateMachineCommands,
)
derivedTypes.forEach { derivedType ->
val controllers: StructureUnitI<*>.() -> Collection<ControllerI<*>> = {
findDownByType(type = ControllerI::class.java, stopSteppingDownIfFound = false).filter {
!it.isIfc() && it.derivedAsType().equals(derivedType, true)
}.sortedBy { "${it.javaClass.simpleName} ${name()}" }
}
val commands: StructureUnitI<*>.() -> List<CommandI<*>> = {
findDownByType(CommandI::class.java).filter {
it.derivedAsType().equals(derivedType, true)
}.sortedBy { "${it.javaClass.simpleName} ${name()}" }
}
val eventsWithData: StructureUnitI<*>.() -> List<EventI<*>> = {
findDownByType(EventI::class.java).filter {
it.props().isNotEmpty() && it.derivedAsType().equals(derivedType, true)
}.sortedBy { "${it.javaClass.simpleName} ${name()}" }
}
val enums: StructureUnitI<*>.() -> List<EnumTypeI<*>> = {
findDownByType(EnumTypeI::class.java).filter {
it.derivedAsType().equals(derivedType, true)
}.sortedBy { it.name() }
}
val interfaces: StructureUnitI<*>.() -> List<CompilationUnitI<*>> = {
findDownByType(CompilationUnitI::class.java, stopSteppingDownIfFound = false).filter {
it.isIfc() && it.derivedAsType().equals(derivedType, true)
}.sortedBy { it.name() }
}
val values: StructureUnitI<*>.() -> List<ValuesI<*>> = {
findDownByType(ValuesI::class.java).filter {
it.derivedAsType().equals(derivedType, true)
}.sortedBy { "${it.javaClass.simpleName} ${name()}" }
}
val basics: StructureUnitI<*>.() -> List<BasicI<*>> = {
findDownByType(BasicI::class.java).filter {
it.derivedAsType().equals(derivedType, true)
}.sortedBy { "${it.javaClass.simpleName} ${name()}" }
}
val entities: StructureUnitI<*>.() -> List<EntityI<*>> = {
val retEntities = findDownByType(EntityI::class.java).filter {
it.derivedAsType().equals(derivedType, true)
}.sortedBy { "${it.javaClass.simpleName} ${name()}" }
retEntities.forEach {
it.propIdOrAdd()
it.propDeletedAt()
}
retEntities
}
moduleGenerators.add(
GeneratorSimple(
"IfcBase", contextBuilder = goContextBuilder,
template = FragmentsTemplate(name = "${fileNamePrefix}${derivedType}IfcBase",
nameBuilder = itemAndTemplateNameAsGoFileName, fragments = {
listOf(ItemsFragment(items = interfaces, fragments = {
listOf(goTemplates.ifc())
}))
})
)
)
moduleGenerators.add(
GeneratorSimple(
"ApiBase", contextBuilder = goContextBuilder,
template = FragmentsTemplate(name = "${fileNamePrefix}${derivedType}ApiBase",
nameBuilder = itemAndTemplateNameAsGoFileName, fragments = {
listOf(
ItemsFragment(items = entities, fragments = { listOf(goTemplates.entity()) }),
ItemsFragment(items = controllers, fragments = { listOf(goTemplates.pojo()) }),
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = values,
fragments = { listOf(goTemplates.pojo()) }),
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = basics,
fragments = { listOf(goTemplates.pojo()) }),
ItemsFragment(items = enums, fragments = { listOf(goTemplates.enum()) })
)
})
)
)
moduleGenerators.add(
GeneratorSimple(
"TestBase", contextBuilder = goContextBuilder,
template = FragmentsTemplate(name = "${fileNamePrefix}${derivedType}TestBase",
nameBuilder = itemAndTemplateNameAsGoFileName,
fragments = {
listOf(
ItemsFragment(items = entities,
fragments = { listOf(goTemplates.newTestInstance()) }),
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = values,
fragments = { listOf(goTemplates.newTestInstance()) }),
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = basics,
fragments = { listOf(goTemplates.newTestInstance()) })
)
})
)
)
moduleGenerators.add(
GeneratorSimple(
"CommandsBase", contextBuilder = goContextBuilder,
template = FragmentsTemplate(name = "${fileNamePrefix}${derivedType}EsCommandsBase",
nameBuilder = itemAndTemplateNameAsGoFileName, fragments = {
listOf(
ItemsFragment(items = entities, fragments = { listOf(goTemplates.commandTypes()) }),
ItemsFragment(items = commands, fragments = { listOf(goTemplates.command()) }),
)
})
)
)
moduleGenerators.add(
GeneratorSimple(
"EventsBase", contextBuilder = goContextBuilder,
template = FragmentsTemplate(name = "${fileNamePrefix}${derivedType}EsEventsBase",
nameBuilder = itemAndTemplateNameAsGoFileName, fragments = {
listOf(
ItemsFragment(items = entities, fragments = { listOf(goTemplates.eventTypes()) }),
ItemsFragment(
items = eventsWithData,
fragments = { listOf(goTemplates.pojoExcludePropsWithValue()) }),
)
})
)
)
}
return GeneratorContexts(generator, swaggerContextBuilder, goContextBuilder)
}
open fun typeScriptApiBase(fileNamePrefix: String = "", model: StructureUnitI<*>): GeneratorContexts<StructureUnitI<*>> {
val tsTemplates = buildTsTemplates()
val tsContextFactory = buildTsContextFactory()
val tsContextBuilder = tsContextFactory.buildForImplOnly()
val components: StructureUnitI<*>.() -> List<CompI<*>> = {
if (this is CompI<*>) listOf(this) else findDownByType(CompI::class.java)
}
val modules: StructureUnitI<*>.() -> List<ModuleI<*>> = {
if (this is ModuleI<*>) listOf(this) else findDownByType(ModuleI::class.java)
}
val commands: StructureUnitI<*>.() -> List<CommandI<*>> = { findDownByType(CommandI::class.java) }
val commandEnums: StructureUnitI<*>.() -> List<EnumTypeI<*>> = {
findDownByType(EnumTypeI::class.java).filter {
it.parent() is ControllerI<*> && it.name().endsWith("CommandType")
}
}
val events: StructureUnitI<*>.() -> List<EventI<*>> = { findDownByType(EventI::class.java) }
val eventEnums: StructureUnitI<*>.() -> List<EnumTypeI<*>> = {
findDownByType(EnumTypeI::class.java).filter {
it.parent() is ControllerI<*> && it.name().endsWith("EventType")
}
}
val enums: StructureUnitI<*>.() -> List<EnumTypeI<*>> = {
findDownByType(EnumTypeI::class.java).filter {
it.parent() is StructureUnitI<*> && it.derivedAsType().isEmpty()
}.sortedBy { it.name() }
}
val values: StructureUnitI<*>.() -> List<ValuesI<*>> = {
findDownByType(ValuesI::class.java).filter { it.derivedAsType().isEmpty() }
.sortedBy { "${it.javaClass.simpleName} ${name()}" }
}
val basics: StructureUnitI<*>.() -> List<BasicI<*>> = {
findDownByType(BasicI::class.java).filter { it.derivedAsType().isEmpty() }
.sortedBy { "${it.javaClass.simpleName} ${name()}" }
}
val entities: StructureUnitI<*>.() -> List<EntityI<*>> = {
findDownByType(EntityI::class.java).filter { it.derivedAsType().isEmpty() }
.sortedBy { "${it.javaClass.simpleName} ${name()}" }
}
val moduleGenerators = mutableListOf<GeneratorI<StructureUnitI<*>>>()
val generator = GeneratorGroup(
"angular",
listOf(GeneratorGroupItems("angularModules", items = modules, generators = moduleGenerators))
)
moduleGenerators.addAll(
listOf(
GeneratorSimple(
"ApiBase", contextBuilder = tsContextBuilder,
template = FragmentsTemplate(name = "${fileNamePrefix}ApiBase",
nameBuilder = itemAndTemplateNameAsTsFileName, fragments = {
listOf(
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = entities,
fragments = { listOf(tsTemplates.pojo()) }),
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = values,
fragments = { listOf(tsTemplates.pojo()) }),
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = basics,
fragments = { listOf(tsTemplates.pojo()) }),
ItemsFragment(items = enums, fragments = { listOf(tsTemplates.enum()) })
)
})
),
)
)
return GeneratorContexts(generator, tsContextBuilder)
}
open fun angularTypeScriptComponent(fileNamePrefix: String = "", model: StructureUnitI<*>): GeneratorContexts<StructureUnitI<*>> {
val tsTemplates = buildTsTemplates()
val tsContextFactory = buildTsContextFactory()
val tsContextBuilder = tsContextFactory.buildForImplOnly()
val components: StructureUnitI<*>.() -> List<CompI<*>> = {
if (this is CompI<*>) listOf(this) else findDownByType(CompI::class.java)
}
val modules: StructureUnitI<*>.() -> List<ModuleI<*>> = {
if (this is ModuleI<*>) listOf(this) else findDownByType(ModuleI::class.java)
}
val enums: StructureUnitI<*>.() -> List<EnumTypeI<*>> = {
findDownByType(EnumTypeI::class.java).filter {
it.parent() is StructureUnitI<*> && it.derivedAsType().isEmpty()
}.sortedBy { it.name() }
}
val basics: StructureUnitI<*>.() -> List<BasicI<*>> = {
findDownByType(BasicI::class.java).filter { it.derivedAsType().isEmpty() }
.sortedBy { "${it.javaClass.simpleName} ${name()}" }
}
val entities: StructureUnitI<*>.() -> List<EntityI<*>> = {
findDownByType(EntityI::class.java).filter { it.derivedAsType().isEmpty() }
.sortedBy { "${it.javaClass.simpleName} ${name()}" }
}
val compGenerators = mutableListOf<GeneratorI<StructureUnitI<*>>>()
val generator = GeneratorGroup(
"angularTypeScriptComponents",
listOf(GeneratorGroupItems("angularTypeScriptComponents", items = components, generators = compGenerators))
)
modules.invoke(model).forEach {module ->
compGenerators.addAll(
listOf(
GeneratorAngular(
"ModuleViewTypeScript", contextBuilder = tsContextBuilder,
template = FragmentsTemplate(name = "${module.name().toLowerCase()}-module-view.component",
nameBuilder = templateNameAsTsFileName, fragments = {
listOf(
ItemsFragment(items = modules,
fragments = {
listOf<Template<ModuleI<*>>>(tsTemplates.moduleTypeScript()).filter { this.name() == module.name() } }),
)
}
)
),
GeneratorAngular(
"ModuleViewService", contextBuilder = tsContextBuilder,
template = FragmentsTemplate(name = "${module.name().toLowerCase()}-module-view.service",
nameBuilder = templateNameAsTsFileName, fragments = {
listOf(
ItemsFragment(items = modules,
fragments = {
listOf<Template<ModuleI<*>>>(tsTemplates.moduleService(modules.invoke(model))).filter { this.name() == module.name() } }),
)
}
)
),
)
)
module.entities().forEach {entity ->
compGenerators.addAll(
listOf(
GeneratorAngular(
"EntityViewTypeScript", contextBuilder = tsContextBuilder,
template = FragmentsTemplate(name = "${module.name()}_${entity.name().toLowerCase()}-entity-view.component",
nameBuilder = templateNameAsTsFileName, fragments = {
listOf(
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = entities,
fragments = {
listOf<Template<CompilationUnitI<*>>>(tsTemplates.entityViewTypeScript()).filter { this.name() == entity.name() } }),
)
}
)
),
GeneratorAngular(
"EntityFormTypeScript", contextBuilder = tsContextBuilder,
template = FragmentsTemplate(name = "${module.name()}_${entity.name().toLowerCase()}-entity-form.component",
nameBuilder = templateNameAsTsFileName, fragments = {
listOf(
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = entities,
fragments = {
listOf<Template<CompilationUnitI<*>>>(tsTemplates.entityFormTypeScript()).filter { this.name() == entity.name() } }),
)
}
)
),
GeneratorAngular(
"EntityListTypeScript", contextBuilder = tsContextBuilder,
template = FragmentsTemplate(name = "${module.name()}_${entity.name().toLowerCase()}-entity-list.component",
nameBuilder = templateNameAsTsFileName, fragments = {
listOf(
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = entities,
fragments = {
listOf<Template<CompilationUnitI<*>>>(tsTemplates.entityListTypeScript()).filter { this.name() == entity.name() } }),
)
}
)
),
GeneratorAngular(
"EntityDataService", contextBuilder = tsContextBuilder,
template = FragmentsTemplate(name = "${module.name()}_${entity.name().toLowerCase()}-data.service",
nameBuilder = templateNameAsTsFileName, fragments = {
listOf(
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = entities,
fragments = {
listOf<Template<CompilationUnitI<*>>>(tsTemplates.entityDataService()).filter { this.name() == entity.name() } }),
)
}
)
),
)
)
entity.props().filter { it.type() is EnumTypeI<*> }.forEach { enum ->
compGenerators.addAll(
listOf(
GeneratorAngular(
"EnumTypeScript", contextBuilder = tsContextBuilder,
template = FragmentsTemplate(name = "${module.name()}_${enum.type().name().toLowerCase()}-enum.component",
nameBuilder = templateNameAsTsFileName, fragments = {
listOf(
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = enums,
fragments = {
listOf<Template<CompilationUnitI<*>>>(tsTemplates.enumTypeScript(enum.parent())).filter { this.name() == enum.type().name() }}),
)
}
)
)
)
)
}
}
module.basics().forEach {basic ->
compGenerators.addAll(
listOf(
GeneratorAngular(
"BasicTypeScript", contextBuilder = tsContextBuilder,
template = FragmentsTemplate(name = "${module.name()}_${basic.name().toLowerCase()}-basic.component",
nameBuilder = templateNameAsTsFileName, fragments = {
listOf(
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = basics,
fragments = {
listOf<Template<CompilationUnitI<*>>>(tsTemplates.basicTypeScript()).filter { this.name() == basic.name() } }),
)
}
)
),
)
)
basic.props().filter { it.type() is EnumTypeI<*> }.forEach { enum ->
compGenerators.addAll(
listOf(
GeneratorAngular(
"EnumTypeScript", contextBuilder = tsContextBuilder,
template = FragmentsTemplate(name = "${module.name()}_${enum.type().name().toLowerCase()}-enum.component",
nameBuilder = templateNameAsTsFileName, fragments = {
listOf(
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = enums,
fragments = {
listOf<Template<CompilationUnitI<*>>>(tsTemplates.enumTypeScript(enum.parent())).filter { this.name() == enum.type().name() }}),
)
}
)
)
)
)
}
}
}
return GeneratorContexts(generator, tsContextBuilder)
}
open fun angularModules(fileNamePrefix: String = "", model: StructureUnitI<*>): GeneratorContexts<StructureUnitI<*>> {
val angularTemplates = buildAngularTemplates()
val angularContextFactory = buildAngularContextFactory()
val angularContextBuilder = angularContextFactory.buildForImplOnly()
val components: StructureUnitI<*>.() -> List<CompI<*>> = {
if (this is CompI<*>) listOf(this) else findDownByType(CompI::class.java)
}
val modules: StructureUnitI<*>.() -> List<ModuleI<*>> = {
if (this is ModuleI<*>) listOf(this) else findDownByType(ModuleI::class.java)
}
val compGenerators = mutableListOf<GeneratorI<StructureUnitI<*>>>()
val generator = GeneratorGroup(
"angularModule",
listOf(GeneratorGroupItems("angularModule", items = components, generators = compGenerators))
)
modules.invoke(model).forEach {module ->
compGenerators.addAll(
listOf(
GeneratorAngular(
"AngularModule", contextBuilder = angularContextBuilder,
template = FragmentsTemplate(name = "${module.name().toLowerCase()}-model.module",
nameBuilder = templateNameAsTsFileName, fragments = {
listOf(
ItemsFragment(items = modules,
fragments = {
listOf<Template<ModuleI<*>>>(angularTemplates.angularModule()).filter { this.name() == module.name() } }),
)
}
)
),
GeneratorAngular(
"AngularRoutingModule", contextBuilder = angularContextBuilder,
template = FragmentsTemplate(name = "${module.name().toLowerCase()}-routing.module",
nameBuilder = templateNameAsTsFileName, fragments = {
listOf(
ItemsFragment(items = modules,
fragments = {
listOf<Template<ModuleI<*>>>(angularTemplates.angularRoutingModule()).filter { this.name() == module.name() } }),
)
}
)
),
)
)
}
return GeneratorContexts(generator, angularContextBuilder)
}
open fun angularHtmlAndScssComponent(fileNamePrefix: String = "", model: StructureUnitI<*>): GeneratorContexts<StructureUnitI<*>> {
val angularTemplates = buildAngularTemplates()
val angularContextFactory = buildAngularContextFactory()
val angularContextBuilder = angularContextFactory.buildForImplOnly()
val components: StructureUnitI<*>.() -> List<CompI<*>> = {
if (this is CompI<*>) listOf(this) else findDownByType(CompI::class.java)
}
val modules: StructureUnitI<*>.() -> List<ModuleI<*>> = {
if (this is ModuleI<*>) listOf(this) else findDownByType(ModuleI::class.java)
}
val enums: StructureUnitI<*>.() -> List<EnumTypeI<*>> = {
findDownByType(EnumTypeI::class.java).filter {
it.parent() is StructureUnitI<*> && it.derivedAsType().isEmpty()
}.sortedBy { it.name() }
}
val basics: StructureUnitI<*>.() -> List<BasicI<*>> = {
findDownByType(BasicI::class.java).filter { it.derivedAsType().isEmpty() }
.sortedBy { "${it.javaClass.simpleName} ${name()}" }
}
val entities: StructureUnitI<*>.() -> List<EntityI<*>> = {
findDownByType(EntityI::class.java).filter { it.derivedAsType().isEmpty() }
.sortedBy { "${it.javaClass.simpleName} ${name()}" }
}
val compGenerators = mutableListOf<GeneratorI<StructureUnitI<*>>>()
val generator = GeneratorGroup(
"angularHtmlAndScssComponents",
listOf(GeneratorGroupItems("angularHtmlAndScssComponents", items = components, generators = compGenerators))
)
modules.invoke(model).forEach {module ->
compGenerators.addAll(
listOf(
GeneratorAngular(
"ModuleHtml", contextBuilder = angularContextBuilder,
template = FragmentsTemplate(name = "${module.name().toLowerCase()}-module-view.component",
nameBuilder = templateNameAsHTMLFileName, fragments = {
listOf(
ItemsFragment(items = modules,
fragments = {
listOf<Template<ModuleI<*>>>(angularTemplates.moduleHTML()).filter { this.name() == module.name() } }),
)
}
)
),
GeneratorAngular(
"ModuleScss", contextBuilder = angularContextBuilder,
template = FragmentsTemplate(name = "${fileNamePrefix}${module.name().toLowerCase()}-module-view.component",
nameBuilder = templateNameAsCSSFileName, fragments = {
listOf(
ItemsFragment(items = modules,
fragments = {
listOf<Template<ModuleI<*>>>(angularTemplates.moduleSCSS()).filter { this.name() == module.name() } }),
)
}
)
),
)
)
module.entities().forEach {entity ->
compGenerators.addAll(
listOf(
GeneratorAngular(
"EntityViewHtml", contextBuilder = angularContextBuilder,
template = FragmentsTemplate(name = "${module.name()}_${entity.name().toLowerCase()}-entity-view.component",
nameBuilder = templateNameAsHTMLFileName, fragments = {
listOf(
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = entities,
fragments = {
listOf<Template<CompilationUnitI<*>>>(angularTemplates.entityViewHTML()).filter { this.name() == entity.name() } }),
)
}
)
),
GeneratorAngular(
"EntityViewScss", contextBuilder = angularContextBuilder,
template = FragmentsTemplate(name = "${module.name()}_${entity.name().toLowerCase()}-entity-view.component",
nameBuilder = templateNameAsCSSFileName, fragments = {
listOf(
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = entities,
fragments = {
listOf<Template<CompilationUnitI<*>>>(angularTemplates.entityViewSCSS()).filter { this.name() == entity.name() } }),
)
}
)
),
GeneratorAngular(
"EntityFormHtml", contextBuilder = angularContextBuilder,
template = FragmentsTemplate(name = "${module.name()}_${entity.name().toLowerCase()}-entity-form.component",
nameBuilder = templateNameAsHTMLFileName, fragments = {
listOf(
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = entities,
fragments = {
listOf<Template<CompilationUnitI<*>>>(angularTemplates.entityFormHTML()).filter { this.name() == entity.name() } }),
)
}
)
),
GeneratorAngular(
"EntityFormScss", contextBuilder = angularContextBuilder,
template = FragmentsTemplate(name = "${module.name()}_${entity.name().toLowerCase()}-entity-form.component",
nameBuilder = templateNameAsCSSFileName, fragments = {
listOf(
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = entities,
fragments = {
listOf<Template<CompilationUnitI<*>>>(angularTemplates.entityFormSCSS()).filter { this.name() == entity.name() } }),
)
}
)
),
GeneratorAngular(
"EntityListHtml", contextBuilder = angularContextBuilder,
template = FragmentsTemplate(name = "${module.name()}_${entity.name().toLowerCase()}-entity-list.component",
nameBuilder = templateNameAsHTMLFileName, fragments = {
listOf(
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = entities,
fragments = {
listOf<Template<CompilationUnitI<*>>>(angularTemplates.entityListHTML()).filter { this.name() == entity.name() } }),
)
}
)
),
GeneratorAngular(
"EntityListScss", contextBuilder = angularContextBuilder,
template = FragmentsTemplate(name = "${module.name()}_${entity.name().toLowerCase()}-entity-list.component",
nameBuilder = templateNameAsCSSFileName, fragments = {
listOf(
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = entities,
fragments = {
listOf<Template<CompilationUnitI<*>>>(angularTemplates.entityListSCSS()).filter { this.name() == entity.name() } }),
)
}
)
),
)
)
entity.props().filter { it.type() is EnumTypeI }.forEach { enum ->
compGenerators.addAll(
listOf(
GeneratorAngular(
"EnumHtml", contextBuilder = angularContextBuilder,
template = FragmentsTemplate(name = "${module.name()}_${enum.type().name().toLowerCase()}-enum.component",
nameBuilder = templateNameAsHTMLFileName, fragments = {
listOf(
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = enums,
fragments = {
listOf<Template<CompilationUnitI<*>>>(angularTemplates.enumHTML(enum.parent(), enum.name())).filter { this.name() == enum.type().name() } }),
)
}
)
),
GeneratorAngular(
"EnumScss", contextBuilder = angularContextBuilder,
template = FragmentsTemplate(name = "${module.name()}_${enum.type().name().toLowerCase()}-enum.component",
nameBuilder = templateNameAsCSSFileName, fragments = {
listOf(
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = enums,
fragments = {
listOf<Template<CompilationUnitI<*>>>(angularTemplates.enumSCSS()).filter { this.name() == enum.type().name() } }),
)
}
)
),
)
)
}
}
module.basics().forEach {basic ->
compGenerators.addAll(
listOf(
GeneratorAngular(
"BasicHtml", contextBuilder = angularContextBuilder,
template = FragmentsTemplate(name = "${module.name()}_${basic.name().toLowerCase()}-basic.component",
nameBuilder = templateNameAsHTMLFileName, fragments = {
listOf(
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = basics,
fragments = {
listOf<Template<CompilationUnitI<*>>>(angularTemplates.basicHTML()).filter { this.name() == basic.name() } }),
)
}
)
),
GeneratorAngular(
"BasicScss", contextBuilder = angularContextBuilder,
template = FragmentsTemplate(name = "${module.name()}_${basic.name().toLowerCase()}-basic.component",
nameBuilder = templateNameAsCSSFileName, fragments = {
listOf(
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = basics,
fragments = {
listOf<Template<CompilationUnitI<*>>>(angularTemplates.basicSCSS()).filter { this.name() == basic.name() } }),
)
}
)
),
)
)
basic.props().filter { it.type() is EnumTypeI }.forEach { enum ->
compGenerators.addAll(
listOf(
GeneratorAngular(
"EnumHtml", contextBuilder = angularContextBuilder,
template = FragmentsTemplate(name = "${module.name()}_${enum.type().name().toLowerCase()}-enum.component",
nameBuilder = templateNameAsHTMLFileName, fragments = {
listOf(
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = enums,
fragments = {
listOf<Template<CompilationUnitI<*>>>(angularTemplates.enumHTML(enum.parent(), enum.name())).filter { this.name() == enum.type().name() } }),
)
}
)
),
GeneratorAngular(
"EnumScss", contextBuilder = angularContextBuilder,
template = FragmentsTemplate(name = "${module.name()}_${enum.type().name().toLowerCase()}-enum.component",
nameBuilder = templateNameAsCSSFileName, fragments = {
listOf(
ItemsFragment<StructureUnitI<*>, CompilationUnitI<*>>(items = enums,
fragments = {
listOf<Template<CompilationUnitI<*>>>(angularTemplates.enumSCSS()).filter { this.name() == enum.type().name() } }),
)
}
)
),
)
)
}
}
}
return GeneratorContexts(generator, angularContextBuilder)
}
protected fun registerGoMacros(contextFactory: LangCommonContextFactory) {
val macros = contextFactory.macroController
macros.registerMacro(
OperationI<*>::toGoAggregateEngineRegisterCommands.name,
OperationI<*>::toGoAggregateEngineRegisterCommands
)
macros.registerMacro(
CompilationUnitI<*>::toGoAggregateEngineConst.name,
CompilationUnitI<*>::toGoAggregateEngineConst
)
macros.registerMacro(
CompilationUnitI<*>::toGoAggregateEngineRegisterForEvents.name,
CompilationUnitI<*>::toGoAggregateEngineRegisterForEvents
)
macros.registerMacro(
ConstructorI<*>::toGoAggregateEngineBody.name,
ConstructorI<*>::toGoAggregateEngineBody
)
macros.registerMacro(
OperationI<*>::toGoAggregateEngineSetupBody.name,
OperationI<*>::toGoAggregateEngineSetupBody
)
macros.registerMacro(
OperationI<*>::toGoAggregateApplyEventBody.name,
OperationI<*>::toGoAggregateApplyEventBody
)
macros.registerMacro(ConstructorI<*>::toGoEhEngineBody.name, ConstructorI<*>::toGoEhEngineBody)
macros.registerMacro(OperationI<*>::toGoEhEngineSetupBody.name, OperationI<*>::toGoEhEngineSetupBody)
macros.registerMacro(AttributeI<*>::toGoPropOptionalAfterBody.name, AttributeI<*>::toGoPropOptionalAfterBody)
macros.registerMacro(
OperationI<*>::toGoStatesCommandHandlerSetupBody.name,
OperationI<*>::toGoStatesCommandHandlerSetupBody
)
macros.registerMacro(
OperationI<*>::toGoStatesCommandHandlerExecute.name,
OperationI<*>::toGoStatesCommandHandlerExecute
)
macros.registerMacro(OperationI<*>::toGoEventHandlerApplyEvent.name, OperationI<*>::toGoEventHandlerApplyEvent)
macros.registerMacro(OperationI<*>::toGoEventHandlerSetupBody.name, OperationI<*>::toGoEventHandlerSetupBody)
macros.registerMacro(OperationI<*>::toGoHttpHandlerBody.name, OperationI<*>::toGoHttpHandlerBody)
macros.registerMacro(OperationI<*>::toGoHttpHandlerIdBasedBody.name, OperationI<*>::toGoHttpHandlerIdBasedBody)
macros.registerMacro(OperationI<*>::toGoHttpHandlerCommandBody.name, OperationI<*>::toGoHttpHandlerCommandBody)
macros.registerMacro(OperationI<*>::toGoSetupHttpRouterBody.name, OperationI<*>::toGoSetupHttpRouterBody)
macros.registerMacro(ConstructorI<*>::toGoHttpRouterBeforeBody.name, ConstructorI<*>::toGoHttpRouterBeforeBody)
macros.registerMacro(
ConstructorI<*>::toGoHttpModuleRouterBeforeBody.name,
ConstructorI<*>::toGoHttpModuleRouterBeforeBody
)
macros.registerMacro(OperationI<*>::toGoSetupModuleHttpRouter.name, OperationI<*>::toGoSetupModuleHttpRouter)
macros.registerMacro(OperationI<*>::toGoHttpClientCreateBody.name, OperationI<*>::toGoHttpClientCreateBody)
macros.registerMacro(
OperationI<*>::toGoHttpClientCreateItemsBody.name,
OperationI<*>::toGoHttpClientCreateItemsBody
)
macros.registerMacro(
OperationI<*>::toGoHttpClientDeleteByIdsBody.name,
OperationI<*>::toGoHttpClientDeleteByIdsBody
)
macros.registerMacro(
OperationI<*>::toGoHttpClientDeleteByIdBody.name,
OperationI<*>::toGoHttpClientDeleteByIdBody
)
macros.registerMacro(OperationI<*>::toGoHttpClientFindAllBody.name, OperationI<*>::toGoHttpClientFindAllBody)
macros.registerMacro(
OperationI<*>::toGoHttpClientImportJsonBody.name,
OperationI<*>::toGoHttpClientImportJsonBody
)
macros.registerMacro(
OperationI<*>::toGoHttpClientExportJsonBody.name,
OperationI<*>::toGoHttpClientExportJsonBody
)
macros.registerMacro(
OperationI<*>::toGoHttpClientReadFileJsonBody.name,
OperationI<*>::toGoHttpClientReadFileJsonBody
)
macros.registerMacro(ConstructorI<*>::toGoHttpClientBeforeBody.name, ConstructorI<*>::toGoHttpClientBeforeBody)
macros.registerMacro(
ConstructorI<*>::toGoHttpModuleClientBeforeBody.name,
ConstructorI<*>::toGoHttpModuleClientBeforeBody
)
macros.registerMacro(ConstructorI<*>::toGoCliBeforeBody.name, ConstructorI<*>::toGoCliBeforeBody)
macros.registerMacro(OperationI<*>::toGoCliBuildCommands.name, OperationI<*>::toGoCliBuildCommands)
macros.registerMacro(OperationI<*>::toGoCliDeleteByIdBody.name, OperationI<*>::toGoCliDeleteByIdBody)
macros.registerMacro(OperationI<*>::toGoCliDeleteByIdsBody.name, OperationI<*>::toGoCliDeleteByIdsBody)
macros.registerMacro(OperationI<*>::toGoCliImportJsonBody.name, OperationI<*>::toGoCliImportJsonBody)
macros.registerMacro(OperationI<*>::toGoCliExportJsonBody.name, OperationI<*>::toGoCliExportJsonBody)
macros.registerMacro(OperationI<*>::toGoFindByBody.name, OperationI<*>::toGoFindByBody)
macros.registerMacro(OperationI<*>::toGoCountByBody.name, OperationI<*>::toGoCountByBody)
macros.registerMacro(OperationI<*>::toGoExistByBody.name, OperationI<*>::toGoExistByBody)
macros.registerMacro(
OperationI<*>::toGoStateCommandHandlerSetupBody.name,
OperationI<*>::toGoStateCommandHandlerSetupBody
)
macros.registerMacro(
OperationI<*>::toGoStateCommandHandlerAddCommandPreparerBody.name,
OperationI<*>::toGoStateCommandHandlerAddCommandPreparerBody
)
macros.registerMacro(
OperationI<*>::toGoStateAddCommandsPreparerBody.name,
OperationI<*>::toGoStateAddCommandsPreparerBody
)
macros.registerMacro(
OperationI<*>::toGoStateCommandHandlerExecuteBody.name,
OperationI<*>::toGoStateCommandHandlerExecuteBody
)
macros.registerMacro(
OperationI<*>::toGoStateEventType.name,
OperationI<*>::toGoStateEventType
)
macros.registerMacro(
OperationI<*>::toGoStateEventHandlersPreparerBody.name,
OperationI<*>::toGoStateEventHandlersPreparerBody
)
macros.registerMacro(
OperationI<*>::toGoStateEventHandlerApplyEvent.name,
OperationI<*>::toGoStateEventHandlerApplyEvent
)
macros.registerMacro(
OperationI<*>::toGoStateEventHandlerSetupBody.name,
OperationI<*>::toGoStateEventHandlerSetupBody
)
macros.registerMacro(
OperationI<*>::toGoStatesEventHandlerSetupBody.name,
OperationI<*>::toGoStatesEventHandlerSetupBody
)
macros.registerMacro(
OperationI<*>::toGoStatesEventHandlerApplyEvent.name,
OperationI<*>::toGoStatesEventHandlerApplyEvent
)
macros.registerMacro(
OperationI<*>::toGoAggregateHandleCommand.name,
OperationI<*>::toGoAggregateHandleCommand
)
}
}
| 0 | Kotlin | 0 | 0 | a4230049ae78e4e725100ca90768136e5ae740a9 | 57,912 | ee | Apache License 2.0 |
compiler/cli/src/org/jetbrains/kotlin/cli/common/CLICompiler.kt | tnorbye | 162,147,688 | true | {"Kotlin": 32763299, "Java": 7651072, "JavaScript": 152998, "HTML": 71905, "Lex": 18278, "IDL": 10641, "ANTLR": 9803, "Shell": 7727, "Groovy": 6091, "Batchfile": 5362, "CSS": 4679, "Scala": 80} | /*
* Copyright 2010-2017 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.cli.common
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
import org.jetbrains.kotlin.analyzer.AnalysisResult
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY
import org.jetbrains.kotlin.cli.common.ExitCode.COMPILATION_ERROR
import org.jetbrains.kotlin.cli.common.ExitCode.INTERNAL_ERROR
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.cli.common.environment.setIdeaIoUseFallback
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity.INFO
import org.jetbrains.kotlin.cli.common.messages.GroupingMessageCollector
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.common.messages.MessageCollectorUtil
import org.jetbrains.kotlin.cli.common.messages.MessageRenderer
import org.jetbrains.kotlin.config.CompilerConfiguration
import org.jetbrains.kotlin.config.Services
import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion
import org.jetbrains.kotlin.progress.CompilationCanceledException
import org.jetbrains.kotlin.progress.CompilationCanceledStatus
import org.jetbrains.kotlin.progress.ProgressIndicatorAndCompilationCanceledStatus
import org.jetbrains.kotlin.utils.KotlinPaths
import java.io.File
import java.io.PrintStream
abstract class CLICompiler<A : CommonCompilerArguments> : CLITool<A>() {
protected abstract val performanceManager: CommonCompilerPerformanceManager
// Used in CompilerRunnerUtil#invokeExecMethod, in Eclipse plugin (KotlinCLICompiler) and in kotlin-gradle-plugin (GradleCompilerRunner)
fun execAndOutputXml(errStream: PrintStream, services: Services, vararg args: String): ExitCode {
return exec(errStream, services, MessageRenderer.XML, args)
}
// Used via reflection in KotlinCompilerBaseTask
fun execFullPathsInMessages(errStream: PrintStream, args: Array<String>): ExitCode {
return exec(errStream, Services.EMPTY, MessageRenderer.PLAIN_FULL_PATHS, args)
}
public override fun execImpl(baseMessageCollector: MessageCollector, services: Services, arguments: A): ExitCode {
val performanceManager = performanceManager
if (arguments.reportPerf || arguments.dumpPerf != null) {
performanceManager.enableCollectingPerformanceStatistics()
}
val configuration = CompilerConfiguration()
val messageCollector = GroupingMessageCollector(baseMessageCollector, arguments.allWarningsAsErrors).also {
configuration.put(CLIConfigurationKeys.MESSAGE_COLLECTOR_KEY, it)
}
configuration.put(CLIConfigurationKeys.PERF_MANAGER, performanceManager)
try {
setupCommonArguments(configuration, arguments)
setupPlatformSpecificArgumentsAndServices(configuration, arguments, services)
val paths = computeKotlinPaths(messageCollector, arguments)
if (messageCollector.hasErrors()) {
return ExitCode.COMPILATION_ERROR
}
val canceledStatus = services[CompilationCanceledStatus::class.java]
ProgressIndicatorAndCompilationCanceledStatus.setCompilationCanceledStatus(canceledStatus)
val rootDisposable = Disposer.newDisposable()
try {
setIdeaIoUseFallback()
val code = doExecute(arguments, configuration, rootDisposable, paths)
performanceManager.notifyCompilationFinished()
if (arguments.reportPerf) {
performanceManager.getMeasurementResults()
.forEach { it -> configuration.get(MESSAGE_COLLECTOR_KEY)!!.report(INFO, "PERF: " + it.render(), null) }
}
if (arguments.dumpPerf != null) {
performanceManager.dumpPerformanceReport(File(arguments.dumpPerf!!))
}
return if (messageCollector.hasErrors()) COMPILATION_ERROR else code
} catch (e: CompilationCanceledException) {
messageCollector.report(INFO, "Compilation was canceled", null)
return ExitCode.OK
} catch (e: RuntimeException) {
val cause = e.cause
if (cause is CompilationCanceledException) {
messageCollector.report(INFO, "Compilation was canceled", null)
return ExitCode.OK
} else {
throw e
}
} finally {
Disposer.dispose(rootDisposable)
}
} catch (e: AnalysisResult.CompilationErrorException) {
return COMPILATION_ERROR
} catch (t: Throwable) {
MessageCollectorUtil.reportException(messageCollector, t)
return INTERNAL_ERROR
} finally {
messageCollector.flush()
}
}
private fun setupCommonArguments(configuration: CompilerConfiguration, arguments: A) {
configuration.setupCommonArguments(arguments, this::createMetadataVersion)
}
protected abstract fun createMetadataVersion(versionArray: IntArray): BinaryVersion
protected abstract fun setupPlatformSpecificArgumentsAndServices(
configuration: CompilerConfiguration, arguments: A, services: Services
)
protected abstract fun doExecute(
arguments: A,
configuration: CompilerConfiguration,
rootDisposable: Disposable,
paths: KotlinPaths?
): ExitCode
}
| 7 | Kotlin | 2 | 2 | b6be6a4919cd7f37426d1e8780509a22fa49e1b1 | 6,138 | kotlin | Apache License 2.0 |
src/main/GrammarParser.kt | ArtyomKopan | 722,583,217 | false | {"Kotlin": 23888} | package lgdb
object GrammarParser {
fun parse(data: List<String>): Map<String, String> {
val grammar = mutableMapOf<String, String>()
for (line in data) {
val parts = line.split(":").map { it.trim() }
require(parts.size == 2) { "Некорректный формат ввода грамматики!" }
val nonterminal = parts[0]
val regex = if (parts[1].endsWith('.'))
parts[1].substring(0, parts[1].length - 1)
else parts[1]
grammar[nonterminal] = regex
}
return grammar
}
} | 0 | Kotlin | 0 | 0 | 2e93318b346e1861b85a70b86dc4d793acccabbc | 610 | LinearGraphDistributionBuilder | MIT License |
app/src/main/java/com/lpirro/tiledemo/sharing/ShareConfigReceiver.kt | amitkumar0000 | 343,741,379 | false | null | package com.lpirro.tiledemo.sharing
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.os.Parcel
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lpirro.tiledemo.Utils
import com.lpirro.tiledemo.customquicksettings.QuickSettingModel
import kotlinx.android.parcel.Parcelize
class ShareConfigReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if(context == null)
return
val sharedpreferences = context.getSharedPreferences("MyPREFERENCES", Context.MODE_PRIVATE)
context.sendBroadcast(Intent().apply {
action = "android.intent.action.qsetting.config_response"
putExtra("config_bundle", Bundle().apply {
putParcelable("cofig", Config(shownElements = getShownElements(sharedpreferences), shownNotifications = getNotification(sharedpreferences)))
})
})
}
}
private fun getShownElements(sharedPreferences: SharedPreferences): ShownElements {
val type = object : TypeToken<List<QuickSettingModel.TilesModel?>?>() {}.type
val json: String? = sharedPreferences?.getString(Utils.QSETTING_CONFIG, "")
val tilesList: List<QuickSettingModel.TilesModel> = Gson().fromJson(json, type)
val shownElements = ShownElements(arrayListOf())
if (!json.isNullOrEmpty()) {
tilesList.forEach {
val readState = if (it.isReadOnly)
"readOnly"
else
"readWrite"
shownElements.elements.add(Elements(elementName = it.name, accessLevel = readState))
}
return shownElements
}
return getDefaultShownElements()
}
private fun getDefaultShownElements():ShownElements {
var elements = ArrayList<Elements>()
elements.add(Elements(WLAN, "readWrite"))
elements.add(Elements(Bluetooth, "readWrite"))
elements.add(Elements(Flashlight, "readWrite"))
elements.add(Elements(GPS, "readWrite"))
elements.add(Elements(MOBILEDATA, "readWrite"))
elements.add(Elements(NFC, "readWrite"))
return ShownElements(elements)
}
private fun getNotification(sharedPreferences: SharedPreferences): ShownNotifications {
val type = object : TypeToken<List<Notification?>?>() {}.type
val json: String? = sharedPreferences?.getString(Utils.NOTIFICATION_PACKAGE_LIST, "")
if (json != null) {
val notificationList: List<Notification> = Gson().fromJson(json, type)
return ShownNotifications(notification = notificationList)
} else {
return ShownNotifications(notification = listOf())
}
}
| 0 | Kotlin | 0 | 0 | cc99d7b4f912807239c82c958e7e8aadc2a9637a | 2,731 | tiles | Apache License 2.0 |
src/main/kotlin/org/arxing/bitrisesdk/core/model/shared/UserEntity.kt | Arxing | 390,718,612 | false | {"Kotlin": 27384} | package org.arxing.bitrisesdk.core.model.shared
import com.google.gson.annotations.SerializedName
data class UserEntity(
@SerializedName("avatar_url") val avatarUrl: String,
@SerializedName("created_at") val createdAt: String?,
@SerializedName("data_id") val dataId: Int?,
@SerializedName("email") val email: String?,
@SerializedName("has_used_organization_trial") val hasUsedOrganizationTrial: Boolean?,
@SerializedName("payment_processor") val paymentProcessor: String?,
@SerializedName("slug") val slug: String,
@SerializedName("username") val username: String
)
| 0 | Kotlin | 0 | 0 | 9639ad21b263fd1ece2383e9ca5a8cd0eb3f2022 | 584 | Bitrise-Kotlin-Sdk | Apache License 2.0 |
compiler/testData/diagnostics/tests/thisAndSuper/QualifiedThis.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // FILE: f.kt
class A() {
fun foo() : Unit {
this@A
this<!UNRESOLVED_REFERENCE!>@a<!>
this
}
val x = this@A.<!DEBUG_INFO_LEAKING_THIS!>foo<!>()
val y = this.<!DEBUG_INFO_LEAKING_THIS!>foo<!>()
val z = <!DEBUG_INFO_LEAKING_THIS!>foo<!>()
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 262 | kotlin | Apache License 2.0 |
app/src/main/java/com/example/kotlin_jetpack/ui/log/LoginViewModel.kt | zzm525465248 | 492,705,951 | false | {"Kotlin": 236095, "Java": 113} | package com.example.kotlin_jetpack.ui.log
import android.text.Editable
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.kotlin_jetpack.Api.OnSellRepository
import com.example.kotlin_jetpack.bean.Login_bena
import com.example.kotlin_jetpack.bean.YzCode_Bean
import kotlinx.coroutines.launch
class LoginViewModel :ViewModel() {
val getcode= MutableLiveData<YzCode_Bean>()
val login= MutableLiveData<Login_bena>()
private val onSellRepository by lazy{
OnSellRepository()
}
fun code(id: Long){
viewModelScope.launch {
val bean=onSellRepository.getCode(id)
getcode.value=bean
}
}
fun getlog(id:Long,yzm:Int){
viewModelScope.launch {
val bean=onSellRepository.Login(id,yzm)
login.value=bean
}
}
} | 0 | Kotlin | 0 | 0 | ff8eddd25b68d671e4eb2de2bcfc67a1e81c48df | 906 | Ordinary_music | Apache License 2.0 |
libraries/tools/new-project-wizard/new-project-wizard-cli/build.gradle.kts | android | 263,405,600 | true | null | plugins {
kotlin("jvm")
id("jps-compatible")
}
dependencies {
implementation(kotlinStdlib())
compileOnly(project(":kotlin-reflect-api"))
implementation(project(":libraries:tools:new-project-wizard"))
implementation("org.yaml:snakeyaml:1.24")
testImplementation(projectTests(":compiler:tests-common"))
testImplementation(project(":kotlin-test:kotlin-test-junit"))
testImplementation(commonDep("junit:junit"))
testImplementation(intellijDep())
}
sourceSets {
"main" { projectDefault() }
"test" { projectDefault() }
}
projectTest {
dependsOn(":dist")
workingDir = rootDir
}
testsJar()
| 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 644 | kotlin | Apache License 2.0 |
epli-backend/src/main/kotlin/ru/epli/features/login/LoginRouting.kt | Uliana2303 | 544,899,725 | false | {"Kotlin": 136839} | package ru.epli.features.login
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import ru.epli.cache.TokenCache
import ru.epli.cache.inMemoryCache
import java.util.*
import kotlin.math.log
fun Application.configureLoginRouting() {
routing {
post("/login") {
val loginController = LoginController(call)
loginController.performLogin()
}
post("/get_user_id") {
val loginController = LoginController(call)
loginController.getUserIdByToken()
}
post("/get_user_email_by_token") {
val loginController = LoginController(call)
loginController.getEmailByToken()
}
post("/get_username_by_token") {
val loginController = LoginController(call)
loginController.getUsernameByToken()
}
}
} | 0 | Kotlin | 1 | 0 | ac10c539bfd1127339b68af95a7c09ffbcdf1685 | 950 | summer-practice | MIT License |
compiler/testData/codegen/box/jvm8/simpleCall.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // TARGET_BACKEND: JVM
// JVM_TARGET: 1.8
interface Test {
fun test(): String {
return "OK"
}
}
class TestClass : Test {
}
fun box(): String {
return TestClass().test()
}
| 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 195 | kotlin | Apache License 2.0 |
idea/idea-new-project-wizard/src/org/jetbrains/kotlin/tools/projectWizard/wizard/IdeWizard.kt | android | 263,405,600 | true | null | package org.jetbrains.kotlin.tools.projectWizard.wizard
import com.intellij.facet.impl.ui.libraries.LibraryOptionsPanel
import com.intellij.framework.library.FrameworkLibraryVersionFilter
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ui.configuration.libraries.CustomLibraryDescription
import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContainer
import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContainerFactory
import org.jetbrains.kotlin.idea.framework.JavaRuntimeLibraryDescription
import org.jetbrains.kotlin.tools.projectWizard.core.PluginsCreator
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.SettingReference
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.SettingType
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.reference
import org.jetbrains.kotlin.tools.projectWizard.core.service.ServicesManager
import org.jetbrains.kotlin.tools.projectWizard.core.service.WizardService
import org.jetbrains.kotlin.tools.projectWizard.plugins.StructurePlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemPlugin
import org.jetbrains.kotlin.tools.projectWizard.plugins.projectTemplates.ProjectTemplatesPlugin
import org.jetbrains.kotlin.tools.projectWizard.wizard.service.IdeaWizardService
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class IdeWizard(
createPlugins: PluginsCreator,
initialServices: List<WizardService>,
isUnitTestMode: Boolean
) : Wizard(
createPlugins,
ServicesManager(initialServices) { services ->
services.firstOrNull { it is IdeaWizardService }
?: services.firstOrNull()
},
isUnitTestMode
) {
init {
initPluginSettingsDefaultValues()
}
val jpsData = JpsData(
JavaRuntimeLibraryDescription(null),
LibrariesContainerFactory.createContainer(null as Project?),
)
var jdk: Sdk? = null
var projectPath by setting(StructurePlugin::projectPath.reference)
var projectName by setting(StructurePlugin::name.reference)
var groupId by setting(StructurePlugin::groupId.reference)
var artifactId by setting(StructurePlugin::artifactId.reference)
var buildSystemType by setting(BuildSystemPlugin::type.reference)
var projectTemplate by setting(ProjectTemplatesPlugin::template.reference)
private fun <V : Any, T : SettingType<V>> setting(reference: SettingReference<V, T>) =
object : ReadWriteProperty<Any?, V?> {
override fun setValue(thisRef: Any?, property: KProperty<*>, value: V?) {
if (value == null) return
context.writeSettings {
reference.setValue(value)
}
}
override fun getValue(thisRef: Any?, property: KProperty<*>): V? = context.read {
reference.notRequiredSettingValue
}
}
data class JpsData(
val libraryDescription: JavaRuntimeLibraryDescription,
val librariesContainer: LibrariesContainer,
val libraryOptionsPanel: LibraryOptionsPanel = LibraryOptionsPanel(
libraryDescription,
"",
FrameworkLibraryVersionFilter.ALL,
librariesContainer,
false
)
)
}
| 15 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 3,399 | kotlin | Apache License 2.0 |
library/process/src/unixMain/kotlin/io/matthewnelson/kmp/process/internal/PlatformBuilder.kt | 05nelsonm | 750,560,085 | false | {"Kotlin": 84234} | /*
* Copyright (c) 2024 <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
*
* 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.
**/
@file:Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING", "KotlinRedundantDiagnosticSuppress")
package io.matthewnelson.kmp.process.internal
import io.matthewnelson.kmp.file.IOException
import io.matthewnelson.kmp.process.Process
import io.matthewnelson.kmp.process.Signal
import io.matthewnelson.kmp.process.Stdio
import io.matthewnelson.kmp.process.internal.PosixSpawnAttrs.Companion.posixSpawnAttrInit
import io.matthewnelson.kmp.process.internal.PosixSpawnFileActions.Companion.posixSpawnFileActionsInit
import kotlinx.cinterop.*
import platform.posix.pid_tVar
// unixMain
internal actual class PlatformBuilder internal actual constructor() {
internal actual val env: MutableMap<String, String> by lazy {
parentEnvironment()
}
@Throws(IOException::class)
@OptIn(ExperimentalForeignApi::class)
internal actual fun build(
command: String,
args: List<String>,
env: Map<String, String>,
stdio: Stdio.Config,
destroy: Signal,
): Process = memScoped {
// TODO: pipes Issue #2
val fileActions = posixSpawnFileActionsInit()
val attrs = posixSpawnAttrInit()
val pid = alloc<pid_tVar>()
// null terminated c-string array
val argv = allocArray<CPointerVar<ByteVar>>(args.size + 2).apply {
// First argument for posix_spawn's argv should be the executable name.
// If command is the absolute path to the executable, take the final
// path argument after last separator.
this[0] = command.substringAfterLast('/').cstr.ptr
var i = 1
val iterator = args.iterator()
while (iterator.hasNext()) {
this[i++] = iterator.next().cstr.ptr
}
this[i] = null
}
// null terminated c-string array
val envp = allocArray<CPointerVar<ByteVar>>(env.size + 1).apply {
var i = 0
val iterator = env.entries.iterator()
while (iterator.hasNext()) {
this[i++] = iterator.next().toString().cstr.ptr
}
this[i] = null
}
val result = if (command.startsWith('/')) {
// Absolute path, utilize posix_spawn
posixSpawn(command, pid.ptr, fileActions, attrs, argv, envp)
} else {
// relative path or program name, utilize posix_spawnp
posixSpawnP(command, pid.ptr, fileActions, attrs, argv, envp)
}
// TODO: close things
result.check()
NativeProcess(
pid.value,
command,
args,
env,
stdio,
destroy,
)
}
}
| 6 | Kotlin | 0 | 0 | e2488e9bae780014f2f57dd6c69af034755b254f | 3,317 | kmp-process | Apache License 2.0 |
framework/src/main/kotlin/dev/alpas/view/ViewConfig.kt | racharya | 235,246,550 | true | {"Kotlin": 381871, "Shell": 1497, "JavaScript": 622, "CSS": 402} | package dev.alpas.view
import dev.alpas.Application
import dev.alpas.Config
import dev.alpas.Environment
open class ViewConfig(env: Environment) : Config {
open val isEnabled = true
open val mixManifestDirectory = env("MIX_MANIFEST_DIRECTORY", "")
open val templatesDirectory = "templates"
open val templateExtension = "peb"
open val webDirectory = "web"
open var cacheTemplates = false
protected set
override fun register(app: Application) {
cacheTemplates = app.env.isProduction
}
open fun configsAvailableForView(): Map<String, String?> = emptyMap()
}
| 0 | null | 0 | 0 | d0fe0d2ebba60a506afd893e46396a61e2e28837 | 611 | alpas | MIT License |
libraries/themes/src/main/java/com/andhiratobing/themes/AppThemeColorBar.kt | andhiratobing | 443,302,737 | false | {"Kotlin": 69028} | package com.andhiratobing.themes
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import com.google.accompanist.systemuicontroller.rememberSystemUiController
@Composable
fun AppThemeColorBar() {
val stateUiController = rememberSystemUiController()
val darkTheme = isSystemInDarkTheme()
stateUiController.setStatusBarColor(
color = if (darkTheme) MaterialTheme.colors.onBackground
else MaterialTheme.colors.onBackground
)
stateUiController.setSystemBarsColor(
color = if (darkTheme) MaterialTheme.colors.onBackground
else MaterialTheme.colors.onBackground
)
stateUiController.setNavigationBarColor(
color = if (darkTheme) MaterialTheme.colors.onBackground
else MaterialTheme.colors.onBackground
)
} | 0 | Kotlin | 0 | 1 | 05495ac44369f5fa11b3b23236f18b65b2241c62 | 877 | movie-compose | Apache License 2.0 |
src/docs/kotlin/model/utils/HelmValuesUtils.kt | chriskn | 547,231,007 | false | {"Kotlin": 24577} | package docsascode.model.utils
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper
import java.io.File
private val yamlParser: ObjectMapper = YAMLMapper()
private val valuesYaml = File("./helm/inventory-service/values.yml").readText()
fun resolveHelmValues(): List<List<String>> {
val test = yamlParser.readValue(
valuesYaml,
object : TypeReference<Map<String, Any>>() {}
)
val properties = mutableListOf<List<String>>()
flattenProperties(test, properties)
return properties.sortedBy { it.first() }
}
private fun flattenProperties(
propertyMap: Map<String, Any>,
keys: MutableList<List<String>>,
parentPath: String = ""
) {
propertyMap.entries
.forEach { (propertyName, propertyValue): Map.Entry<String, Any> ->
val canonicalName = if (parentPath.isNotBlank()) {
"$parentPath.$propertyName"
} else {
propertyName
}
if (propertyValue is Map<*, *>) {
flattenProperties(
propertyValue as Map<String, Any>,
keys,
canonicalName
)
} else {
keys.add(
listOf(canonicalName, propertyValue.toString())
)
}
}
}
| 0 | Kotlin | 4 | 10 | 25902d95d313cb68446d55a6ff1f56151ff2e3a1 | 1,429 | arch-docs-as-code-example | MIT License |
app/src/main/kotlin/ru/cinema/api/episodetime/route/EpisodeTimeRoute.kt | alexBlack01 | 541,182,433 | false | {"Kotlin": 279406, "Procfile": 34} | @file:Suppress("MatchingDeclarationName", "Filename")
package ru.cinema.api.episodetime.route
import io.ktor.resources.Resource
import kotlinx.serialization.Serializable
import ru.cinema.api.common.serializations.UUIDSerializer
import java.util.*
@Serializable
@Resource("episodes/{episodeId}/time")
class EpisodeTime(@Serializable(with = UUIDSerializer::class) val episodeId: UUID)
| 0 | Kotlin | 0 | 0 | 97e1909d029b245c9e1d95a70746a7483073107b | 386 | cinema-backend | Apache License 1.1 |
feature/sample/pkg/src/main/java/com/dawn/sample/pkg/feature/itemViewBinder/StringItemViewBinder.kt | blank-space | 304,529,347 | false | null | package com.dawn.sample.pkg.feature.itemViewBinder
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.dawn.sample.pkg.R
import com.drakeet.multitype.ItemViewBinder
/**
* @author : LeeZhaoXing
* @date : 2020/10/21
* @desc :
*/
class StringItemViewBinder() : ItemViewBinder<String, StringItemViewBinder.TextHolder>() {
override fun onBindViewHolder(holder: TextHolder, item: String) {
holder.title.text = item
}
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): TextHolder {
return TextHolder(
(inflater.inflate(R.layout.feature_sample_pkg_recycle_item_string, parent, false))
)
}
override fun getItemId(item: String): Long {
return item.hashCode().toLong()
}
inner class TextHolder(view: View) : RecyclerView.ViewHolder(view) {
val title = view.findViewById<TextView>(R.id.tv_title)
}
} | 0 | Kotlin | 3 | 15 | 93f4b96cd536f0147402e18d77e96b36da3146b9 | 1,043 | scaffold | Apache License 2.0 |
app/src/main/kotlin/me/sweetll/tucao/model/json/ListResponse.kt | blackbbc | 78,953,199 | false | null | package me.sweetll.tucao.model.json
import com.squareup.moshi.Json
class ListResponse<T> : BaseResponse<MutableList<T>>() {
@Json(name = "total_count")
var totalCount: Int = 0
}
| 13 | Java | 209 | 1,014 | cdae0b953c3fe61c463783de6339e1bea2298fe7 | 188 | Tucao | MIT License |
kotlin/Leaderboard/src/test/kotlin/tddmicroexercises/leaderboard/DriverTest.kt | simonrowe | 359,684,744 | true | {"Java": 19145, "PHP": 17427, "C#": 16147, "C++": 15982, "Kotlin": 13571, "CMake": 11741, "Python": 10924, "Ruby": 8589, "JavaScript": 8485, "Scala": 8044, "TypeScript": 8028, "Meson": 5212, "Go": 3569, "Swift": 1148, "Shell": 366, "Batchfile": 69} | package tddmicroexercises.leaderboard
import org.junit.Test
import org.junit.Assert.assertEquals
internal class DriverTest {
@Test
fun nameShouldBeCorrect() {
val driver = Driver("Name", "Country")
assertEquals("Name" , driver.name)
}
}
| 0 | Java | 0 | 0 | 61ab49df6dbcf4b8551c4a83ff40a7bbe1f543c7 | 255 | Racing-Car-Katas | MIT License |
build.gradle.kts | sekvy | 609,752,760 | false | null | plugins {
alias(deps.plugins.benManesVersions)
alias(deps.plugins.kotlinter)
kotlin("multiplatform")
id("org.jetbrains.compose")
id("org.jetbrains.dokka") version "1.7.10"
id("convention.publication")
}
group = "se.sekvy"
version = "0.1.0-alpha"
repositories {
mavenCentral()
maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
}
kotlin {
js(IR) {
browser {}
binaries.executable()
}
sourceSets {
val jsMain by getting {
dependencies {
implementation(compose.ui)
implementation(compose.foundation)
implementation(compose.material)
implementation(compose.runtime)
}
}
}
} | 0 | Kotlin | 0 | 0 | b26a4685ae478bbf512508933ef2b6312f2e8bd9 | 752 | compose-web-canvas-utils | MIT License |
kgl-vulkan/src/commonMain/kotlin/com/kgl/vulkan/enums/QueryResult.kt | NikkyAI | 168,431,916 | true | {"Kotlin": 1894114, "C": 1742775} | /**
* Copyright [2019] [<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.kgl.vulkan.enums
import com.kgl.vulkan.utils.VkFlag
expect enum class QueryResult : VkFlag<QueryResult> {
`64`,
WAIT,
WITH_AVAILABILITY,
PARTIAL
}
| 0 | Kotlin | 0 | 0 | 51dfa8a4c655ff8bcf017d8d4a2eb660e14473ed | 769 | kgl | Apache License 2.0 |
app/src/main/java/lt/markmerkk/widgets/dialogs/DialogCustomActionWidget.kt | marius-m | 67,072,115 | false | null | package lt.markmerkk.widgets.dialogs
import com.jfoenix.svg.SVGGlyph
import javafx.geometry.Pos
import javafx.scene.Parent
import javafx.scene.input.KeyCombination
import javafx.scene.layout.HBox
import javafx.scene.layout.Priority
import javafx.scene.layout.VBox
import lt.markmerkk.Graphics
import lt.markmerkk.Main
import lt.markmerkk.ResultDispatcher
import lt.markmerkk.Strings
import lt.markmerkk.Styles
import lt.markmerkk.Tags
import lt.markmerkk.ui_2.views.jfxButton
import lt.markmerkk.utils.Logs.withLogInstance
import org.slf4j.LoggerFactory
import tornadofx.*
import javax.inject.Inject
class DialogCustomActionWidget : Fragment() {
@Inject lateinit var resultDispatcher: ResultDispatcher
@Inject lateinit var strings: Strings
@Inject lateinit var graphics: Graphics<SVGGlyph>
init {
Main.component().inject(this)
}
private val dialogBundle: DialogBundle = resultDispatcher
.consume(RESULT_DISPATCH_KEY_BUNDLE, DialogBundle::class.java) ?: DialogBundle.asEmpty()
override val root: Parent = borderpane {
val actionConfirm = {
dialogBundle.onAction.invoke()
close()
}
shortcut(KeyCombination.valueOf("Esc")) { close() }
shortcut(KeyCombination.valueOf("Meta+Enter"), actionConfirm)
shortcut(KeyCombination.valueOf("Ctrl+Enter"), actionConfirm)
addClass(Styles.dialogAlertContainerBig)
top {
hbox(spacing = 4, alignment = Pos.CENTER_LEFT) {
label(dialogBundle.header) {
HBox.setHgrow(this, Priority.ALWAYS)
addClass(Styles.dialogAlertTextH1)
maxWidth = Double.MAX_VALUE
}
}
}
center {
vbox {
label(dialogBundle.content) {
VBox.setVgrow(this, Priority.ALWAYS)
addClass(Styles.dialogAlertContentContainer)
addClass(Styles.dialogAlertTextRegular)
}
}
}
bottom {
hbox(alignment = Pos.CENTER_RIGHT, spacing = 4) {
addClass(Styles.dialogContainerActionsButtons)
jfxButton(dialogBundle.actionTitle) {
setOnAction {
dialogBundle.onAction.invoke()
close()
}
}
jfxButton(strings.getString("generic_dialog_cancel").uppercase()) {
setOnAction {
close()
}
}
}
}
}
override fun onDock() {
super.onDock()
l.debug("onDock(dialogBundle: {})".withLogInstance(this), dialogBundle)
}
override fun onUndock() {
l.debug("onUndock()".withLogInstance(this))
super.onUndock()
}
class DialogBundle(
val header: String,
val content: String,
val actionTitle: String,
val onAction: () -> Unit,
) {
companion object {
fun asEmpty(): DialogBundle {
return DialogBundle(
header = "",
content = "",
actionTitle = "",
onAction = {},
)
}
}
}
companion object {
private val l = LoggerFactory.getLogger(Tags.INTERNAL)!!
const val RESULT_DISPATCH_KEY_BUNDLE = "NeAN11DynbyxzfnyTR6C"
}
} | 1 | Kotlin | 2 | 25 | 6632d6bfd53de4760dbc3764c361f2dcd5b5ebce | 3,493 | wt4 | Apache License 2.0 |
lib/src/main/java/com/drew/metadata/adobe/AdobeJpegDescriptor.kt | baelec | 231,688,360 | true | {"Kotlin": 1579585, "Java": 266990, "CSS": 13481, "DIGITAL Command Language": 117} | /*
* Copyright 2002-2019 <NAME> and contributors
*
* 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.
*
* More information about this project is available at:
*
* https://drewnoakes.com/code/exif/
* https://github.com/drewnoakes/metadata-extractor
*/
package com.drew.metadata.adobe
import com.drew.metadata.TagDescriptor
/**
* Provides human-readable string versions of the tags stored in an AdobeJpegDirectory.
*/
class AdobeJpegDescriptor(directory: AdobeJpegDirectory) : TagDescriptor<AdobeJpegDirectory>(directory) {
override fun getDescription(tagType: Int): String? {
return when (tagType) {
AdobeJpegDirectory.TAG_COLOR_TRANSFORM -> colorTransformDescription
AdobeJpegDirectory.TAG_DCT_ENCODE_VERSION -> dctEncodeVersionDescription
else -> super.getDescription(tagType)
}
}
private val dctEncodeVersionDescription: String?
get() {
val value = _directory.getInteger(AdobeJpegDirectory.TAG_DCT_ENCODE_VERSION)
return if (value == null) null else if (value == 0x64) "100" else value.toString()
}
private val colorTransformDescription: String?
get() = getIndexedDescription(AdobeJpegDirectory.TAG_COLOR_TRANSFORM,
"Unknown (RGB or CMYK)",
"YCbCr",
"YCCK")
}
| 0 | Kotlin | 0 | 0 | 2df8efc24efa24aca040bc4f392d9b9285d23369 | 1,794 | metadata-extractor | Apache License 2.0 |
src/main/kotlin/hn/util/LogsStorage.kt | captswag | 298,839,396 | false | null | package hn.util
import java.io.FileWriter
import java.io.PrintWriter
import java.text.SimpleDateFormat
import java.util.*
private const val LOGS_FILENAME = "logs.txt"
private const val DATE_FORMAT = "dd/MM/yyyy - hh:mm a"
private const val DIVIDER = "-"
class LogsStorage {
private val printWriter = PrintWriter(FileWriter(LOGS_FILENAME, true), true)
fun appendDate() {
val simpleDateFormat = SimpleDateFormat(DATE_FORMAT)
val date = simpleDateFormat.format(Date())
printWriter.println(date)
printWriter.println(DIVIDER.repeat(date.length))
}
fun saveString(text: String) {
printWriter.println(text)
}
fun close() {
printWriter.println()
printWriter.close()
}
} | 0 | Kotlin | 0 | 0 | 773882bfc9f2f818969f43ac427d1f44a62dc43a | 751 | log-hn | MIT License |
compiler/testData/codegen/box/inference/plusAssignInsideLambda.kt | JetBrains | 3,432,266 | false | {"Kotlin": 74444760, "Java": 6669398, "Swift": 4261253, "C": 2620837, "C++": 1953730, "Objective-C": 640870, "Objective-C++": 170766, "JavaScript": 135724, "Python": 48402, "Shell": 30960, "TypeScript": 22754, "Lex": 18369, "Groovy": 17273, "Batchfile": 11693, "CSS": 11368, "Ruby": 10470, "EJS": 5241, "Dockerfile": 5136, "HTML": 5073, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | // WITH_STDLIB
import kotlin.experimental.ExperimentalTypeInference
interface SendChannel<in T> {
suspend fun send(value: T)
}
@OptIn(ExperimentalTypeInference::class)
public fun <T> flux(block: suspend SendChannel<T>.() -> Unit) {}
suspend inline fun <T> T.collect(action: (T) -> Unit) { action(this) }
fun test() {
flux {
var result = ""
"OK".collect { result += it }
send(result)
}
}
fun box() = "OK" | 166 | Kotlin | 5,771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 445 | kotlin | Apache License 2.0 |
feature/feed/src/main/java/com/challenge/android_template/feed/FeedScreen.kt | merRen22 | 392,808,733 | false | null | package com.challenge.android_template.feed
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import coil.compose.rememberImagePainter
import com.challenge.android_template.model.Foo
/**
* Feed screen.
*/
@Composable
fun FeedUI(
foodViewModel: FeedViewModel
) {
val uiState by foodViewModel.fooItems.collectAsState()
Scaffold(
topBar = { FeedTopBar() },
content = {
FeedFooContent(
feedUiState = uiState,
onFooSelected = {
},
modifier = Modifier.fillMaxSize(),
)
}
)
}
@Composable
fun FeedTopBar() {
TopAppBar(
title = { R.string.app_name },
backgroundColor = MaterialTheme.colors.surface,
elevation = 0.dp,
)
}
@Composable
fun FeedFooContent(
feedUiState: FeedUiState,
onFooSelected: (Foo) -> Unit,
modifier: Modifier
) {
LazyColumn(modifier = modifier) {
item {
FooHeading(
text = "Some random text",
modifier = Modifier
.padding(start = 16.dp)
)
}
if (feedUiState.isLoading) {
item {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxWidth()
) {
CircularProgressIndicator(
modifier = Modifier.padding(top = 16.dp)
)
}
}
} else {
items(feedUiState.foos) { foo ->
FooItem(
foo = foo,
onClick = onFooSelected,
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
)
}
}
}
}
@Composable
fun FooHeading(
text: String,
modifier: Modifier = Modifier
) {
Text(
text = text,
style = MaterialTheme.typography.subtitle1,
modifier = modifier
)
}
@Composable
fun FooItem(
foo: Foo,
onClick: (Foo) -> Unit,
modifier: Modifier = Modifier
) {
Surface(
modifier = Modifier.clickable(
enabled = true,
onClick = { onClick(foo) }
)
) {
Row(
modifier = modifier,
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
FooImage(
modifier = Modifier.requiredSize(70.dp)
)
Spacer(modifier = Modifier.width(8.dp))
FooName(
modifier = Modifier
.weight(1f)
.padding(end = 8.dp),
foo = foo
)
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
IconButton(onClick = { /*TODO*/ }) {
Icon(
painter = painterResource(id = R.drawable.ic_baseline_more_vert_24),
contentDescription = "More icon"
)
}
}
}
}
}
@Composable
fun FooName(
modifier: Modifier = Modifier,
foo: Foo
) {
Column(modifier = modifier) {
Spacer(modifier = Modifier.height(2.dp))
Text(
text = foo.name,
style = MaterialTheme.typography.body1,
maxLines = 1
)
Spacer(modifier = Modifier.height(4.dp))
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Text(
text = foo.name,
style = MaterialTheme.typography.body2,
)
}
}
}
@Composable
fun FooImage(
modifier: Modifier = Modifier,
shape: RoundedCornerShape = RoundedCornerShape(4.dp),
elevation: Dp = 0.dp
) {
Surface(shape = shape, elevation = elevation) {
Image(
painter = rememberImagePainter(
data = "https://picsum.photos/200/300",
builder = {
crossfade(true)
error(R.drawable.ic_launcher_foreground)
placeholder(R.drawable.ic_launcher_foreground)
}
),
contentDescription = "Foo Image",
modifier = modifier,
contentScale = ContentScale.Crop,
alignment = Alignment.TopCenter
)
}
} | 0 | Kotlin | 0 | 0 | e94b54a1b9f4786315bfdf6caf81445fc89b9fab | 4,441 | template-android | Apache License 2.0 |
app/src/main/java/com/ryanhtech/vocabulario/tools/collection/db/CollectionData.kt | Ryanhtech | 445,900,317 | false | {"Kotlin": 414071} | /*
* Copyright 2021-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.ryanhtech.vocabulario.tools.collection.db
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.ryanhtech.vocabulario.tools.collection.wordpointers.WordPointer
import java.util.*
@Entity(tableName="word_group")
data class CollectionData (
@PrimaryKey(autoGenerate = true) val wid: Int,
@ColumnInfo(name="date") val date: Calendar,
@ColumnInfo(name="title") val title: String,
@ColumnInfo(name="content") val content: List<WordPointer>,
) | 0 | Kotlin | 0 | 0 | 0822b13273167e0db581b42ebf6f8219e8f509d7 | 1,130 | vocabulario | Apache License 2.0 |
plugin-build/plugin/src/test/kotlin/io/github/adityabhaskar/dependencygraph/plugin/DependencyGraphTest.kt | adityabhaskar | 624,785,217 | false | {"Kotlin": 34506} | package io.github.adityabhaskar.dependencygraph.plugin
import org.gradle.testfixtures.ProjectBuilder
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Test
class DependencyGraphTest {
@Test
fun `plugin is applied correctly to the project`() {
val project = ProjectBuilder.builder().build()
project.pluginManager.apply("io.github.adityabhaskar.dependencygraph")
assert(project.tasks.getByName("dependencyGraph") is DependencyGraphTask)
}
@Test
fun `extension dependencyGraphConfig is created correctly`() {
val project = ProjectBuilder.builder().build()
project.pluginManager.apply("io.github.adityabhaskar.dependencygraph")
assertNotNull(project.extensions.getByName("dependencyGraphConfig"))
}
@Test
fun `parameters are passed correctly from extension to task`() {
val project = ProjectBuilder.builder().build()
project.pluginManager.apply("io.github.adityabhaskar.dependencygraph")
(project.extensions.getByName("dependencyGraphConfig") as DependencyGraphExtension).apply {
graphDirection.set(Direction.BottomToTop)
graphFileName.set("A_GRAPH.MD")
mainBranchName.set("master")
repoRootUrl.set("https://c306.net/")
showLegend.set(ShowLegend.Never)
}
val task = project.tasks.getByName("dependencyGraph") as DependencyGraphTask
assertEquals(Direction.BottomToTop, task.graphDirection.get())
assertEquals("A_GRAPH.MD", task.graphFileName.get())
assertEquals("master", task.mainBranchName.get())
assertEquals("https://c306.net/", task.repoRootUrl.get())
assertEquals(ShowLegend.Never, task.showLegend.get())
}
} | 4 | Kotlin | 1 | 5 | 82836716426c381c683b89fd2863f91fbac5caac | 1,785 | Gradle-dependency-graphs | MIT License |
workflow-ui/container-common/src/main/java/com/squareup/workflow1/ui/backstack/BackStackScreen.kt | vng-sq | 705,389,576 | true | {"Kotlin": 1486315, "Shell": 2325, "Ruby": 1690, "Java": 1182} | @file:Suppress("DEPRECATION")
package com.squareup.workflow1.ui.backstack
import com.squareup.workflow1.ui.Screen
import com.squareup.workflow1.ui.WorkflowUiExperimentalApi
import com.squareup.workflow1.ui.asScreen
import com.squareup.workflow1.ui.container.BackStackScreen as NewBackStackScreen
/**
* Represents an active screen ([top]), and a set of previously visited screens to which we may
* return ([backStack]). By rendering the entire history we allow the UI to do things like maintain
* cached view state, implement drag-back gestures without waiting for the workflow, etc.
*
* Effectively a list that can never be empty.
*
* If multiple [BackStackScreen]s are used as sibling renderings within the same parent navigation
* container (either the root activity or another [BackStackScreen]), then the siblings must be
* distinguished by wrapping them in [Named][com.squareup.workflow1.ui.Named] renderings in order to
* correctly support AndroidX `SavedStateRegistry`.
*
* @param bottom the bottom-most entry in the stack
* @param rest the rest of the stack, empty by default
*/
@WorkflowUiExperimentalApi
@Deprecated("Use com.squareup.workflow1.ui.container.BackStackScreen")
public class BackStackScreen<StackedT : Any>(
bottom: StackedT,
rest: List<StackedT>
) {
/**
* Creates a screen with elements listed from the [bottom] to the top.
*/
public constructor(
bottom: StackedT,
vararg rest: StackedT
) : this(bottom, rest.toList())
public val frames: List<StackedT> = listOf(bottom) + rest
/**
* The active screen.
*/
public val top: StackedT = frames.last()
/**
* Screens to which we may return.
*/
public val backStack: List<StackedT> = frames.subList(0, frames.size - 1)
public operator fun get(index: Int): StackedT = frames[index]
public operator fun plus(other: BackStackScreen<StackedT>?): BackStackScreen<StackedT> {
return if (other == null) {
this
} else {
BackStackScreen(frames[0], frames.subList(1, frames.size) + other.frames)
}
}
public fun <R : Any> map(transform: (StackedT) -> R): BackStackScreen<R> {
return frames.map(transform)
.toBackStackScreen()
}
public fun <R : Any> mapIndexed(transform: (index: Int, StackedT) -> R): BackStackScreen<R> {
return frames.mapIndexed(transform)
.toBackStackScreen()
}
override fun equals(other: Any?): Boolean {
return (other as? BackStackScreen<*>)?.frames == frames
}
override fun hashCode(): Int {
return frames.hashCode()
}
override fun toString(): String {
return "${this::class.java.simpleName}($frames)"
}
}
@WorkflowUiExperimentalApi
public fun <T : Any> List<T>.toBackStackScreenOrNull(): BackStackScreen<T>? = when {
isEmpty() -> null
else -> toBackStackScreen()
}
@WorkflowUiExperimentalApi
public fun <T : Any> List<T>.toBackStackScreen(): BackStackScreen<T> {
require(isNotEmpty())
return BackStackScreen(first(), subList(1, size))
}
@WorkflowUiExperimentalApi
public fun BackStackScreen<*>.asNonLegacy(): NewBackStackScreen<Screen> {
return NewBackStackScreen(
bottom = asScreen(frames.first()),
rest = when (frames.size) {
1 -> emptyList()
else -> frames.takeLast(frames.count() - 1).map { asScreen(it) }
}
)
}
| 0 | null | 0 | 0 | d60d8959aab72b699950d20c8fd7364aa08dd219 | 3,288 | workflow-kotlin | Apache License 2.0 |
app/src/main/java/com/codersandeep/shopeaze/ui/profile/ProfileFragment.kt | coder-sandeep | 685,632,917 | false | {"Kotlin": 33597} | package com.codersandeep.shopeaze.ui.profile
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.navigation.fragment.findNavController
import com.codersandeep.shopeaze.R
import com.codersandeep.shopeaze.databinding.FragmentHomeBinding
import com.codersandeep.shopeaze.databinding.FragmentProfileBinding
import com.codersandeep.shopeaze.utils.TokenManager
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class ProfileFragment : Fragment() {
private var _binding: FragmentProfileBinding? = null
private val binding get() = _binding!!
@Inject
lateinit var tokenManager : TokenManager
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
_binding = FragmentProfileBinding.inflate(inflater,container,false)
if (tokenManager.getToken().isNullOrBlank()) {
binding.layoutLogged.visibility = View.INVISIBLE
binding.layoutNotLogged.visibility = View.VISIBLE
}else{
binding.layoutLogged.visibility = View.VISIBLE
binding.layoutNotLogged.visibility = View.INVISIBLE
}
binding.buttonSendToLogin.setOnClickListener(){
val action = ProfileFragmentDirections.actionProfileFragmentToAuthActivity()
findNavController().navigate(action)
}
binding.buttonLogout.setOnClickListener(){
tokenManager.deleteToken()
Toast.makeText(context, "Logged out", Toast.LENGTH_LONG).show()
}
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
}
| 0 | Kotlin | 0 | 0 | a4e4cd55568223563eb66e97ab633da5e8ed9553 | 1,955 | ShopEaze | Apache License 2.0 |