path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/moony/calc/base/BaseFragment.kt | doctor-blue | 335,141,170 | false | {"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "XML": 121, "Java": 8, "Kotlin": 71, "Diff": 2} | package com.moony.calc.base
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
abstract class BaseFragment : Fragment() {
private lateinit var binding: ViewDataBinding
protected var fragmentActivity: FragmentActivity? = null
protected var baseContext: Context?=null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false)
fragmentActivity = activity
baseContext = activity
return binding.root
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initControls(view, savedInstanceState)
initEvents()
}
abstract fun getLayoutId(): Int
abstract fun initControls(view: View, savedInstanceState: Bundle?)
abstract fun initEvents()
fun getViewBinding():ViewDataBinding{
return binding
}
}
| 0 | Kotlin | 0 | 1 | cc01c2c7daaeb26be5354a357dbdb5d8844bb538 | 1,441 | moony-calc | Apache License 2.0 |
app/src/internal/java/com/kickstarter/ui/activities/FeatureFlagsActivity.kt | SaadMakhalSaad2 | 316,064,748 | false | null | package com.kickstarter.ui.activities
import android.os.Bundle
import android.view.View
import androidx.annotation.StringRes
import com.kickstarter.R
import com.kickstarter.libs.BaseActivity
import com.kickstarter.libs.preferences.BooleanPreferenceType
import com.kickstarter.libs.qualifiers.RequiresActivityViewModel
import com.kickstarter.libs.rx.transformers.Transformers.observeForUI
import com.kickstarter.libs.utils.BooleanUtils
import com.kickstarter.ui.adapters.FeatureFlagsAdapter
import com.kickstarter.ui.itemdecorations.TableItemDecoration
import com.kickstarter.viewmodels.FeatureFlagsViewModel
import kotlinx.android.synthetic.internal.activity_feature_flags.*
import kotlinx.android.synthetic.internal.item_feature_flag_override.view.*
@RequiresActivityViewModel(FeatureFlagsViewModel.ViewModel::class)
class FeatureFlagsActivity : BaseActivity<FeatureFlagsViewModel.ViewModel>() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_feature_flags)
val configFlagsAdapter = FeatureFlagsAdapter()
config_flags.adapter = configFlagsAdapter
config_flags.addItemDecoration(TableItemDecoration())
val optimizelyFlagsAdapter = FeatureFlagsAdapter()
optimizely_flags.adapter = optimizelyFlagsAdapter
optimizely_flags.addItemDecoration(TableItemDecoration())
this.viewModel.outputs.configFeatures()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { configFlagsAdapter.takeFlags(it) }
this.viewModel.outputs.optimizelyFeatures()
.compose(bindToLifecycle())
.compose(observeForUI())
.subscribe { optimizelyFlagsAdapter.takeFlags(it) }
}
private fun displayPreference(@StringRes labelRes: Int, booleanPreferenceType: BooleanPreferenceType, overrideContainer: View) {
overrideContainer.override_label.setText(labelRes)
val switch = overrideContainer.override_switch
switch.isChecked = booleanPreferenceType.get()
overrideContainer.setOnClickListener {
booleanPreferenceType.set(BooleanUtils.negate(booleanPreferenceType.get()))
switch.isChecked = booleanPreferenceType.get()
}
}
}
| 0 | null | 0 | 2 | 4e002f3a4a1c53218570ef1721511e3373109d4d | 2,335 | android-oss | Apache License 2.0 |
app/src/main/java/com/example/protasks/models/Message.kt | Albertocalib | 242,500,041 | false | {"Java": 755257, "Kotlin": 300094, "Dockerfile": 226} | package com.example.protasks.models
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
class Message(
@Expose
@SerializedName("body")
private var body: String? = null,
@Expose
@SerializedName("user")
private var user: User? = null,
@Expose
@SerializedName("task")
private var task: Task? = null
) {
@Expose
@SerializedName("id")
private var id: Long = 0
fun setId(id: Long) {
this.id = id
}
fun getId(): Long {
return id
}
fun getBody(): String? {
return body
}
fun setBody(body: String?) {
this.body = body
}
fun getTask(): Task? {
return task
}
fun setTask(task: Task) {
this.task = task
}
fun getUser(): User? {
return user
}
fun setUser(user: User) {
this.user = user
}
} | 1 | null | 1 | 1 | cc220ee5316ce340d43137bcf129256db919f45e | 907 | ProTasks | MIT License |
gateway/src/main/java/gcu/product/gateway/di/GatewayModule.kt | Ilyandr | 584,776,484 | false | {"Java": 408363, "Kotlin": 191825, "AIDL": 15199} | package gcu.product.gateway.di
import dagger.Module
import dagger.Provides
import dagger.Reusable
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ViewModelComponent
import gcu.product.gateway.network.api.PaymentsApi
import gcu.product.gateway.network.api.VpnDefaultApi
import gcu.product.gateway.network.connections.VpnGateway
import gcu.product.gateway.network.connections.VpnGatewayImpl
import gcu.product.gateway.network.payments.PaymentsGateway
import gcu.product.gateway.network.payments.PaymentsGatewayImpl
@Module
@InstallIn(ViewModelComponent::class)
internal class GatewayModule {
@Provides
@Reusable
fun provideConnectionGateway(api: VpnDefaultApi): VpnGateway = VpnGatewayImpl(api)
@Provides
@Reusable
fun providePaymentsGateway(api: PaymentsApi): PaymentsGateway = PaymentsGatewayImpl(api)
} | 1 | null | 1 | 1 | a47d4fee515c7a155cadd2eaa967f6dc38b4fed1 | 850 | Supple-VPN | MIT License |
amazingmvp-kotlin/src/main/java/com/amazingmvpkotlin/ui/adapter/recyclerView/SubGenreAdapter.kt | ppamorim | 53,759,790 | false | null | /*
* Copyright (C) 2016 <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.amazingmvpkotlin.ui.adapter.recyclerView
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.amazingmvpkotlin.R
import com.amazingmvpkotlin.ui.adapter.viewHolder.SubGenreViewHolder
import com.github.ppamorim.amazingmvpkotlinrules.domain.model.SubGenre
class SubGenreAdapter(var subGenres: List<SubGenre>): RecyclerView.Adapter<SubGenreViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int) =
SubGenreViewHolder(LayoutInflater.from(parent!!.context)
.inflate(R.layout.adapter_genre, parent, false))
override fun onBindViewHolder(holder: SubGenreViewHolder?, position: Int) {
holder?.configView(getItemAtPosition(position))
}
override fun getItemCount() = subGenres.count()
fun getItemAtPosition(position: Int) = subGenres.getOrNull(position)
}
| 1 | null | 1 | 1 | 7e19db8d41f86ad1ad7d8497a9d024ba30cbabe7 | 1,462 | Amazing-MVP-Kotlin | MIT License |
jetbrains-core/src/software/aws/toolkits/jetbrains/services/dynamodb/actions/DeleteTableAction.kt | JetBrains | 223,485,227 | true | {"Gradle Kotlin DSL": 21, "Markdown": 16, "Java Properties": 2, "Shell": 1, "Text": 12, "Ignore List": 3, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 3, "YAML": 28, "XML": 96, "Kotlin": 1102, "JSON": 54, "Java": 9, "SVG": 64, "TOML": 1, "INI": 1, "CODEOWNERS": 1, "Maven POM": 4, "Dockerfile": 14, "JavaScript": 3, "Python": 5, "Go": 1, "Go Module": 1, "Microsoft Visual Studio Solution": 6, "C#": 79} | // Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package software.aws.toolkits.jetbrains.services.dynamodb.actions
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.fileEditor.FileEditorManager
import software.amazon.awssdk.services.dynamodb.DynamoDbClient
import software.aws.toolkits.jetbrains.core.awsClient
import software.aws.toolkits.jetbrains.core.explorer.actions.DeleteResourceAction
import software.aws.toolkits.jetbrains.core.explorer.refreshAwsTree
import software.aws.toolkits.jetbrains.services.dynamodb.DynamoDbResources
import software.aws.toolkits.jetbrains.services.dynamodb.editor.DynamoDbVirtualFile
import software.aws.toolkits.jetbrains.services.dynamodb.explorer.DynamoDbTableNode
class DeleteTableAction : DeleteResourceAction<DynamoDbTableNode>() {
override fun performDelete(selected: DynamoDbTableNode) {
val project = selected.nodeProject
val client = project.awsClient<DynamoDbClient>()
val fileEditorManager = FileEditorManager.getInstance(selected.nodeProject)
fileEditorManager.openFiles.forEach {
if (it is DynamoDbVirtualFile && it.tableArn == selected.resourceArn()) {
// Wait so that we know it closes successfully, otherwise this operation is not a success
ApplicationManager.getApplication().invokeAndWait {
fileEditorManager.closeFile(it)
}
}
}
client.deleteTable { it.tableName(selected.displayName()) }
project.refreshAwsTree(DynamoDbResources.LIST_TABLES)
}
}
| 6 | Kotlin | 4 | 9 | ccee3307fe58ad48f93cd780d4378c336ee20548 | 1,665 | aws-toolkit-jetbrains | Apache License 2.0 |
core-data-ace/src/main/java/co/llanox/alacartaexpress/mobile/LaCoroErrorHandler.kt | LaCoro | 303,470,569 | false | null | package co.llanox.alacartaexpress.mobile
import android.content.Context
import android.widget.Toast
import com.google.firebase.crashlytics.FirebaseCrashlytics
import com.mobile.llanox.acedatacore.R
import com.parse.ParseException
/**
* Created by jgabrielgutierrez on 15-10-17.
*/
object LaCoroErrorHandler : ErrorHandler {
override fun showHumanReadableError(error: Throwable, ctx: Context): Int {
if (error is ParseException) {
val code = error.code
if (ParseException.EMAIL_TAKEN == code || ParseException.USERNAME_TAKEN == code) {
Toast.makeText(ctx, ctx.getString(R.string.backend_err_email_already_taken), Toast.LENGTH_LONG).show()
return ParseException.EMAIL_TAKEN
}
Toast.makeText(ctx, ctx.getString(R.string.err_general_error, code), Toast.LENGTH_LONG).show()
}
return -1
}
override fun updateCurrentUserID() {
val crashlytics = FirebaseCrashlytics.getInstance()
crashlytics.setUserId(ACEUtil.getCurrentUserID())
}
override fun addInfoToLogger(key: String, value: String) {
val crashlytics = FirebaseCrashlytics.getInstance()
crashlytics.setCustomKey(key,value)
}
override fun onError(error: Throwable) {
val crashlytics = FirebaseCrashlytics.getInstance()
crashlytics.recordException(error)
}
}
| 1 | null | 1 | 1 | 3b98a6e85251c7c174a35182740c5191a37183ff | 1,398 | ManagerAndroidApp | MIT License |
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/extensions/metadata.kt | pambrose | 219,052,707 | false | null | // GENERATED
package com.fkorotkov.kubernetes.extensions
import io.fabric8.kubernetes.api.model.ListMeta as model_ListMeta
import io.fabric8.kubernetes.api.model.ObjectMeta as model_ObjectMeta
import io.fabric8.kubernetes.api.model.extensions.Ingress as extensions_Ingress
import io.fabric8.kubernetes.api.model.extensions.IngressList as extensions_IngressList
import io.fabric8.kubernetes.api.model.extensions.PodSecurityPolicy as extensions_PodSecurityPolicy
import io.fabric8.kubernetes.api.model.extensions.PodSecurityPolicyList as extensions_PodSecurityPolicyList
import io.fabric8.kubernetes.api.model.extensions.Scale as extensions_Scale
fun extensions_Ingress.`metadata`(block: model_ObjectMeta.() -> Unit = {}) {
if(this.`metadata` == null) {
this.`metadata` = model_ObjectMeta()
}
this.`metadata`.block()
}
fun extensions_IngressList.`metadata`(block: model_ListMeta.() -> Unit = {}) {
if(this.`metadata` == null) {
this.`metadata` = model_ListMeta()
}
this.`metadata`.block()
}
fun extensions_PodSecurityPolicy.`metadata`(block: model_ObjectMeta.() -> Unit = {}) {
if(this.`metadata` == null) {
this.`metadata` = model_ObjectMeta()
}
this.`metadata`.block()
}
fun extensions_PodSecurityPolicyList.`metadata`(block: model_ListMeta.() -> Unit = {}) {
if(this.`metadata` == null) {
this.`metadata` = model_ListMeta()
}
this.`metadata`.block()
}
fun extensions_Scale.`metadata`(block: model_ObjectMeta.() -> Unit = {}) {
if(this.`metadata` == null) {
this.`metadata` = model_ObjectMeta()
}
this.`metadata`.block()
}
| 1 | null | 1 | 1 | 95d79afaf5e0353fc0efcb2842df72f026ae5081 | 1,595 | k8s-kotlin-dsl | MIT License |
python/pydevSrc/com/jetbrains/python/debugger/pydev/InterruptDebugConsoleCommand.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.debugger.pydev
class InterruptDebugConsoleCommand(debugger: RemoteDebugger) : AbstractCommand<Any>(debugger, INTERRUPT_DEBUG_CONSOLE) {
override fun buildPayload(payload: Payload?) {}
} | 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 376 | intellij-community | Apache License 2.0 |
clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/CreateRunRequest.kt | oapicf | 529,246,487 | false | {"Markdown": 6348, "YAML": 73, "Text": 16, "Ignore List": 52, "JSON": 1138, "Makefile": 3, "JavaScript": 1042, "F#": 585, "XML": 468, "Shell": 47, "Batchfile": 10, "Scala": 2313, "INI": 31, "Dockerfile": 17, "Maven POM": 22, "Java": 6356, "Emacs Lisp": 1, "Haskell": 39, "Swift": 263, "Ruby": 555, "OASv3-yaml": 19, "Cabal Config": 2, "Go": 1036, "Go Checksums": 1, "Go Module": 4, "CMake": 11, "C++": 3617, "TOML": 5, "Rust": 268, "Nim": 253, "Perl": 252, "Microsoft Visual Studio Solution": 2, "C#": 778, "HTML": 257, "Xojo": 507, "Gradle": 20, "R": 503, "JSON with Comments": 8, "QMake": 1, "Kotlin": 1548, "Python": 1600, "Crystal": 486, "ApacheConf": 2, "PHP": 1715, "Gradle Kotlin DSL": 1, "Protocol Buffer": 250, "C": 752, "Ada": 16, "Objective-C": 522, "Java Properties": 2, "Erlang": 521, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 501, "SQL": 242, "AsciiDoc": 1, "CSS": 3, "PowerShell": 507, "Elixir": 5, "Apex": 426, "Gemfile.lock": 1, "Option List": 2, "Eiffel": 277, "Gherkin": 1, "Dart": 500, "Groovy": 251, "Elm": 13} | package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import org.openapitools.model.AssistantObjectToolsInner
import org.openapitools.model.AssistantsApiResponseFormatOption
import org.openapitools.model.AssistantsApiToolChoiceOption
import org.openapitools.model.CreateMessageRequest
import org.openapitools.model.CreateRunRequestModel
import org.openapitools.model.TruncationObject
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Email
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import javax.validation.Valid
import io.swagger.v3.oas.annotations.media.Schema
/**
*
* @param assistantId The ID of the [assistant](/docs/api-reference/assistants) to use to execute this run.
* @param model
* @param instructions Overrides the [instructions](/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis.
* @param additionalInstructions Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions.
* @param additionalMessages Adds additional messages to the thread before creating the run.
* @param tools Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis.
* @param metadata Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long.
* @param temperature What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.
* @param stream If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message.
* @param maxPromptTokens The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `complete`. See `incomplete_details` for more info.
* @param maxCompletionTokens The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `complete`. See `incomplete_details` for more info.
* @param truncationStrategy
* @param toolChoice
* @param responseFormat
*/
data class CreateRunRequest(
@Schema(example = "null", required = true, description = "The ID of the [assistant](/docs/api-reference/assistants) to use to execute this run.")
@get:JsonProperty("assistant_id", required = true) val assistantId: kotlin.String,
@field:Valid
@Schema(example = "null", description = "")
@get:JsonProperty("model") val model: CreateRunRequestModel? = null,
@Schema(example = "null", description = "Overrides the [instructions](/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis.")
@get:JsonProperty("instructions") val instructions: kotlin.String? = null,
@Schema(example = "null", description = "Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions.")
@get:JsonProperty("additional_instructions") val additionalInstructions: kotlin.String? = null,
@field:Valid
@Schema(example = "null", description = "Adds additional messages to the thread before creating the run.")
@get:JsonProperty("additional_messages") val additionalMessages: kotlin.collections.List<CreateMessageRequest>? = null,
@field:Valid
@get:Size(max=20)
@Schema(example = "null", description = "Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis.")
@get:JsonProperty("tools") val tools: kotlin.collections.List<AssistantObjectToolsInner>? = null,
@field:Valid
@Schema(example = "null", description = "Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format. Keys can be a maximum of 64 characters long and values can be a maxium of 512 characters long. ")
@get:JsonProperty("metadata") val metadata: kotlin.Any? = null,
@get:DecimalMin("0")
@get:DecimalMax("2")
@Schema(example = "1", description = "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. ")
@get:JsonProperty("temperature") val temperature: java.math.BigDecimal? = java.math.BigDecimal("1"),
@Schema(example = "null", description = "If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message. ")
@get:JsonProperty("stream") val stream: kotlin.Boolean? = null,
@get:Min(256)
@Schema(example = "null", description = "The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `complete`. See `incomplete_details` for more info. ")
@get:JsonProperty("max_prompt_tokens") val maxPromptTokens: kotlin.Int? = null,
@get:Min(256)
@Schema(example = "null", description = "The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `complete`. See `incomplete_details` for more info. ")
@get:JsonProperty("max_completion_tokens") val maxCompletionTokens: kotlin.Int? = null,
@field:Valid
@Schema(example = "null", description = "")
@get:JsonProperty("truncation_strategy") val truncationStrategy: TruncationObject? = null,
@field:Valid
@Schema(example = "null", description = "")
@get:JsonProperty("tool_choice") val toolChoice: AssistantsApiToolChoiceOption? = null,
@field:Valid
@Schema(example = "null", description = "")
@get:JsonProperty("response_format") val responseFormat: AssistantsApiResponseFormatOption? = null
) {
}
| 2 | Java | 0 | 4 | c04dc03fa17b816be6e9a262c047840301c084b6 | 7,218 | openapi-openai | MIT License |
example/src/main/java/com/e16din/sc/example/screens/splash/SplashScreen.kt | e16din | 108,880,916 | false | {"Gradle": 6, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 20, "XML": 33, "Java": 29} | package com.e16din.sc.example.screens.splash
import android.content.pm.ActivityInfo
import com.e16din.sc.example.R
import com.e16din.sc.screens.Screen
class SplashScreen : Screen() {
init {
layout = R.layout.screen_splash
isFullScreen = true
theme = R.style.AppTheme_NoActionBar
orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
}
| 1 | null | 1 | 1 | c48444e34c82b446075f34895a9b82119b38a54e | 380 | ScreensController | MIT License |
AndroidCommonBaseFrameLibraryFromLorenWang/src/main/java/android/lorenwang/commonbaseframe/network/callback/AcbflwRepOptionsByPresenterCallback.kt | Seachal | 357,416,119 | false | {"INI": 7, "JSON": 6, "Gradle": 17, "Shell": 2, "Markdown": 21, "Text": 1, "Ignore List": 14, "Java": 498, "Kotlin": 158, "Java Properties": 5, "Proguard": 11, "XML": 184, "JavaScript": 11, "robots.txt": 1, "HTML": 1, "CSS": 2, "SVG": 1} | package android.lorenwang.commonbaseframe.network.callback
import android.lorenwang.commonbaseframe.network.file.AcbflwFileUpLoadBean
/**
* 功能作用:响应数据操作回调,主要针对于在presenter基类处理后的回调,下一步就是扩展处理数据后给到view层
* 创建时间:2019-12-11 10:14
* 创建人:王亮(<NAME>)
* 思路:
* 方法:
* 注意:
* 修改人:
* 修改时间:
* 备注:该类放到presenter中,因为mvp中的p层负责m数据和v的中间连接,而该回调是用来对m数据层从接口获取到的数据之后的
* 一些处理,例如当activity被结束后不调用该方法给view层展示数据等
*/
abstract class AcbflwRepOptionsByPresenterCallback<T> {
/**
* 返回view操作数据
*/
abstract fun viewOptionsData(data: T)
/**
* 响应数据异常
* @param code 错误码
*/
open fun repDataError(code: Any?, message: String?){}
/**
* 文件上传进度
*
* @param bean 文件实例
* @param total 文件上传总容量
* @param nowUpload 当前已上传数据
* @param process 上传进度,0-1之间
*/
open fun fileUpLoadProcess(bean: AcbflwFileUpLoadBean, total: Long, nowUpload: Long, process: Double) {}
}
| 1 | null | 1 | 1 | 7690a5b15ad84faa88856a57dba9145fcea0126b | 916 | LorenWangCustomTools | Apache License 2.0 |
mobile_app1/module364/src/main/java/module364packageKt0/Foo1416.kt | uber-common | 294,831,672 | false | null | package module364packageKt0;
annotation class Foo1416Fancy
@Foo1416Fancy
class Foo1416 {
fun foo0(){
module364packageKt0.Foo1415().foo6()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
fun foo4(){
foo3()
}
fun foo5(){
foo4()
}
fun foo6(){
foo5()
}
} | 6 | null | 6 | 72 | 9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e | 331 | android-build-eval | Apache License 2.0 |
idea/testData/checker/unmetTraitRequirements.kt | EasyKotlin | 93,485,627 | false | null | open class Base {
}
interface Derived: <warning>Base</warning> {
fun foo() {
f1(this@Derived)
}
}
<error>class DerivedImpl</error>(): Derived {}
<error>object ObjectImpl</error>: Derived {}
fun f1(b: Base) = b
// KT-3006 | 0 | null | 0 | 1 | 133e9354a4ccec21eb4d226cf3f6c1f3da072309 | 240 | exp | Apache License 2.0 |
app/src/main/java/com/pmpavan/githubpullrequests/ui/GithubActivity.kt | pmpavan | 139,534,771 | false | {"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Java": 2, "XML": 19, "Kotlin": 47} | package com.pmpavan.githubpullrequests.ui
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProvider
import android.arch.lifecycle.ViewModelProviders
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.widget.Toast
import com.pmpavan.githubpullrequests.R
import com.pmpavan.githubpullrequests.databinding.ActivityMainBinding
import com.pmpavan.githubpullrequests.ui.base.BaseActivity
import com.pmpavan.githubpullrequests.ui.util.UiUtils
import com.pmpavan.githubpullrequests.viewmodel.PullRequestListAdapter
import com.pmpavan.githubpullrequests.viewmodel.PullRequestViewModel
import com.pmpavan.githubpullrequests.viewmodel.constants.PullRequestConstants
import com.pmpavan.githubpullrequests.viewmodel.events.MainActivityEvent
import com.pmpavan.githubpullrequests.viewmodel.uistate.PullRequestUiState
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import javax.inject.Inject
class GithubActivity : BaseActivity() {
@Inject
lateinit var eventBus: EventBus
@Inject
lateinit var factory: ViewModelProvider.Factory
@Inject
lateinit var adapter: PullRequestListAdapter
@Inject
lateinit var listState: PullRequestUiState
private lateinit var viewDataBinding: ActivityMainBinding
private lateinit var viewModel: PullRequestViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
registerForEvents(eventBus)
invokeDataBinding()
setupControllers()
}
private fun setupControllers() {
adapter.handler = viewModel
// viewDataBinding.list.addItemDecoration(SimpleDividerItemDecoration(this))
viewDataBinding.list.adapter = adapter
viewDataBinding.requests = listState
viewModel.data.observe(this@GithubActivity, Observer { t ->
listState.update(t!!)
})
}
private fun invokeDataBinding() {
viewModel = ViewModelProviders.of(this@GithubActivity, factory).get(PullRequestViewModel::class.java)
viewDataBinding = DataBindingUtil.setContentView(this@GithubActivity, R.layout.activity_main)
viewDataBinding.vm = viewModel
viewDataBinding.executePendingBindings()
}
override fun onStop() {
super.onStop()
unregisterForEvents(eventBus)
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onViewModelInteraction(mainActivityEvent: MainActivityEvent) {
when (mainActivityEvent.id) {
PullRequestConstants.ON_SEARCH_ERROR -> {
Toast.makeText(this@GithubActivity, mainActivityEvent.message, Toast.LENGTH_SHORT).show()
}
PullRequestConstants.CLOSE_KEYBOARD -> {
UiUtils.hideKeyboard(this, viewDataBinding.projectName.editText)
}
}
}
}
| 1 | null | 1 | 1 | 49fdbbd1ffccdf372b60774cfc249d9ebd29325f | 2,963 | GithubPullRequests | MIT License |
scrimage-tests/src/test/kotlin/com/sksamuel/scrimage/core/nio/MultipleImagaeLoaderExceptionErrorTest.kt | sksamuel | 10,459,209 | false | null | package com.sksamuel.scrimage.core.nio
import com.sksamuel.scrimage.nio.ImageSource
import com.sksamuel.scrimage.nio.ImmutableImageLoader
import io.kotest.assertions.throwables.shouldThrowAny
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.string.shouldMatch
class MultipleImagaeLoaderExceptionErrorTest : FunSpec() {
init {
test("multiple image load failures should all be reported") {
val bytes = byteArrayOf(1, 2, 3)
val e = shouldThrowAny {
ImmutableImageLoader.create().load(ImageSource.of(bytes))
}
e.message shouldMatch """Image parsing failed. Tried the following ImageReader implementations:
com.sksamuel.scrimage.nio.ImageIOReader@.*? failed due to No ImageInputStream supported this image format
com.sksamuel.scrimage.nio.PngReader@.*? failed
com.sksamuel.scrimage.nio.OpenGifReader@.*? failed due to Image is truncated.""".toRegex()
}
}
}
| 3 | null | 128 | 866 | 705e0dbbf920fc9c20e48f780927645f44e62f01 | 938 | scrimage | Apache License 2.0 |
app/src/main/java/com/ctech/eaty/ui/login/action/LoginAction.kt | dbof10 | 116,687,959 | false | null | package com.ctech.eaty.ui.login.action
import com.ctech.eaty.base.redux.Action
sealed class LoginAction : Action() {
class LOAD_USER : LoginAction()
class REQUEST_TOKEN(val loginProvider: String, val oauthToken: String, val authTokenSecret: String = "") : LoginAction()
}
| 2 | null | 11 | 49 | 2e3445debaedfea03f9b44ab62744046fe07f1cc | 282 | hunt-android | Apache License 2.0 |
app/src/main/java/com/sethchhim/kuboo_client/data/repository/FetchRepository.kt | befora | 137,512,422 | false | null | package com.sethchhim.kuboo_client.data.repository
import androidx.lifecycle.MutableLiveData
import com.sethchhim.kuboo_client.BaseApplication
import com.sethchhim.kuboo_client.Settings
import com.sethchhim.kuboo_client.service.NotificationService
import com.sethchhim.kuboo_client.util.SystemUtil
import com.sethchhim.kuboo_remote.KubooRemote
import com.sethchhim.kuboo_remote.model.Book
import com.sethchhim.kuboo_remote.model.Login
import com.tonyodev.fetch2.Download
import com.tonyodev.fetch2.Error
import com.tonyodev.fetch2.FetchListener
import com.tonyodev.fetch2.Status
import com.tonyodev.fetch2core.DownloadBlock
import timber.log.Timber
import javax.inject.Inject
class FetchRepository : FetchListener {
init {
BaseApplication.appComponent.inject(this)
kubooRemote.addFetchListener(this)
}
@Inject lateinit var downloadsRepository: DownloadsRepository
@Inject lateinit var kubooRemote: KubooRemote
@Inject lateinit var notificationService: NotificationService
@Inject lateinit var systemUtil: SystemUtil
override fun onCancelled(download: Download) {
Timber.i("onCancelled $download")
notificationService.cancelProgress()
}
override fun onCompleted(download: Download) {
Timber.i("onCompleted $download")
notificationService.increaseCompletedCount()
kubooRemote.isQueueEmpty(MutableLiveData<Boolean>().apply {
observeForever { result ->
if (result == true) {
notificationService.cancelProgress()
notificationService.startCompleted(download)
}
}
})
}
override fun onAdded(download: Download) {}
override fun onStarted(download: Download, downloadBlocks: List<DownloadBlock>, totalBlocks: Int) {}
override fun onDeleted(download: Download) {
Timber.i("onDeleted $download")
notificationService.cancelProgress()
downloadsRepository.deleteDownload(download)
}
override fun onError(download: Download, error: Error, throwable: Throwable?) {
Timber.i("onError $download")
notificationService.cancelProgress()
}
override fun onPaused(download: Download) {
Timber.i("onPaused $download")
kubooRemote.isPauseEmpty(MutableLiveData<Boolean>().apply {
observeForever { result ->
if (result == false) notificationService.pauseProgress()
}
})
}
override fun onProgress(download: Download, etaInMilliSeconds: Long, downloadedBytesPerSecond: Long) {
Timber.i("onProgress $download")
kubooRemote.getFetchDownloads().observeForever { result ->
var downloadsCount = 0
result?.forEach { if (it.status == Status.QUEUED) downloadsCount++ }
kubooRemote.getFetchDownload(download).observeForever {
if (it?.status == Status.DOWNLOADING) notificationService.startProgress(download, downloadsCount)
}
}
}
override fun onQueued(download: Download, waitingOnNetwork: Boolean) {
Timber.i("onQueued $download")
//no notification required
}
override fun onRemoved(download: Download) {
Timber.i("onRemoved $download")
notificationService.cancelProgress()
}
override fun onResumed(download: Download) {
Timber.i("onResumed $download")
//no notification required
}
override fun onWaitingNetwork(download: Download) {}
override fun onDownloadBlockUpdated(download: Download, downloadBlock: DownloadBlock, totalBlocks: Int) {}
internal fun deleteDownload(download: Download) = kubooRemote.deleteDownload(download)
internal fun deleteDownload(book: Book) {
kubooRemote.deleteDownload(book)
downloadsRepository.deleteDownload(book)
}
internal fun deleteSeries(book: Book, keepBook: Boolean) = kubooRemote.deleteSeries(book, keepBook)
internal fun deleteFetchDownloadsNotInList(doNotDeleteList: MutableList<Book>) = kubooRemote.deleteFetchDownloadsNotInList(doNotDeleteList)
internal fun getDownload(book: Book) = kubooRemote.getFetchDownload(book)
internal fun getDownloads() = kubooRemote.getFetchDownloads()
internal fun resumeDownload(download: Download): Any = when (systemUtil.isNetworkAllowed()) {
true -> kubooRemote.resume(download)
false -> Timber.w("Network is not allowed! disableCellular[${Settings.DISABLE_CELLULAR}] isNetworkAllowed[${systemUtil.isNetworkAllowed()}]")
}
internal fun retryDownload(download: Download): Any = when (systemUtil.isNetworkAllowed()) {
true -> kubooRemote.retry(download)
false -> Timber.w("Network is not allowed! disableCellular[${Settings.DISABLE_CELLULAR}] isNetworkAllowed[${systemUtil.isNetworkAllowed()}]")
}
internal fun startDownloads(login: Login, list: List<Book>, savePath: String) = when (systemUtil.isNetworkAllowed()) {
true -> kubooRemote.startDownloads(login, list, savePath)
false -> Timber.w("Network is not allowed! disableCellular[${Settings.DISABLE_CELLULAR}] isNetworkAllowed[${systemUtil.isNetworkAllowed()}]")
}
} | 1 | null | 39 | 81 | 33e456344172eab96b136e30130c4125096f253d | 5,211 | Kuboo | Apache License 2.0 |
app/src/main/java/com/dicelab/whopuppy/viewmodel/MyInfoEditViewModel.kt | yunjaena | 349,346,681 | false | null | package com.dicelab.whopuppy.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.dicelab.whopuppy.base.viewmodel.ViewModelBase
import com.dicelab.whopuppy.constant.STATUS_OK
import com.dicelab.whopuppy.customview.ProgressStatus
import com.dicelab.whopuppy.data.UserRepository
import com.dicelab.whopuppy.data.entity.User
import com.dicelab.whopuppy.data.response.toCommonResponse
import com.dicelab.whopuppy.util.SingleLiveEvent
import com.dicelab.whopuppy.util.handleHttpException
import com.dicelab.whopuppy.util.handleProgress
import com.dicelab.whopuppy.util.withThread
import io.reactivex.rxjava3.kotlin.addTo
class MyInfoEditViewModel(
private val userRepository: UserRepository
) : ViewModelBase() {
val nickNameCheckErrorText: LiveData<String?>
get() = _nickNameCheckErrorText
val nickNameCheckStatus: LiveData<ProgressStatus>
get() = _nickNameCheckStatus
private var _nickNameCheckErrorText: MutableLiveData<String?> = MutableLiveData(null)
private var _nickNameCheckStatus = MutableLiveData(ProgressStatus.STOP)
private var checkSuccessNickName: String? = null
val nickNameChangeSuccessEvent = SingleLiveEvent<Boolean?>()
val nickNameChangeFailMessage = SingleLiveEvent<String>()
fun checkNickNameValid(nickName: String) {
_nickNameCheckStatus.value = ProgressStatus.LOADING
_nickNameCheckErrorText.value = null
userRepository.checkValidNickName(User(nickname = nickName))
.handleHttpException()
.withThread()
.subscribe({
if (it.httpStatus == STATUS_OK) {
_nickNameCheckStatus.value = ProgressStatus.SUCCESS
checkSuccessNickName = nickName
} else
_nickNameCheckStatus.value = ProgressStatus.FAIL
}) {
it.toCommonResponse()?.also { response ->
_nickNameCheckErrorText.value = response.errorMessage
}
_nickNameCheckStatus.value = ProgressStatus.FAIL
}.addTo(compositeDisposable)
}
fun changeNickName() {
if (_nickNameCheckStatus.value != ProgressStatus.SUCCESS || checkSuccessNickName.isNullOrEmpty()) {
return
}
userRepository.updateNickName(User(nickname = checkSuccessNickName))
.handleHttpException()
.withThread()
.handleProgress(this)
.subscribe({
nickNameChangeSuccessEvent.call()
}) {
it.toCommonResponse()?.also { response ->
nickNameChangeFailMessage.value = response.errorMessage
}
}.addTo(compositeDisposable)
}
}
| 0 | Kotlin | 0 | 0 | d9eb135bd0849e56d1cbab461e61f334642cfc15 | 2,772 | WhoPuppy_AOS | Apache License 2.0 |
app/src/main/java/com/example/mentalabexplore/Model.kt | SonjaSt | 435,802,880 | false | {"Kotlin": 54091} | package com.example.mentalabexplore
import android.content.Context
import android.net.Uri
import android.os.Build
import android.util.Log
import android.widget.Switch
import androidx.annotation.RequiresApi
import com.mentalab.MentalabCodec
import com.mentalab.MentalabCommands
import com.mentalab.MentalabConstants
import com.mentalab.RecordSubscriber
import java.net.URI
import java.util.*
import java.util.concurrent.TimeUnit
import kotlin.math.absoluteValue
object Model {
const val keyGyro = "Gyro"
const val keyMag = "Mag"
const val keyAcc = "Acc"
const val keyChannel = "Channel"
const val keyTemperature = "Temperature"
const val keyBattery = "Battery"
var isConnected = false
var connectedTo = ""
var refreshRate: Long = 100 // internal refresh rate, used when scheduling chart updates
var range_y = 2000.0f // range in uV
var timeWindow = 10 // in seconds
var timeGap = 2000L // distance of ticks to each other in ms, i.e. 2000 -> 2 seconds between ticks on x-Axis
var maxElements = timeWindow*1000 / refreshRate.toInt() // max elements to be drawn
var batteryVals: LinkedList<Float> = LinkedList<Float>()
var minBattery: Float = 100.0f
var temperatureVals: LinkedList<Float> = LinkedList<Float>()
var channelAverages: MutableList<Float> = mutableListOf<Float>(1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f)
var channelMaxes: MutableList<Float> = mutableListOf<Float>(1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f)
var sensorMaxes: MutableList<Float> = mutableListOf<Float>(1.0f, 1.0f, 1.0f)
var sensorAverages: MutableList<Float> = mutableListOf<Float>(1.0f, 1.0f, 1.0f)
var startTime: Long? = null
var lastTime: Long? = null
var timestamps: LinkedList<Long> = LinkedList<Long>() // timestamps in milliseconds
var markerTimestamps: LinkedList<Long> = LinkedList<Long>()
var markerColor = 0xFFAA0000
var markerColors: LinkedList<Long> = LinkedList<Long>()
// channelData holds *all* channel data (ExG and sensors)
var channelData: List<LinkedList<Float>> = listOf(LinkedList<Float>(), LinkedList<Float>(), LinkedList<Float>(), LinkedList<Float>(), LinkedList<Float>(), LinkedList<Float>(), LinkedList<Float>(), LinkedList<Float>(), LinkedList<Float>(), LinkedList<Float>(), LinkedList<Float>(), LinkedList<Float>(), LinkedList<Float>(), LinkedList<Float>(), LinkedList<Float>(), LinkedList<Float>(), LinkedList<Float>())
var dataMap: Map<String, Queue<Float>>? = null
fun changeTimeWindow(newTime: Int) {
timeWindow = newTime
val newMax = newTime*1000 / refreshRate.toInt()
if(newMax < maxElements) {
for((i, c) in channelData.withIndex()) {
if(c.size > newMax) {
// TODO: test this and make sure (c.size-newMax) is correct
c.subList(0, (c.size-newMax)).clear()
// Note: removing elements from the beginning of the channelData lists
// will influence the average for the lists with the current implementation!
}
}
}
maxElements = newMax
}
fun scanDevices(applicationContext: Context): Set<String> {
return MentalabCommands.scan()
}
fun connectDevice(name: String): Boolean {
try {
MentalabCommands.connect(name)
getDataFromDevice()
isConnected = true
connectedTo = name
}
catch(e: Exception) {
Log.e("Model", "Encountered exception in connectDevice(${name})")
e.printStackTrace()
isConnected = false
}
return isConnected
}
// The dataMap only changes when settings on the device are changed
fun getDataFromDevice() {
val stream = MentalabCommands.getRawData()
dataMap = MentalabCodec.decode(stream)
}
// TODO merge insertDataFromDevice and insertSensorDataFromDevice
// The reason they're separate right now is because the sensor channels share a common average and max
// TODO: The device sometimes sends out nonsensical values after turning it on (in my tests a bunch of values around 400000)
// This could mess with the average for a while when the app is started
fun insertDataFromDevice(s: String) {
if(!isConnected || dataMap == null) return
var index = getChannelIndexFromString(s)!!
var newDataPoint = dataMap!!.get(s)?.poll()
if(newDataPoint == null) {
if(channelData[index].isEmpty()) newDataPoint = 0.0f // Emergency dummy value to make sure our timestamps don't go out of sync
else newDataPoint = channelData[index].last
}
dataMap!!.get(s)?.clear()
if(newDataPoint!!.absoluteValue > channelMaxes[index].absoluteValue){
channelMaxes[index] = newDataPoint
}
var removed: Float? = null
if (channelData[index].size >= maxElements) {
removed = channelData[index].remove()
}
channelData[index].add(newDataPoint)
if(channelAverages[index] == 1.0f) channelAverages[index] == newDataPoint
if(removed == null) {
var numPoints = channelData[index].size
if(numPoints <= 1) channelAverages[index] = newDataPoint
else channelAverages[index] = ((numPoints-1) * channelAverages[index] + newDataPoint) / numPoints
}
else channelAverages[index] = channelAverages[index] + newDataPoint / channelData[index].size - removed / channelData[index].size
}
fun insertSensorDataFromDevice(s: String) {
if(!isConnected) return
var index = getChannelIndexFromString(s)!!
var newDataPoint = dataMap?.get(s)?.poll()
if(newDataPoint == null) {
if(channelData[index].isEmpty()) newDataPoint = 0.0f // Emergency dummy value to make sure our timestamps don't go out of sync
else newDataPoint = channelData[index].last
}
dataMap?.get(s)?.clear()
var ind = -1
when {
index < 11 -> { ind = 0 }
index < 14 -> { ind = 1 }
else -> { ind = 2 }
}
if(newDataPoint!!.absoluteValue > sensorMaxes[ind].absoluteValue){
sensorMaxes[ind] = newDataPoint
}
var removed: Float? = null
if (channelData[index].size >= maxElements) {
removed = channelData[index].remove()
}
channelData[index].add(newDataPoint)
// Note: the sensor averages are pretty useless, so I mimic the behaviour for the ExG data
// The average ends up being the average over all axes
if(sensorAverages[ind] == 1.0f) sensorAverages[ind] == newDataPoint
if(removed == null) {
var avg = 0.0f
for (a in channelData[index])
avg += a
if(!channelData[index].isEmpty()) avg /= channelData[index].size
sensorAverages[ind] = avg
}
else sensorAverages[ind] = sensorAverages[ind] + newDataPoint / channelData[index].size - removed / channelData[index].size
}
// I should use a map, I know
fun getChannelIndexFromString(s: String): Int? {
when(s) {
"Channel_1" -> return 0
"Channel_2" -> return 1
"Channel_3" -> return 2
"Channel_4" -> return 3
"Channel_5" -> return 4
"Channel_6" -> return 5
"Channel_7" -> return 6
"Channel_8" -> return 7
"Gyro_X" -> return 8
"Gyro_Y" -> return 9
"Gyro_Z" -> return 10
"Acc_X" -> return 11
"Acc_Y" -> return 12
"Acc_Z" -> return 13
"Mag_X" -> return 14
"Mag_Y" -> return 15
"Mag_Z" -> return 16
else -> {
return null
}
}
}
fun getData(s: String): Queue<Float>? {
if(!isConnected) return null
val index = getChannelIndexFromString(s)
index?.let{
return channelData[index]
}
return LinkedList<Float>()
}
fun getDeviceKeys(): MutableList<String>? {
if(!isConnected || dataMap == null) return null
var keys = mutableListOf<String>()
for((e, _) in dataMap!!) {
keys.add(e)
}
return keys
return null
}
fun getActiveChannels(): MutableList<String>? {
var keys = getDeviceKeys()
if(keys == null) return null
var activeChannels: MutableList<String> = mutableListOf()
for(i in 1..keys.size) {
if(keys[i-1].contains("Channel_")) activeChannels.add(keys[i-1])
}
return activeChannels
}
fun isGyroscopeActive(): Boolean {
val keys = getDeviceKeys()
keys?.let{
if(keys.contains("Gyro_X") && keys.contains("Gyro_Y") && keys.contains("Gyro_Z")) return true
}
return false
}
fun isAccelerometerActive(): Boolean {
val keys = getDeviceKeys()
keys?.let{
if(keys.contains("Acc_X") && keys.contains("Acc_Y") && keys.contains("Acc_Z")) return true
}
return false
}
fun isMagnetometerActive(): Boolean {
val keys = getDeviceKeys()
keys?.let{
if(keys.contains("Mag_X") && keys.contains("Mag_Y") && keys.contains("Mag_Z")) return true
}
return false
}
fun getAverage(s: String): Float {
var index = getChannelIndexFromString(s)
return channelAverages[index!!]
}
fun getTemperatureString(): String {
if(!isConnected || temperatureVals.size == 0) return ""
var temperature = temperatureVals[0]
for(t in temperatureVals) {
temperature = (temperature + t) / 2.0f
}
return "${temperature.toInt()}°C"
}
fun getBatteryString(): String {
if(!isConnected || batteryVals.size == 0) return ""
var battery = 0.0f
for(b in batteryVals) {
battery += b
}
battery /= batteryVals.size
if(battery <= minBattery) minBattery = battery
return "${minBattery.toInt()}%"
}
fun timeWithLeadingZero(t: Long): String{
return when {
t < 10 -> "0$t"
else -> "$t"
}
}
fun millisToHours(s: Long): String {
val s_seconds = s / 1000
var h = s_seconds / 3600
var m = (s_seconds % 3600) / 60
var s = s_seconds % 60
return "${timeWithLeadingZero(h)}:${timeWithLeadingZero(m)}:${timeWithLeadingZero(s)}"
}
fun scaleToVolts(scale: Float): String {
if(scale >= 2000.0f) return "${(scale/2000.0f).toInt()} mV"
else return "${(scale/2.0f).toInt()} uV"
}
fun scaleToVolts(): String {
return scaleToVolts(range_y)
}
fun insertAllData() {
if(!isConnected || dataMap == null) return
var keys = getDeviceKeys()
if (keys == null) return
for (k in keys) {
if(k.contains(keyChannel)) {
insertDataFromDevice(k)
}
if(k.contains(keyAcc) || k.contains(keyGyro) || k.contains(keyMag)) {
insertSensorDataFromDevice(k)
}
if(k.contains(keyBattery)){
var bat = dataMap!!.get("Battery ")?.poll()
dataMap!!.get("Battery ")?.clear()
if(bat != null) {
if (batteryVals.size >= 5) {
batteryVals.remove()
}
batteryVals.add(bat)
}
}
if(k.contains(keyTemperature)){
var bat = dataMap!!.get("Temperature ")?.poll()
dataMap!!.get("Temperature ")?.clear()
if(bat != null) {
if (temperatureVals.size >= 5) {
temperatureVals.remove()
}
temperatureVals.add(bat)
}
}
}
}
fun setMarker(){
if(startTime != null) markerTimestamps.add(TimeUnit.MILLISECONDS.toMillis(System.currentTimeMillis()) - startTime!!)
}
fun updateData() {
insertAllData()
if(timestamps.size >= maxElements) timestamps.remove()
var t: Long = TimeUnit.MILLISECONDS.toMillis(System.currentTimeMillis())
if (startTime == null) {
startTime = t
lastTime = 0
}
t -= startTime!!
timestamps.add(t)
if(!markerTimestamps.isEmpty() && markerTimestamps.first < timestamps[0]) markerTimestamps.removeFirst()
}
fun clearAllData() {
isConnected = false
connectedTo = ""
batteryVals.clear()
minBattery = 100.0f
temperatureVals.clear()
channelAverages = mutableListOf<Float>(1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f)
channelMaxes = mutableListOf<Float>(1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f)
sensorMaxes = mutableListOf<Float>(1.0f, 1.0f, 1.0f)
sensorAverages = mutableListOf<Float>(1.0f, 1.0f, 1.0f)
startTime = null
lastTime = null
timestamps.clear()
markerTimestamps.clear()
markerColor = 0xFFAA0000
markerColors.clear()
for(i in 0..(channelData.size-1)){
channelData[i].clear()
}
dataMap = null
}
fun formatDeviceMemory() {
MentalabCommands.formatDeviceMemory()
}
fun changeRange(newRange: String) {
var t = (newRange.subSequence(0, newRange.length-2) as String).toFloat()
if(newRange.contains("uV")) {
range_y = t*2.0f
}
if(newRange.contains("mV")){
range_y = t*2000.0f
}
}
// Needed for the y-axis scale spinner
fun rangeToSelection():Int {
return when(range_y) {
2.0f -> 0
10.0f -> 1
20.0f -> 2
200.0f -> 3
400.0f -> 4
1000.0f -> 5
2000.0f -> 6
10000.0f -> 7
20000.0f -> 8
200000.0f -> 9
else -> 6
}
}
// TODO: Make this work - currently not in use
// This function sets the new enabled channels and modules (in theory)
// The behaviour of the function isn't predictable, i.e. sending False for channel 1
// switches off some other channel (?)
fun setEnabledChannelsAndModules(activeChannelsMap: Map<String, Boolean>, activeModulesMap: Map<String, Boolean>): Boolean {
Log.d("MODEL_CHANNELS", activeChannelsMap.toString())
Log.d("MODEL_CHANNELS", activeModulesMap.toString())
try {
MentalabCommands.setEnabled(activeChannelsMap)
Log.d("MODEL_CHANNELS", "Channels set")
for ((key, value) in activeModulesMap) {
MentalabCommands.setEnabled(mapOf(key to value))
Log.d("MODEL_CHANNELS", "Module set")
}
//getDataFromDevice()
return true
}
catch(e: Exception) {
Log.d("MODEL_CHANNELS", e.toString())
return false
}
}
// I have no idea how to record data, as there is close to 0 documentation on this
@RequiresApi(Build.VERSION_CODES.Q)
fun recordData(c: Context) {
val s: Uri = Uri.parse("")
var sub : RecordSubscriber = RecordSubscriber.Builder(s, "recordedData", c).build()
MentalabCommands.record(sub)
}
fun pushDataToLSL() {
MentalabCommands.pushToLsl()
}
} | 0 | Kotlin | 0 | 0 | e6b8125637c74b77b6254c28fbe561e6e85c40b8 | 15,665 | mentalab-explore-android | MIT License |
app/src/main/java/com/github/theapache64/swipesearch/ui/screen/search/SearchScreen.kt | theapache64 | 461,540,614 | false | {"Kotlin": 42680} | package com.github.theapache64.swipesearch.ui.screen.search
import androidx.compose.foundation.layout.*
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Alignment.Companion.CenterHorizontally
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.github.theapache64.swipesearch.R
import com.github.theapache64.swipesearch.ui.composable.twyper.rememberTwyperController
import com.github.theapache64.swipesearch.ui.theme.SwipeSearchTheme
@Preview()
@Composable
fun SearchScreenPreview() {
SwipeSearchTheme {
SearchScreen()
}
}
@Composable
fun SearchScreen(
viewModel: SearchViewModel = hiltViewModel()
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(10.dp),
) {
// Some top margin
Spacer(modifier = Modifier.height(10.dp))
// App title
Text(
text = stringResource(id = R.string.app_name),
style = MaterialTheme.typography.h4
)
Spacer(modifier = Modifier.height(10.dp))
// The input field
SearchInput(
query = viewModel.uiState.query,
onQueryChanged = { newQuery ->
viewModel.onQueryChanged(newQuery)
},
)
Spacer(modifier = Modifier.height(20.dp))
viewModel.uiState.subTitle?.let { parallelMsg ->
Text(
text = parallelMsg,
modifier = Modifier.align(CenterHorizontally),
color = Color.White.copy(alpha = 0.5f)
)
}
Spacer(modifier = Modifier.height(30.dp))
val twyperController = rememberTwyperController()
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxWidth()
.height(300.dp)
) {
val loadingMessage = viewModel.uiState.loadingMsg
val errorMessage = viewModel.uiState.blockingMsg
when {
loadingMessage != null -> {
Loading(loadingMessage)
}
errorMessage != null -> {
Text(text = errorMessage)
}
else -> {
Cards(
items = viewModel.uiState.items,
onItemSwipedOut = viewModel::onItemSwipedOut,
onEndReached = {
viewModel.onPageEndReached()
},
modifier = Modifier.padding(10.dp),
twyperController = twyperController
)
}
}
}
if (viewModel.uiState.items.isNotEmpty()) {
Spacer(modifier = Modifier.height(50.dp))
Controllers(
twyperController = twyperController,
modifier = Modifier.align(CenterHorizontally)
)
}
}
}
| 1 | Kotlin | 3 | 27 | c7d03d7ab0e3652c6fcfeb4fb9126228d21d2be0 | 3,296 | swipe-search | Apache License 2.0 |
Dagger2/app/src/main/java/com/demo/zee/chapter02/e/User.kt | totemtec | 368,780,586 | false | null | package com.demo.zee.chapter02.e
import javax.inject.Inject
class User constructor() {
val name = "User from @Inject constructor()"
} | 0 | Kotlin | 0 | 0 | 15c446d43073bc32876b0fb97d38eadd26f96dbc | 139 | hilt | Apache License 2.0 |
app/src/main/java/net/squanchy/search/algolia/AlgoliaIndex.kt | squanchy-dev | 72,942,055 | false | null | package net.squanchy.search.algolia
import com.algolia.search.saas.AlgoliaException
import com.algolia.search.saas.Index
import com.algolia.search.saas.Query
import net.squanchy.search.algolia.model.AlgoliaSearchResponse
import java.io.IOException
interface SearchIndex {
@Throws(IOException::class)
fun search(key: String): AlgoliaSearchResponse?
}
class AlgoliaIndex(private val index: Index, private val parser: ResponseParser<AlgoliaSearchResponse>) : SearchIndex {
override fun search(key: String): AlgoliaSearchResponse? {
return try {
parser.parse(index.searchSync(Query(key)).toString())
} catch (e: AlgoliaException) {
throw IOException(e)
}
}
}
| 0 | Kotlin | 45 | 298 | aa0909c327500f39fb65488baa62f7e4624837ea | 724 | squanchy-android | Apache License 2.0 |
mapskit/src/main/java/com/trendyol/mapskit/maplibrary/GoogleCameraUpdateProvider.kt | Trendyol | 380,598,800 | false | null | package com.trendyol.mapskit.maplibrary
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.model.LatLngBounds
import com.google.android.gms.maps.CameraUpdate as GoogleCameraUpdate
class GoogleCameraUpdateProvider {
fun provide(cameraUpdate: CameraUpdate): GoogleCameraUpdate {
return when (cameraUpdate) {
is CameraUpdate.NewLatLng -> CameraUpdateFactory.newLatLng(cameraUpdate.latLng.toGoogleLatLng())
is CameraUpdate.NewLatLngZoom -> CameraUpdateFactory.newLatLngZoom(
cameraUpdate.latLng.toGoogleLatLng(), cameraUpdate.zoomLevel
)
is CameraUpdate.NewLatLngBounds -> {
val latLngBounds = LatLngBounds.builder()
.apply { cameraUpdate.latLng.forEach { include(it.toGoogleLatLng()) } }
.build()
CameraUpdateFactory.newLatLngBounds(latLngBounds, cameraUpdate.padding)
}
}
}
}
| 0 | Kotlin | 0 | 23 | 14373a408d5251275db043498658643c00a7fbb4 | 988 | MapsKit | Apache License 2.0 |
shared/src/androidMain/kotlin/com/kevinschildhorn/fotopresenter/ui/compose/DirectoryPreviews.kt | KevinSchildhorn | 522,216,678 | false | {"Kotlin": 205070, "Swift": 580} | package com.kevinschildhorn.fotopresenter.ui.compose
import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import com.kevinschildhorn.fotopresenter.data.DirectoryContents
import com.kevinschildhorn.fotopresenter.data.FolderDirectory
import com.kevinschildhorn.fotopresenter.data.State
import com.kevinschildhorn.fotopresenter.data.network.MockNetworkDirectoryDetails
import com.kevinschildhorn.fotopresenter.ui.compose.directory.DirectoryGridCell
import com.kevinschildhorn.fotopresenter.ui.compose.directory.DirectoryGrid
import com.kevinschildhorn.fotopresenter.ui.compose.directory.FolderDirectoryGridCell
import com.kevinschildhorn.fotopresenter.ui.state.DirectoryGridState
import com.kevinschildhorn.fotopresenter.ui.state.FolderDirectoryGridCellState
import com.kevinschildhorn.fotopresenter.ui.state.ImageDirectoryGridCellState
@Preview
@Composable
fun BaseDirectoryPreview() {
Column {
DirectoryGridCell() {}
}
}
@Preview
@Composable
fun FolderDirectoryEmptyPreview() {
Column {
FolderDirectoryGridCell(FolderDirectoryGridCellState("Hello",0))
}
}
@Preview
@Composable
fun DirectoryGridPreview() {
DirectoryGrid(
directoryContent = DirectoryGridState(
folderStates = listOf(
FolderDirectoryGridCellState("Hello",0),
),
imageStates = mutableListOf(
ImageDirectoryGridCellState(State.IDLE,"Hello", 1)
)
),
onFolderPressed = {},
onImageDirectoryPressed = {},
)
}
| 0 | Kotlin | 0 | 0 | 2435fe62bb32de8c5081baf772806e76c9e572b5 | 1,613 | FoToPresenter | Apache License 2.0 |
scheduled-tasks/src/main/java/io/github/reactivecircus/streamlined/work/worker/StorySyncWorker.kt | ReactiveCircus | 233,422,078 | false | null | package io.github.reactivecircus.streamlined.work.worker
import android.content.Context
import androidx.hilt.work.HiltWorker
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import dagger.assisted.Assisted
import dagger.assisted.AssistedInject
import io.github.reactivecircus.streamlined.domain.interactor.SyncStories
import reactivecircus.blueprint.interactor.EmptyParams
@HiltWorker
class StorySyncWorker @AssistedInject constructor(
@Assisted appContext: Context,
@Assisted params: WorkerParameters,
private val syncStories: SyncStories
) : CoroutineWorker(appContext, params) {
override suspend fun doWork(): Result {
syncStories.execute(EmptyParams)
return Result.success()
}
companion object {
const val TAG = "story-sync"
}
}
| 2 | Kotlin | 5 | 70 | 64b3bddcfe66bb376770b506107e307669de8005 | 815 | streamlined | Apache License 2.0 |
app/src/androidTest/java/com/phicdy/mycuration/domain/rss/RssV1.kt | phicdy | 24,188,186 | false | {"Kotlin": 688608, "HTML": 1307, "Shell": 1127} | package com.phicdy.mycuration.domain.rss
class RssV1 {
fun text(): String {
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<rdf:RDF\n" +
" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" +
" xmlns=\"http://purl.org/rss/1.0/\"\n" +
" xmlns:content=\"http://purl.org/rss/1.0/modules/content/\"\n" +
" xmlns:taxo=\"http://purl.org/rss/1.0/modules/taxonomy/\"\n" +
" xmlns:opensearch=\"http://a9.com/-/spec/opensearchrss/1.0/\"\n" +
" xmlns:dc=\"http://purl.org/dc/elements/1.1/\"\n" +
" xmlns:hatena=\"http://www.hatena.ne.jp/info/xmlns#\"\n" +
" xmlns:media=\"http://search.yahoo.com/mrss\"\n" +
">\n" +
" <channel rdf:about=\"http://b.hatena.ne.jp/hotentry/it\">\n" +
" <title>はてなブックマーク - 人気エントリー - テクノロジー</title>\n" +
" <link>http://b.hatena.ne.jp/hotentry/it</link>\n" +
" <description>最近の人気エントリー - テクノロジー</description>\n" +
"\n" +
" <items>\n" +
" <rdf:Seq>\n" +
" <rdf:li rdf:resource=\"https://kuenishi.hatenadiary.jp/entry/2018/04/13/022908\" />\n" +
" <rdf:li rdf:resource=\"https://internet.watch.impress.co.jp/docs/yajiuma/1116878.html\" />\n" +
" <rdf:li rdf:resource=\"https://kantan-shikaku.com/ks/excel-test-for-work/\" />\n" +
" <rdf:li rdf:resource=\"http://www.kodansha.co.jp/upload/pr.kodansha.co.jp/files/180413_seimei_kaizokuban.pdf\" />\n" +
" <rdf:li rdf:resource=\"https://anond.hatelabo.jp/20180413102948\" />\n" +
" <rdf:li rdf:resource=\"https://employment.en-japan.com/engineerhub/entry/2018/04/13/110000\" />\n" +
" <rdf:li rdf:resource=\"https://employment.en-japan.com/engineerhub/entry/2018/04/10/110000\" />\n" +
" <rdf:li rdf:resource=\"https://qiita.com/issei_y/items/ab641746be2704db98be\" />\n" +
" <rdf:li rdf:resource=\"https://withnews.jp/article/f0180413000qq000000000000000W06w10101qq000017106A\" />\n" +
" <rdf:li rdf:resource=\"https://qiita.com/aoshirobo/items/32deb45cb8c8b87d65a4\" />\n" +
" <rdf:li rdf:resource=\"https://axia.co.jp/2018-04-13\" />\n" +
" <rdf:li rdf:resource=\"http://kyon-mm.hatenablog.com/entry/2018/04/13/074023\" />\n" +
" <rdf:li rdf:resource=\"https://togetter.com/li/1217505\" />\n" +
" <rdf:li rdf:resource=\"https://virtualcast.jp/\" />\n" +
" <rdf:li rdf:resource=\"https://liginc.co.jp/388554\" />\n" +
" <rdf:li rdf:resource=\"https://blog.tinect.jp/?p=50813\" />\n" +
" <rdf:li rdf:resource=\"https://pc.watch.impress.co.jp/docs/news/1116988.html\" />\n" +
" <rdf:li rdf:resource=\"https://www.jaipa.or.jp/information/docs/180412-1.pdf\" />\n" +
" <rdf:li rdf:resource=\"https://natalie.mu/comic/news/277927\" />\n" +
" <rdf:li rdf:resource=\"https://inside.dmm.com/entry/2018/04/13/hello-kubernetes\" />\n" +
" <rdf:li rdf:resource=\"http://uxmilk.jp/62899\" />\n" +
" <rdf:li rdf:resource=\"https://postd.cc/vim3/\" />\n" +
" <rdf:li rdf:resource=\"https://linq.career-tasu.jp/magazine/knowhow-excel-test/\" />\n" +
" <rdf:li rdf:resource=\"https://vimawesome.com/\" />\n" +
" <rdf:li rdf:resource=\"https://anond.hatelabo.jp/20180413022546\" />\n" +
" <rdf:li rdf:resource=\"http://nlab.itmedia.co.jp/nl/articles/1804/13/news091.html\" />\n" +
" <rdf:li rdf:resource=\"http://vgdrome.blogspot.com/2018/04/chinesePUBGripoffwar.html\" />\n" +
" <rdf:li rdf:resource=\"https://codezine.jp/article/detail/10734\" />\n" +
" <rdf:li rdf:resource=\"https://webtan.impress.co.jp/e/2018/04/13/28947\" />\n" +
" <rdf:li rdf:resource=\"https://gigazine.net/news/20180413-facial-recognition-catch-fugitive/\" />\n" +
" </rdf:Seq>\n" +
" </items>\n" +
" </channel>\n" +
" <item rdf:about=\"https://kuenishi.hatenadiary.jp/entry/2018/04/13/022908\">\n" +
" <title>トップレベルのコンピュータエンジニアなら普段からチェックして当然の技術系メディアN選 - kuenishi's blog</title>\n" +
" <link>https://kuenishi.hatenadiary.jp/entry/2018/04/13/022908</link>\n" +
" <description>2018 - 04 - 13 トップレベルのコンピュータエンジニアなら普段からチェックして当然の技術系メディアN選 〜〜が知っておくべきサイト20選とか、エンジニアなら今すぐフォローすべき有名人とか、いつも釣られてみにいくと全く興味なかったり拍子抜けしたりするわけだが、こういうのが並んでいたらあまりの格の違いに絶望してしまうだろうというものを適当に並べてみた。私が見ているわけではなくて、こうありた...</description>\n" +
" <content:encoded><blockquote cite="https://kuenishi.hatenadiary.jp/entry/2018/04/13/022908" title="トップレベルのコンピュータエンジニアなら普段からチェックして当然の技術系メディアN選 - kuenishi's blog"><cite><img src="http://cdn-ak.favicon.st-hatena.com/?url=https%3A%2F%2Fkuenishi.hatenadiary.jp%2Fentry%2F2018%2F04%2F13%2F022908" alt="" /> <a href="https://kuenishi.hatenadiary.jp/entry/2018/04/13/022908">トップレベルのコンピュータエンジニアなら普段からチェックして当然の技術系メディアN選 - kuenishi's blog</a></cite><p><a href="https://kuenishi.hatenadiary.jp/entry/2018/04/13/022908"><img src="https://cdn-ak-scissors.b.st-hatena.com/image/square/1db2a014bdea7ae25967aced483f3e5eca394182/height=90;version=1;width=120/https%3A%2F%2Fcdn.blog.st-hatena.com%2Fimages%2Ftheme%2Fog-image-1500.png" alt="トップレベルのコンピュータエンジニアなら普段からチェックして当然の技術系メディアN選 - kuenishi's blog" title="トップレベルのコンピュータエンジニアなら普段からチェックして当然の技術系メディアN選 - kuenishi's blog" class="entry-image" /></a></p><p>2018 - 04 - 13 トップレベルのコンピュータエンジニアなら普段からチェックして当然の技術系メディアN選 〜〜が知っておくべきサイト20選とか、エンジニアなら今すぐフォローすべき有名人とか、いつも釣られてみにいくと全く興味なかったり拍子抜けしたりするわけだが、こういうのが並んでいたらあまりの格の違いに絶望してしまうだろうというものを適当に並べてみた。私が見ているわけではなくて、こうありた...</p><p><a href="http://b.hatena.ne.jp/entry/https://kuenishi.hatenadiary.jp/entry/2018/04/13/022908"><img src="http://b.hatena.ne.jp/entry/image/https://kuenishi.hatenadiary.jp/entry/2018/04/13/022908" alt="はてなブックマーク - トップレベルのコンピュータエンジニアなら普段からチェックして当然の技術系メディアN選 - kuenishi's blog" title="はてなブックマーク - トップレベルのコンピュータエンジニアなら普段からチェックして当然の技術系メディアN選 - kuenishi's blog" border="0" style="border: none" /></a> <a href="http://b.hatena.ne.jp/append?https://kuenishi.hatenadiary.jp/entry/2018/04/13/022908"><img src="http://b.hatena.ne.jp/images/append.gif" border="0" alt="はてなブックマークに追加" title="はてなブックマークに追加" /></a></p></blockquote></content:encoded>\n" +
" <dc:date>2018-04-13T02:33:56+09:00</dc:date>\n" +
" <dc:subject>テクノロジー</dc:subject>\n" +
" <hatena:bookmarkcount>1902</hatena:bookmarkcount>\n" +
" </item>\n" +
" <item rdf:about=\"https://internet.watch.impress.co.jp/docs/yajiuma/1116878.html\">\n" +
" <title>「Excelが使える」のレベルを的確に見抜ける、入社試験に使えるサンプル問題が公開中【やじうまWatch】 - INTERNET Watch</title>\n" +
" <link>https://internet.watch.impress.co.jp/docs/yajiuma/1116878.html</link>\n" +
" <description>やじうまWatch 「Excelが使える」のレベルを的確に見抜ける、入社試験に使えるサンプル問題が公開中 tks24 2018年4月13日 06:00 入社試験に使える、Excelがどの程度使えるかをチェックするためのサンプル問題が公開され、有用だと話題になっている。 「Excelが使える」と自己アピールする人の中には、マクロまでしっかり使いこなす人もいれば、セルに数字を入力するので精一杯の人...</description>\n" +
" <content:encoded><blockquote cite="https://internet.watch.impress.co.jp/docs/yajiuma/1116878.html" title="「Excelが使える」のレベルを的確に見抜ける、入社試験に使えるサンプル問題が公開中【やじうまWatch】 - INTERNET Watch"><cite><img src="http://cdn-ak.favicon.st-hatena.com/?url=https%3A%2F%2Finternet.watch.impress.co.jp%2Fdocs%2Fyajiuma%2F1116878.html" alt="" /> <a href="https://internet.watch.impress.co.jp/docs/yajiuma/1116878.html">「Excelが使える」のレベルを的確に見抜ける、入社試験に使えるサンプル問題が公開中【やじうまWatch】 - INTERNET Watch</a></cite><p><a href="https://internet.watch.impress.co.jp/docs/yajiuma/1116878.html"><img src="https://cdn-ak-scissors.b.st-hatena.com/image/square/0e82d1dcac71fcd16db3e39d9fd4e11018bfc6ea/height=90;version=1;width=120/https%3A%2F%2Finternet.watch.impress.co.jp%2Fimg%2Fiw%2Flist%2F1116%2F878%2Fyajiuma-watch_1.png" alt="「Excelが使える」のレベルを的確に見抜ける、入社試験に使えるサンプル問題が公開中【やじうまWatch】 - INTERNET Watch" title="「Excelが使える」のレベルを的確に見抜ける、入社試験に使えるサンプル問題が公開中【やじうまWatch】 - INTERNET Watch" class="entry-image" /></a></p><p>やじうまWatch 「Excelが使える」のレベルを的確に見抜ける、入社試験に使えるサンプル問題が公開中 tks24 2018年4月13日 06:00 入社試験に使える、Excelがどの程度使えるかをチェックするためのサンプル問題が公開され、有用だと話題になっている。 「Excelが使える」と自己アピールする人の中には、マクロまでしっかり使いこなす人もいれば、セルに数字を入力するので精一杯の人...</p><p><a href="http://b.hatena.ne.jp/entry/https://internet.watch.impress.co.jp/docs/yajiuma/1116878.html"><img src="http://b.hatena.ne.jp/entry/image/https://internet.watch.impress.co.jp/docs/yajiuma/1116878.html" alt="はてなブックマーク - 「Excelが使える」のレベルを的確に見抜ける、入社試験に使えるサンプル問題が公開中【やじうまWatch】 - INTERNET Watch" title="はてなブックマーク - 「Excelが使える」のレベルを的確に見抜ける、入社試験に使えるサンプル問題が公開中【やじうまWatch】 - INTERNET Watch" border="0" style="border: none" /></a> <a href="http://b.hatena.ne.jp/append?https://internet.watch.impress.co.jp/docs/yajiuma/1116878.html"><img src="http://b.hatena.ne.jp/images/append.gif" border="0" alt="はてなブックマークに追加" title="はてなブックマークに追加" /></a></p></blockquote></content:encoded>\n" +
" <dc:date>2018-04-13T06:03:55+09:00</dc:date>\n" +
" <dc:subject>テクノロジー</dc:subject>\n" +
" <hatena:bookmarkcount>813</hatena:bookmarkcount>\n" +
" </item>\n" +
"</rdf:RDF>\n"
}
} | 38 | Kotlin | 9 | 30 | c270cb9f819dfcb6a2ac4b9ee5ddc459c698497f | 10,473 | MyCuration | The Unlicense |
lib/android/src/main/java/com/kiki/react/amap/search/cloud/CloudSearchModule.kt | MonchiLin | 175,767,938 | false | {"YAML": 1, "JSON with Comments": 1, "JSON": 1, "JavaScript": 3, "Text": 1, "Ignore List": 1, "Git Attributes": 1, "Markdown": 1, "Gradle": 4, "Shell": 1, "Batchfile": 1, "INI": 1, "Java Properties": 2, "Starlark": 1, "XML": 5, "Java": 5, "Kotlin": 5, "TSX": 1, "Objective-C": 2, "Ruby": 1} | package com.kiki.react.amap.search.cloud
import android.util.Log
import com.amap.api.services.core.LatLonPoint
import com.facebook.react.bridge.*
import com.kiki.react.amap.search.utils.AMapParse
import com.amap.api.services.cloud.CloudItemDetail as AMapCloudItemDetail
import com.amap.api.services.cloud.CloudResult as AMapCloudResult
import com.amap.api.services.cloud.CloudSearch as AMapCloudSearch
val TAG = "kiki"
class CloudSearchModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
internal var reactContext: ReactContext? = null
init {
this.reactContext = reactContext
}
override fun getName(): String {
return "AMapCloudSearch"
}
@ReactMethod
fun AMapCloudSearch(options: ReadableMap, promise: Promise) {
if (options.getString("tableId") == null || "".equals(options.getString("tableId"))) {
promise.reject("参数错误", "请传入正确的 tableId")
return
}
if (!options.hasKey("searchBoundParams")) {
promise.reject("参数错误", "请传入 searchBoundParams")
return
}
if (!options.hasKey("searchBoundType")) {
promise.reject("参数错误", "请传入 searchBoundType")
return
}
val query = if (options.hasKey("query")) {
options.getString("query")
} else {
""
}
val radius = if (options.hasKey("radius")) {
options.getInt("radius")
} else {
1000
}
val pagination = if (options.hasKey("pagination")) {
val map = options.getMap("pagination")
if (map!!.hasKey("pageNum") && map.hasKey("pageSize")) {
map
} else {
val map = Arguments.createMap()
map.putInt("pageNum", 1)
map.putInt("pageSize", 20)
map
}
} else {
val map = Arguments.createMap()
map.putInt("pageNum", 1)
map.putInt("pageSize", 20)
map
}
val tableId = options.getString("tableId")
val searchBoundType = options.getString("searchBoundType")
val bound: AMapCloudSearch.SearchBound = if ("Bound".equals(searchBoundType)) {
val bound = options.getMap("searchBoundParams")
val latitude = bound!!.getDouble("latitude")
val longitude = bound.getDouble("longitude")
val latLonPoint = LatLonPoint(latitude, longitude)
AMapCloudSearch.SearchBound(latLonPoint, radius)
} else if ("Rectangle".equals(searchBoundType)) {
val bound = options.getArray("searchBoundParams")
val point1 = bound!!.getMap(1)
val point2 = bound.getMap(2)
val latlon1 = LatLonPoint(point1!!.getDouble("latitude"), point1.getDouble("longitude"))
val latlon2 = LatLonPoint(point2!!.getDouble("latitude"), point2.getDouble("longitude"))
AMapCloudSearch.SearchBound(latlon1, latlon2)
} else if ("Polygon".equals(searchBoundType)) {
val bound = options.getArray("searchBoundParams")
val latlons = (0..bound!!.size() - 1).map {
val point = bound.getMap(it)
val latitude = point!!.getDouble("latitude")
val longitude = point.getDouble("longitude")
LatLonPoint(latitude, longitude)
}
AMapCloudSearch.SearchBound(latlons)
} else if ("Local".equals(searchBoundType)) {
val city = options.getString("searchBoundParams")
AMapCloudSearch.SearchBound(city)
} else {
promise.reject("参数错误", "请传入正确的 searchBoundType, " +
"searchBoundType 只能为: Bound Polygon Rectangle Local 之一")
return
}
val mCloudSearch = AMapCloudSearch(reactContext)
val mQuery = AMapCloudSearch.Query(tableId, query, bound);
mQuery.pageNum = pagination.getInt("pageNum")
mQuery.pageSize = pagination.getInt("pageSize")
mCloudSearch.setOnCloudSearchListener(object : AMapCloudSearch.OnCloudSearchListener {
override fun onCloudItemDetailSearched(cloudItemDetail: AMapCloudItemDetail?, count: Int) {
Log.d(TAG, "onCloudItemDetailSearched ->> " + cloudItemDetail)
}
override fun onCloudSearched(cloudResult: AMapCloudResult, count: Int) {
Log.d(TAG, "onCloudSearched ->> " + cloudResult)
promise.resolve(toWriteArray(cloudResult))
}
})
mCloudSearch.searchCloudAsyn(mQuery);// 异步搜索
}
private fun toWriteArray(cloudResult: AMapCloudResult): WritableMap? {
val map = Arguments.createMap()
map.putMap("query", AMapParse.parseQuery(cloudResult.query))
map.putMap("bound", AMapParse.parserSearchBound(cloudResult.bound))
map.putInt("pageCount", cloudResult.pageCount)
map.putInt("totalCount", cloudResult.totalCount)
map.putArray("clouds", AMapParse.parserCloudItem(cloudResult.clouds))
return map
}
}
| 18 | Kotlin | 0 | 0 | a9d6bc8175e310d9dec117d4b1e26014fbf2b868 | 5,178 | react-native-amap-search | MIT License |
HelloTransform/sample/src/main/java/com/pengxr/hellotransform/HelloActivity.kt | pengxurui | 364,502,372 | false | null | package com.pengxr.hellotransform
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
/**
* Created by pengxr on 15/5/2022
*/
class HelloActivity : AppCompatActivity() {
@Hello
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_hello)
}
} | 1 | Kotlin | 14 | 53 | 08c1b999760dcedd29408f50f0a0e74f4cbc0391 | 362 | DemoHall | Apache License 2.0 |
src/test/kotlin/nl/dirkgroot/structurizr/dsl/lexer/PropertiesTest.kt | dirkgroot | 561,786,663 | false | {"Kotlin": 75934, "Lex": 2535, "ASL": 463} | package nl.dirkgroot.structurizr.dsl.lexer
import com.intellij.psi.TokenType.WHITE_SPACE
import io.kotest.matchers.collections.shouldContainExactly
import nl.dirkgroot.structurizr.dsl.psi.SDTypes.*
import nl.dirkgroot.structurizr.dsl.support.tokenize
import org.junit.Test
class PropertiesTest {
@Test
fun `properties block`() {
"""
properties {
name value
"quoted name" "quoted value"
properties description
}
""".trimIndent().tokenize() shouldContainExactly listOf(
UNQUOTED_TEXT to "properties",
WHITE_SPACE to " ",
BRACE1 to "{",
CRLF to "\n",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "name",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "value",
CRLF to "\n",
WHITE_SPACE to " ",
QUOTED_TEXT to "\"quoted name\"",
WHITE_SPACE to " ",
QUOTED_TEXT to "\"quoted value\"",
CRLF to "\n",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "properties",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "description",
CRLF to "\n",
BRACE2 to "}",
)
}
@Test
fun `properties block with line comments`() {
"""
properties {
// line comment
name value // line comment
}
""".trimIndent().tokenize() shouldContainExactly listOf(
UNQUOTED_TEXT to "properties",
WHITE_SPACE to " ",
BRACE1 to "{",
CRLF to "\n",
WHITE_SPACE to " ",
LINE_COMMENT to "// line comment",
CRLF to "\n",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "name",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "value",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "//",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "line",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "comment",
CRLF to "\n",
BRACE2 to "}",
)
}
@Test
fun `properties block with block comments`() {
"""
properties {
/* block comment */
name value /* block comment */
name /* block comment */ value
/* block
comment */
}
""".trimIndent().tokenize() shouldContainExactly listOf(
UNQUOTED_TEXT to "properties",
WHITE_SPACE to " ",
BRACE1 to "{",
CRLF to "\n",
WHITE_SPACE to " ",
BLOCK_COMMENT to "/* block comment */",
CRLF to "\n",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "name",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "value",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "/*",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "block",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "comment",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "*/",
CRLF to "\n",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "name",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "/*",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "block",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "comment",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "*/",
WHITE_SPACE to " ",
UNQUOTED_TEXT to "value",
CRLF to "\n",
WHITE_SPACE to " ",
BLOCK_COMMENT to "/* block\n comment */",
CRLF to "\n",
BRACE2 to "}",
)
}
}
| 11 | Kotlin | 3 | 54 | 9bcbcfab6c1e7ef8258dc7c21f049e555b119237 | 3,836 | structurizr-dsl-intellij-plugin | MIT License |
DSLs/kubernetes/dsl/src/main/kotlin-gen/dev/forkhandles/k8s/apiextensions/v1beta1/openAPIV3Schema.kt | fork-handles | 649,794,132 | false | {"Kotlin": 575626, "Shell": 2264, "Just": 1042, "Nix": 740} | // GENERATED
package dev.forkhandles.k8s.apiextensions.v1beta1
import io.fabric8.kubernetes.api.model.apiextensions.v1beta1.CustomResourceValidation as v1beta1_CustomResourceValidation
import io.fabric8.kubernetes.api.model.apiextensions.v1beta1.JSONSchemaProps as v1beta1_JSONSchemaProps
fun v1beta1_CustomResourceValidation.openAPIV3Schema(block: v1beta1_JSONSchemaProps.() -> Unit = {}) {
if (openAPIV3Schema == null) {
openAPIV3Schema = v1beta1_JSONSchemaProps()
}
openAPIV3Schema.block()
}
| 0 | Kotlin | 0 | 9 | 68221cee577ea16dc498745606d07b0fb62f5cb7 | 518 | k8s-dsl | MIT License |
app/src/main/java/com/example/filemanager/screens/files/all/AllFilesState.kt | KhuzinT | 639,105,158 | false | null | package com.example.filemanager.screens.files.all
import android.os.Environment.getExternalStorageDirectory
import com.example.filemanager.screens.utils.SortedBy
import java.io.File
data class AllFilesState(
val directory: File = getExternalStorageDirectory(),
val files: List<File> = emptyList(),
val sortedBy: SortedBy = SortedBy.NameAZ
) | 0 | Kotlin | 0 | 0 | 266e48740766817f41b869e84ac1db57ae14a4e8 | 354 | FileManager | MIT License |
app/src/main/java/com/example/filemanager/screens/files/all/AllFilesState.kt | KhuzinT | 639,105,158 | false | null | package com.example.filemanager.screens.files.all
import android.os.Environment.getExternalStorageDirectory
import com.example.filemanager.screens.utils.SortedBy
import java.io.File
data class AllFilesState(
val directory: File = getExternalStorageDirectory(),
val files: List<File> = emptyList(),
val sortedBy: SortedBy = SortedBy.NameAZ
) | 0 | Kotlin | 0 | 0 | 266e48740766817f41b869e84ac1db57ae14a4e8 | 354 | FileManager | MIT License |
app/src/main/kotlin/com/ashish/movieguide/ui/people/list/PeopleComponent.kt | AshishKayastha | 82,365,723 | false | null | package com.ashish.movieguide.ui.people.list
import com.ashish.movieguide.di.modules.FragmentModule
import com.ashish.movieguide.di.multibindings.AbstractComponent
import com.ashish.movieguide.di.multibindings.fragment.FragmentComponentBuilder
import dagger.Subcomponent
@Subcomponent(modules = arrayOf(FragmentModule::class))
interface PeopleComponent : AbstractComponent<PeopleFragment> {
@Subcomponent.Builder
interface Builder : FragmentComponentBuilder<PeopleFragment, PeopleComponent> {
fun withModule(module: FragmentModule): Builder
}
} | 5 | Kotlin | 5 | 16 | f455e468b917491fd1e35b07f70e9e9e2d00649d | 567 | Movie-Guide | Apache License 2.0 |
v2-model-enumeration/src/commonMain/kotlin/com/bselzer/gw2/v2/model/enumeration/PvpLadderType.kt | Woody230 | 388,820,096 | false | {"Kotlin": 750899} | package com.bselzer.gw2.v2.model.enumeration
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
enum class PvpLadderType {
@SerialName("ranked")
RANKED,
@SerialName("unranked")
UNRANKED
} | 2 | Kotlin | 0 | 2 | 7bd43646f94d1e8de9c20dffcc2753707f6e455b | 251 | GW2Wrapper | Apache License 2.0 |
android/src/main/kotlin/com/usercentrics/sdk/flutter/serializer/AdditionalConsentModeDataSerializer.kt | Usercentrics | 416,296,210 | false | {"Dart": 343894, "Kotlin": 204588, "Swift": 105016, "Ruby": 2063, "Shell": 1316, "HTML": 1050, "Objective-C": 733} | package com.usercentrics.sdk.flutter.serializer
import com.usercentrics.sdk.AdTechProvider
import com.usercentrics.sdk.AdditionalConsentModeData
internal fun AdditionalConsentModeData.serialize(): Any {
return mapOf(
"acString" to acString,
"adTechProviders" to adTechProviders.map { it.serialize() }
)
}
private fun AdTechProvider.serialize() : Any {
return mapOf(
"id" to id,
"name" to name,
"privacyPolicyUrl" to privacyPolicyUrl,
"consent" to consent
)
}
| 0 | Dart | 8 | 4 | a06a5ec81bb21a125718942efd2880b5086d07ae | 526 | flutter-sdk | Apache License 2.0 |
app/src/androidTest/java/com/iliaberlana/wefoxpokedex/framework/PokemonRemoteDataSourceTest.kt | siayerestaba | 206,335,343 | false | null | package com.iliaberlana.wefoxpokedex.framework
import androidx.test.core.app.ApplicationProvider
import assertk.assertThat
import assertk.assertions.isEqualToWithGivenProperties
import com.iliaberlana.wefoxpokedex.TestApplication
import com.iliaberlana.wefoxpokedex.domain.exception.DomainError
import com.iliaberlana.wefoxpokedex.framework.remote.NetworkFactory
import com.iliaberlana.wefoxpokedex.framework.remote.PokemonRemoteDataSource
import com.iliaberlana.wefoxpokedex.framework.remote.model.PokemonRemote
import com.iliaberlana.wefoxpokedex.framework.remote.model.Sprites
import com.iliaberlana.wefoxpokedex.framework.remote.model.Type
import com.iliaberlana.wefoxpokedex.framework.remote.model.Types
import io.kotlintest.matchers.types.shouldNotBeNull
import io.kotlintest.shouldBe
import kotlinx.coroutines.runBlocking
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.After
import org.junit.Before
import org.junit.Test
class PokemonRemoteDataSourceTest {
private val mockWebServer = MockWebServer()
private lateinit var pokemonRemoteDataSource: PokemonRemoteDataSource
@Before
fun setUp() {
mockWebServer.start(8080)
val httpUrl = mockWebServer.url("/")
val testApp = ApplicationProvider.getApplicationContext() as TestApplication
testApp.setApiUrl(httpUrl.toString())
pokemonRemoteDataSource = PokemonRemoteDataSource(NetworkFactory(), httpUrl.toString())
}
@After
fun tearDown() {
mockWebServer.shutdown()
}
@Test
fun should_return_throw_when_response_is_not_200ok() = runBlocking {
mockWebServer.enqueue(MockResponse().setResponseCode(404))
var domainError: DomainError = DomainError.UnknownException
try {
pokemonRemoteDataSource.getPokemon(944)
} catch (error: DomainError) {
domainError = error
}
domainError.shouldBe(DomainError.NoPokemonFound)
}
@Test
fun should_result_a_pokemon() = runBlocking {
val response = MockResponse()
.addHeader("Content-Type", "application/json; charset=utf-8")
.addHeader("Cache-Control", "no-cache")
.setBody(
"{\n" +
"\t\"base_experience\": 64,\n" +
"\t\"height\": 7,\n" +
"\t\"id\": 1,\n" +
"\t\"name\": \"bulbasaur\",\n" +
"\t\"order\": 1,\n" +
"\t\"sprites\": {\n" +
"\t\t\"front_default\": \"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png\"\n" +
"\t},\n" +
"\t\"types\": [{\n" +
"\t\t\t\"slot\": 2,\n" +
"\t\t\t\"type\": {\n" +
"\t\t\t\t\"name\": \"poison\",\n" +
"\t\t\t\t\"url\": \"https://pokeapi.co/api/v2/type/4/\"\n" +
"\t\t\t}\n" +
"\t\t},\n" +
"\t\t{\n" +
"\t\t\t\"slot\": 1,\n" +
"\t\t\t\"type\": {\n" +
"\t\t\t\t\"name\": \"grass\",\n" +
"\t\t\t\t\"url\": \"https://pokeapi.co/api/v2/type/12/\"\n" +
"\t\t\t}\n" +
"\t\t}\n" +
"\t],\n" +
"\t\"weight\": 69\n" +
"}"
)
mockWebServer.enqueue(response)
val actual = pokemonRemoteDataSource.getPokemon(1)
actual.shouldNotBeNull()
val expected = PokemonRemote(
1,
1,
"bulbasaur",
69,
7,
64,
Sprites("https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png"),
listOf(Types(Type("poison")), Types(Type("grass")))
)
assertThat(expected).isEqualToWithGivenProperties(
actual,
PokemonRemote::id,
PokemonRemote::order,
PokemonRemote::name,
PokemonRemote::weight,
PokemonRemote::height,
PokemonRemote::sprites,
PokemonRemote::base_experience,
PokemonRemote::types
)
}
} | 0 | Kotlin | 0 | 0 | 51a085e2deb46eb06f933396b3b91f5347866915 | 4,402 | WefoxPokeDex | MIT License |
app/src/androidTest/java/com/iliaberlana/wefoxpokedex/framework/PokemonRemoteDataSourceTest.kt | siayerestaba | 206,335,343 | false | null | package com.iliaberlana.wefoxpokedex.framework
import androidx.test.core.app.ApplicationProvider
import assertk.assertThat
import assertk.assertions.isEqualToWithGivenProperties
import com.iliaberlana.wefoxpokedex.TestApplication
import com.iliaberlana.wefoxpokedex.domain.exception.DomainError
import com.iliaberlana.wefoxpokedex.framework.remote.NetworkFactory
import com.iliaberlana.wefoxpokedex.framework.remote.PokemonRemoteDataSource
import com.iliaberlana.wefoxpokedex.framework.remote.model.PokemonRemote
import com.iliaberlana.wefoxpokedex.framework.remote.model.Sprites
import com.iliaberlana.wefoxpokedex.framework.remote.model.Type
import com.iliaberlana.wefoxpokedex.framework.remote.model.Types
import io.kotlintest.matchers.types.shouldNotBeNull
import io.kotlintest.shouldBe
import kotlinx.coroutines.runBlocking
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.junit.After
import org.junit.Before
import org.junit.Test
class PokemonRemoteDataSourceTest {
private val mockWebServer = MockWebServer()
private lateinit var pokemonRemoteDataSource: PokemonRemoteDataSource
@Before
fun setUp() {
mockWebServer.start(8080)
val httpUrl = mockWebServer.url("/")
val testApp = ApplicationProvider.getApplicationContext() as TestApplication
testApp.setApiUrl(httpUrl.toString())
pokemonRemoteDataSource = PokemonRemoteDataSource(NetworkFactory(), httpUrl.toString())
}
@After
fun tearDown() {
mockWebServer.shutdown()
}
@Test
fun should_return_throw_when_response_is_not_200ok() = runBlocking {
mockWebServer.enqueue(MockResponse().setResponseCode(404))
var domainError: DomainError = DomainError.UnknownException
try {
pokemonRemoteDataSource.getPokemon(944)
} catch (error: DomainError) {
domainError = error
}
domainError.shouldBe(DomainError.NoPokemonFound)
}
@Test
fun should_result_a_pokemon() = runBlocking {
val response = MockResponse()
.addHeader("Content-Type", "application/json; charset=utf-8")
.addHeader("Cache-Control", "no-cache")
.setBody(
"{\n" +
"\t\"base_experience\": 64,\n" +
"\t\"height\": 7,\n" +
"\t\"id\": 1,\n" +
"\t\"name\": \"bulbasaur\",\n" +
"\t\"order\": 1,\n" +
"\t\"sprites\": {\n" +
"\t\t\"front_default\": \"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png\"\n" +
"\t},\n" +
"\t\"types\": [{\n" +
"\t\t\t\"slot\": 2,\n" +
"\t\t\t\"type\": {\n" +
"\t\t\t\t\"name\": \"poison\",\n" +
"\t\t\t\t\"url\": \"https://pokeapi.co/api/v2/type/4/\"\n" +
"\t\t\t}\n" +
"\t\t},\n" +
"\t\t{\n" +
"\t\t\t\"slot\": 1,\n" +
"\t\t\t\"type\": {\n" +
"\t\t\t\t\"name\": \"grass\",\n" +
"\t\t\t\t\"url\": \"https://pokeapi.co/api/v2/type/12/\"\n" +
"\t\t\t}\n" +
"\t\t}\n" +
"\t],\n" +
"\t\"weight\": 69\n" +
"}"
)
mockWebServer.enqueue(response)
val actual = pokemonRemoteDataSource.getPokemon(1)
actual.shouldNotBeNull()
val expected = PokemonRemote(
1,
1,
"bulbasaur",
69,
7,
64,
Sprites("https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png"),
listOf(Types(Type("poison")), Types(Type("grass")))
)
assertThat(expected).isEqualToWithGivenProperties(
actual,
PokemonRemote::id,
PokemonRemote::order,
PokemonRemote::name,
PokemonRemote::weight,
PokemonRemote::height,
PokemonRemote::sprites,
PokemonRemote::base_experience,
PokemonRemote::types
)
}
} | 0 | Kotlin | 0 | 0 | 51a085e2deb46eb06f933396b3b91f5347866915 | 4,402 | WefoxPokeDex | MIT License |
RoomDbUnitTest/app/src/main/java/com/example/roomdbunittest/ui/MainActivity.kt | fairoozp | 356,848,633 | false | null | package com.example.roomdbunittest.ui
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.roomdbunittest.R
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
} | 0 | Kotlin | 0 | 1 | 09bfb87ce91f6ccb6f8b08534b127f77116a5179 | 346 | Android_Kotlin_projects | MIT License |
detekt-gradle-plugin/src/test/kotlin/io/gitlab/arturbosch/detekt/DetektTaskKotlinDslTest.kt | DSamaryan | 138,333,243 | true | {"Kotlin": 1016009, "Java": 9706, "Groovy": 3620, "Shell": 1710, "HTML": 698} | package io.gitlab.arturbosch.detekt
import org.assertj.core.api.Assertions.assertThat
import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.TaskOutcome
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import java.io.File
/**
* @author Marvin Ramin
*/
internal class DetektTaskKotlinDslTest : Spek({
val buildGradle = """
|import io.gitlab.arturbosch.detekt.detekt
|
|plugins {
| `java-library`
| id("io.gitlab.arturbosch.detekt")
|}
|
|repositories {
| jcenter()
| mavenLocal()
|}
""".trimMargin()
val dslTest = DslBaseTest("build.gradle.kts", buildGradle)
describe("The Detekt Gradle plugin used in a build.gradle.kts file") {
lateinit var rootDir: File
beforeEachTest {
rootDir = createTempDir(prefix = "applyPlugin")
}
it("can be used without configuration") {
val detektConfig = ""
dslTest.writeFiles(rootDir, detektConfig)
dslTest.writeConfig(rootDir)
// Using a custom "project-cache-dir" to avoid a Gradle error on Windows
val result = GradleRunner.create()
.withProjectDir(rootDir)
.withArguments("--project-cache-dir", createTempDir(prefix = "cache").absolutePath, "check", "--stacktrace", "--info")
.withPluginClasspath()
.build()
assertThat(result.output).contains("number of classes: 1")
assertThat(result.output).contains("Ruleset: comments")
assertThat(result.task(":check")?.outcome).isEqualTo(TaskOutcome.SUCCESS)
}
it("can be used without configuration using source files in src/main/kotlin") {
val detektConfig = ""
val srcDir = File(rootDir, "src/main/kotlin")
dslTest.writeFiles(rootDir, detektConfig, srcDir)
dslTest.writeConfig(rootDir)
// Using a custom "project-cache-dir" to avoid a Gradle error on Windows
val result = GradleRunner.create()
.withProjectDir(rootDir)
.withArguments("--project-cache-dir", createTempDir(prefix = "cache").absolutePath, "check", "--stacktrace", "--info")
.withPluginClasspath()
.build()
assertThat(result.output).contains("number of classes: 1")
assertThat(result.output).contains("Ruleset: comments")
assertThat(result.task(":check")?.outcome).isEqualTo(TaskOutcome.SUCCESS)
}
it("can be applied with a custom detekt version") {
val detektConfig = """
|detekt {
| toolVersion = "$VERSION_UNDER_TEST"
|}
"""
dslTest.writeFiles(rootDir, detektConfig)
dslTest.writeConfig(rootDir)
// Using a custom "project-cache-dir" to avoid a Gradle error on Windows
val result = GradleRunner.create()
.withProjectDir(rootDir)
.withArguments("--project-cache-dir", createTempDir(prefix = "cache").absolutePath, "check", "--stacktrace", "--info")
.withPluginClasspath()
.build()
assertThat(result.output).contains("number of classes: 1")
assertThat(result.output).contains("Ruleset: comments")
assertThat(result.task(":check")?.outcome).isEqualTo(TaskOutcome.SUCCESS)
// Asserts that the "custom" module is not built, and that custom ruleset is not enabled
assertThat(result.output).doesNotContain("Ruleset: test-custom")
assertThat(File(rootDir, "custom/build")).doesNotExist()
}
it("can be applied with a custom config file") {
val configPath = File(rootDir, "config.yml")
val detektConfig = """
|detekt {
| config = files("${configPath.safeAbsolutePath}")
|}
"""
dslTest.writeFiles(rootDir, detektConfig)
dslTest.writeConfig(rootDir)
// Using a custom "project-cache-dir" to avoid a Gradle error on Windows
val result = GradleRunner.create()
.withProjectDir(rootDir)
.withArguments("--project-cache-dir", createTempDir(prefix = "cache").absolutePath, "check", "--stacktrace", "--info")
.withPluginClasspath()
.build()
assertThat(result.output).contains("Ruleset: comments", "number of classes: 1", "--config ${configPath.absolutePath}")
assertThat(result.task(":check")?.outcome).isEqualTo(TaskOutcome.SUCCESS)
}
it("can be applied with a full config") {
val configFile = File(rootDir, "config.yml")
val baselineFile = File(rootDir, "baseline.xml")
val detektConfig = """
|detekt {
| debug = true
| parallel = true
| disableDefaultRuleSets = true
| toolVersion = "$VERSION_UNDER_TEST"
| config = files("${configFile.safeAbsolutePath}")
| baseline = file("${baselineFile.safeAbsolutePath}")
| filters = ".*/resources/.*, .*/build/.*"
|}
"""
dslTest.writeFiles(rootDir, detektConfig)
dslTest.writeConfig(rootDir)
dslTest.writeBaseline(rootDir)
// Using a custom "project-cache-dir" to avoid a Gradle error on Windows
val result = GradleRunner.create()
.withProjectDir(rootDir)
.withArguments("--project-cache-dir", createTempDir(prefix = "cache").absolutePath, "check", "--stacktrace", "--info")
.withPluginClasspath()
.build()
assertThat(result.output).contains("number of classes: 1")
assertThat(result.output).contains("--parallel", "--debug", "--disable-default-rulesets")
assertThat(result.output).doesNotContain("Ruleset: comments")
assertThat(result.task(":check")?.outcome).isEqualTo(TaskOutcome.SUCCESS)
}
it("can configure a new custom detekt task") {
val configFile = File(rootDir, "config.yml")
val detektConfig = """
|task<io.gitlab.arturbosch.detekt.Detekt>("detektFailFast") {
| description = "Runs a failfast detekt build."
|
| input = files("src/main/java")
| config = files("${configFile.safeAbsolutePath}")
| debug = true
| reports {
| xml {
| destination = file("build/reports/failfast.xml")
| }
| html.destination = file("build/reports/failfast.html")
| }
|}
"""
dslTest.writeFiles(rootDir, detektConfig)
dslTest.writeConfig(rootDir, failfast = true)
dslTest.writeBaseline(rootDir)
// Using a custom "project-cache-dir" to avoid a Gradle error on Windows
val result = GradleRunner.create()
.withProjectDir(rootDir)
.withArguments("--project-cache-dir", createTempDir(prefix = "cache").absolutePath, "detektFailFast", "--stacktrace", "--info")
.withPluginClasspath()
.build()
assertThat(result.output).contains("number of classes: 1")
assertThat(result.output).contains("Ruleset: comments")
assertThat(result.task(":detektFailFast")?.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(File(rootDir, "build/reports/failfast.xml")).exists()
assertThat(File(rootDir, "build/reports/failfast.html")).exists()
}
it("can configure reports") {
val detektConfig = """
|detekt {
| reports {
| xml.destination = file("build/xml/detekt.xml")
| html.destination = file("build/html/detekt.html")
| }
|}
"""
dslTest.writeFiles(rootDir, detektConfig)
dslTest.writeConfig(rootDir)
dslTest.writeBaseline(rootDir)
// Using a custom "project-cache-dir" to avoid a Gradle error on Windows
val result = GradleRunner.create()
.withProjectDir(rootDir)
.withArguments("--project-cache-dir", createTempDir(prefix = "cache").absolutePath, "check", "--stacktrace", "--info")
.withPluginClasspath()
.build()
assertThat(result.output).contains("number of classes: 1")
assertThat(result.output).contains("Ruleset: comments")
assertThat(result.task(":check")?.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(File(rootDir, "build/xml/detekt.xml")).exists()
assertThat(File(rootDir, "build/html/detekt.html")).exists()
}
it("can configure reports base directory") {
val detektConfig = """
|detekt {
| reportsDir = file("build/my-reports")
|}
"""
dslTest.writeFiles(rootDir, detektConfig)
dslTest.writeConfig(rootDir)
dslTest.writeBaseline(rootDir)
// Using a custom "project-cache-dir" to avoid a Gradle error on Windows
val result = GradleRunner.create()
.withProjectDir(rootDir)
.withArguments("--project-cache-dir", createTempDir(prefix = "cache").absolutePath, "check", "--stacktrace", "--info")
.withPluginClasspath()
.build()
assertThat(result.output).contains("number of classes: 1")
assertThat(result.task(":check")?.outcome).isEqualTo(TaskOutcome.SUCCESS)
assertThat(File(rootDir, "build/my-reports/detekt.xml")).exists()
assertThat(File(rootDir, "build/my-reports/detekt.html")).exists()
}
it("can configure the input directory") {
val customSourceLocation = File(rootDir, "gensrc/kotlin")
val detektConfig = """
|detekt {
| debug = true
| input = files("${customSourceLocation.safeAbsolutePath}")
|}
"""
dslTest.writeFiles(rootDir, detektConfig, customSourceLocation)
dslTest.writeConfig(rootDir)
dslTest.writeBaseline(rootDir)
// Using a custom "project-cache-dir" to avoid a Gradle error on Windows
val result = GradleRunner.create()
.withProjectDir(rootDir)
.withArguments("--project-cache-dir", createTempDir(prefix = "cache").absolutePath, "check", "--stacktrace", "--info")
.withPluginClasspath()
.build()
assertThat(result.output).contains("number of classes: 1")
assertThat(result.output).contains("--input, ${customSourceLocation.absolutePath}")
assertThat(result.task(":check")?.outcome).isEqualTo(TaskOutcome.SUCCESS)
}
it("can be used without configuration") {
val detektConfig = """
|dependencies {
| detektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:${VERSION_UNDER_TEST}")
|}
"""
dslTest.writeFiles(rootDir, detektConfig)
dslTest.writeConfig(rootDir)
// Using a custom "project-cache-dir" to avoid a Gradle error on Windows
val result = GradleRunner.create()
.withProjectDir(rootDir)
.withArguments("--project-cache-dir", createTempDir(prefix = "cache").absolutePath, "check", "--stacktrace", "--info")
.withPluginClasspath()
.build()
assertThat(result.output).contains("number of classes: 1")
assertThat(result.output).contains("Ruleset: comments")
assertThat(result.task(":check")?.outcome).isEqualTo(TaskOutcome.SUCCESS)
}
}
})
| 0 | Kotlin | 0 | 0 | 2f9ba37842f2c7e562b9fd7a8f8f8328842483f3 | 10,182 | detekt | Apache License 2.0 |
src/main/kotlin/io/layercraft/packetlib/packets/v1_19_3/play/clientbound/StatisticsPacket.kt | Layercraft | 531,857,310 | false | null | package io.layercraft.packetlib.packets.v1_19_3.play.clientbound
import io.layercraft.packetlib.packets.*
import io.layercraft.packetlib.serialization.MinecraftProtocolDeserializeInterface
import io.layercraft.packetlib.serialization.MinecraftProtocolSerializeInterface
/**
* Award Statistics | 0x04 | play | clientbound
*
* @param entries list of StatisticsPacketEntries
* @see <a href="https://wiki.vg/index.php?title=Protocol&oldid=18071#Award_Statistics">https://wiki.vg/Protocol#Award_Statistics</a>
*/
@MinecraftPacket(id = 0x04, state = PacketState.PLAY, direction = PacketDirection.CLIENTBOUND)
data class StatisticsPacket(
val entries: List<StatisticsPacketEntries>, // varint array
) : ClientBoundPacket {
companion object : PacketSerializer<StatisticsPacket> {
override fun deserialize(input: MinecraftProtocolDeserializeInterface<*>): StatisticsPacket {
val entries = input.readVarIntArray { arrayInput ->
val categoryId = arrayInput.readVarInt()
val statisticId = arrayInput.readVarInt()
val value = arrayInput.readVarInt()
return@readVarIntArray StatisticsPacketEntries(categoryId, statisticId, value)
}
return StatisticsPacket(entries)
}
override fun serialize(output: MinecraftProtocolSerializeInterface<*>, value: StatisticsPacket) {
output.writeVarIntArray(value.entries) { arrayValue, arrayOutput ->
arrayOutput.writeVarInt(arrayValue.categoryId)
arrayOutput.writeVarInt(arrayValue.statisticId)
arrayOutput.writeVarInt(arrayValue.value)
}
}
}
}
/**
* StatisticsPacketEntries
*
* @param categoryId categoryId
* @param statisticId statisticId
* @param value value
*/
data class StatisticsPacketEntries(
val categoryId: Int, // varint
val statisticId: Int, // varint
val value: Int, // varint
) | 5 | Kotlin | 1 | 4 | 3491d690689369264101853861e1d5a572cde24f | 1,955 | PacketLib | MIT License |
app/src/main/java/com/impaircheck/constants.kt | mahmoud-elsadany | 834,831,205 | false | {"Kotlin": 267428} | package com.impaircheck
import com.google.firebase.database.DatabaseReference
import com.impaircheck.models.userTestsItem
object constants {
lateinit var fireBaseDatabase: DatabaseReference
var APP_VERSION = ""
var APP_VERSION_CODE = -1
var IS_NEW_USER = false
var currentUserId = -1
var currentTestObject: userTestsItem? = null
} | 0 | Kotlin | 0 | 1 | 6bbc86748f1c5e0c5298219f70dfaffe0907807e | 361 | ImpairCheckRepo | MIT License |
libraries/tools/kotlin-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/logging/GradlePrintingMessageCollector.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-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.gradle.logging
import org.gradle.api.logging.Logger
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.compilerRunner.KotlinLogger
internal class GradlePrintingMessageCollector(val logger: KotlinLogger) :
MessageCollector {
constructor(logger: Logger) : this(GradleKotlinLogger(logger))
private var hasErrors = false
override fun hasErrors() = hasErrors
override fun clear() {
// Do nothing
}
override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) {
fun formatMsg(prefix: String) =
buildString {
append("$prefix: ")
location?.apply {
append("$path: ")
if (line > 0 && column > 0) {
append("($line, $column): ")
}
}
append(message)
}
when (severity) {
CompilerMessageSeverity.ERROR,
CompilerMessageSeverity.EXCEPTION -> {
hasErrors = true
logger.error(formatMsg("e"))
}
CompilerMessageSeverity.WARNING,
CompilerMessageSeverity.STRONG_WARNING -> {
logger.warn(formatMsg("w"))
}
CompilerMessageSeverity.INFO -> {
logger.info(formatMsg("i"))
}
CompilerMessageSeverity.LOGGING,
CompilerMessageSeverity.OUTPUT -> {
logger.debug(formatMsg("v"))
}
}!! // !! is used to force compile-time exhaustiveness
}
} | 1 | Kotlin | 2 | 2 | b6be6a4919cd7f37426d1e8780509a22fa49e1b1 | 1,988 | kotlin | Apache License 2.0 |
libraries/framework/src/main/java/com/developersancho/framework/base/BaseFragment.kt | developersancho | 523,126,274 | false | {"Kotlin": 182195} | package com.developersancho.framework.base
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
abstract class BaseFragment<VB : ViewBinding> : Fragment() {
private var _binding: VB? = null
val binding: VB
get() = _binding
?: throw RuntimeException("Should only use binding after onCreateView and before onDestroyView")
protected fun requireBinding(): VB = requireNotNull(_binding)
protected var viewId: Int = -1
abstract fun onViewReady(bundle: Bundle?)
open fun onViewListener() {}
open fun observeUi() {}
final override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = getBinding(inflater, container)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewId = binding.root.id
observeUi()
onViewReady(savedInstanceState)
onViewListener()
}
override fun onDestroyView() {
_binding = null
super.onDestroyView()
}
protected fun checkArgument(argsKey: String): Boolean {
return requireArguments().containsKey(argsKey)
}
protected fun requireCompatActivity(): AppCompatActivity {
requireActivity()
val activity = requireActivity()
if (activity is AppCompatActivity) {
return activity
} else {
throw TypeCastException("Main activity should extend from 'AppCompatActivity'")
}
}
} | 0 | Kotlin | 0 | 8 | 3557e85b86699d8c053a9fc370077ef580a8019a | 1,791 | HB.Case.Android | Apache License 2.0 |
bookpage/src/main/java/com/kai/crawler/xpath/core/AxisSelector.kt | pressureKai | 326,004,502 | false | null | package com.kai.crawler.xpath.core
import org.jsoup.nodes.Element
import org.jsoup.select.Elements
/**
* 通过轴选出对应作用域的全部节点
* 去掉不实用的轴,不支持namespace,attribute(可用 /@*代替),preceding(preceding-sibling支持),following(following-sibling支持)
* 添加 preceding-sibling-one,following-sibling-one,即只选前一个或后一个兄弟节点,添加 sibling 选取全部兄弟节点
*/
class AxisSelector {
/**
* 自身
*
* @param e
* @return
*/
fun self(e: Element?): Elements {
return Elements(e)
}
/**
* 父节点
*
* @param e
* @return
*/
fun parent(e: Element): Elements {
return Elements(e.parent())
}
/**
* 直接子节点
*
* @param e
* @return
*/
fun child(e: Element): Elements {
return e.children()
}
/**
* 全部祖先节点 父亲,爷爷 , 爷爷的父亲...
*
* @param e
* @return
*/
fun ancestor(e: Element): Elements {
return e.parents()
}
/**
* 全部祖先节点和自身节点
*
* @param e
* @return
*/
fun ancestorOrSelf(e: Element): Elements {
val rs = e.parents()
rs.add(e)
return rs
}
/**
* 全部子代节点 儿子,孙子,孙子的儿子...
*
* @param e
* @return
*/
fun descendant(e: Element): Elements {
return e.allElements
}
/**
* 全部子代节点和自身
*
* @param e
* @return
*/
fun descendantOrSelf(e: Element): Elements {
val rs = e.allElements
rs.add(e)
return rs
}
/**
* 节点前面的全部同胞节点,preceding-sibling
*
* @param e
* @return
*/
fun precedingSibling(e: Element): Elements {
val rs = Elements()
var tmp = e.previousElementSibling()
while (tmp != null) {
rs.add(tmp)
tmp = tmp.previousElementSibling()
}
return rs
}
/**
* 返回前一个同胞节点(扩展),语法 preceding-sibling-one
*
* @param e
* @return
*/
fun precedingSiblingOne(e: Element): Elements {
val rs = Elements()
if (e.previousElementSibling() != null) {
rs.add(e.previousElementSibling())
}
return rs
}
/**
* 节点后面的全部同胞节点following-sibling
*
* @param e
* @return
*/
fun followingSibling(e: Element): Elements {
val rs = Elements()
var tmp = e.nextElementSibling()
while (tmp != null) {
rs.add(tmp)
tmp = tmp.nextElementSibling()
}
return rs
}
/**
* 返回下一个同胞节点(扩展) 语法 following-sibling-one
*
* @param e
* @return
*/
fun followingSiblingOne(e: Element): Elements {
val rs = Elements()
if (e.nextElementSibling() != null) {
rs.add(e.nextElementSibling())
}
return rs
}
/**
* 全部同胞(扩展)
*
* @param e
* @return
*/
fun sibling(e: Element): Elements {
return e.siblingElements()
}
} | 0 | Kotlin | 1 | 1 | 73edc5e8b838f9ba89e5ac717051c15871120673 | 2,928 | FreeRead | Apache License 2.0 |
plugins/kotlin/completion/testData/kdoc/TagNameMiddle.kt | ingokegel | 72,937,917 | true | null | // FIR_COMPARISON
// FIR_IDENTICAL
/**
* @r<caret>
*/
fun f(x: Int): Int {
}
// ABSENT: @param
// EXIST: @return | 1 | null | 1 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 115 | intellij-community | Apache License 2.0 |
DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/openshift/authentication.kt | fkorotkov | 84,911,320 | false | null | // GENERATED
package com.fkorotkov.openshift
import io.fabric8.openshift.api.model.ConsoleAuthentication as model_ConsoleAuthentication
import io.fabric8.openshift.api.model.ConsoleSpec as model_ConsoleSpec
fun model_ConsoleSpec.`authentication`(block: model_ConsoleAuthentication.() -> Unit = {}) {
if(this.`authentication` == null) {
this.`authentication` = model_ConsoleAuthentication()
}
this.`authentication`.block()
}
| 4 | Kotlin | 19 | 301 | fa0b20b5a542cb332430fa85b1035456939a2ca6 | 440 | k8s-kotlin-dsl | MIT License |
app/src/main/java/com/apptive/linkit/presentation/model/FolderView.kt | Cotidie | 448,929,843 | false | null | package com.apptive.linkit.presentation.model
import android.graphics.Bitmap
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import com.apptive.linkit.domain.model.EMPTY_BITMAP
import com.apptive.linkit.domain.model.EMPTY_LONG
/** Compose에서 활용할 Folder 객체 */
data class FolderView(
val id: Long = EMPTY_LONG,
val name: MutableState<String> = mutableStateOf(""),
val image: MutableState<Bitmap> = mutableStateOf(EMPTY_BITMAP),
val gid: MutableState<Long?> = mutableStateOf(null),
val snode: MutableState<Long?> = mutableStateOf(null)
) {
fun isShared(): Boolean = (gid.value != null)
} | 10 | Kotlin | 1 | 3 | 9396b6dcf0d92cb46722b3fc4ba76c2d2007f2ae | 653 | Linkit-App | Apache License 2.0 |
app/src/main/java/io/github/tonnyl/mango/data/User.kt | LoveAndroid01 | 99,331,552 | true | {"Kotlin": 176451, "HTML": 27029} | package io.github.tonnyl.mango.data
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Embedded
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
import android.os.Parcel
import android.os.Parcelable
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
/**
* Created by lizhaotailang on 2017/6/25.
* {
* "id" : 1,
* "name" : "<NAME>",
* "username" : "simplebits",
* "html_url" : "https://dribbble.com/simplebits",
* "avatar_url" : "https://d13yacurqjgara.cloudfront.net/users/1/avatars/normal/dc.jpg?1371679243",
* "bio" : "Co-founder & designer of <a href=\"https://dribbble.com/dribbble\">@Dribbble</a>. Principal of SimpleBits. Aspiring clawhammer banjoist.",
* "location" : "Salem, MA",
* "links" : {
* "web" : "http://simplebits.com",
* "twitter" : "https://twitter.com/simplebits"
* },
* "buckets_count" : 10,
* "comments_received_count" : 3395,
* "followers_count" : 29262,
* "followings_count" : 1728,
* "likes_count" : 34954,
* "likes_received_count" : 27568,
* "projects_count" : 8,
* "rebounds_received_count" : 504,
* "shots_count" : 214,
* "teams_count" : 1,
* "can_upload_shot" : true,
* "type" : "Player",
* "pro" : true,
* "buckets_url" : "https://dribbble.com/v1/users/1/buckets",
* "followers_url" : "https://dribbble.com/v1/users/1/followers",
* "following_url" : "https://dribbble.com/v1/users/1/following",
* "likes_url" : "https://dribbble.com/v1/users/1/likes",
* "shots_url" : "https://dribbble.com/v1/users/1/shots",
* "teams_url" : "https://dribbble.com/v1/users/1/teams",
* "created_at" : "2009-07-08T02:51:22Z",
* "updated_at" : "2014-02-22T17:10:33Z"
* }
*/
@Entity(tableName = "user")
class User() : Parcelable {
@ColumnInfo(name = "name")
@SerializedName("name")
@Expose
var name: String = ""
@ColumnInfo(name = "username")
@SerializedName("username")
@Expose
var username: String = ""
@ColumnInfo(name = "html_url")
@SerializedName("html_url")
@Expose
var htmlUrl: String = ""
@ColumnInfo(name = "avatar_url")
@SerializedName("avatar_url")
@Expose
var avatarUrl: String = ""
@ColumnInfo(name = "bio")
@SerializedName("bio")
@Expose
var bio: String = ""
@ColumnInfo(name = "location")
@SerializedName("location")
@Expose
var location: String? = ""
@Embedded
@SerializedName("links")
@Expose
var links: Links = Links()
@ColumnInfo(name = "buckets_count")
@SerializedName("buckets_count")
@Expose
var bucketsCount: Int = 0
@ColumnInfo(name = "comments_received_count")
@SerializedName("comments_received_count")
@Expose
var commentsReceivedCount: Int = 0
@ColumnInfo(name = "followers_count")
@SerializedName("followers_count")
@Expose
var followersCount: Int = 0
@ColumnInfo(name = "followings_count")
@SerializedName("followings_count")
@Expose
var followingsCount: Int = 0
@ColumnInfo(name = "likes_count")
@SerializedName("likes_count")
@Expose
var likesCount: Int = 0
@ColumnInfo(name = "likes_received_count")
@SerializedName("likes_received_count")
@Expose
var likesReceivedCount: Int = 0
@ColumnInfo(name = "projects_count")
@SerializedName("projects_count")
@Expose
var projectsCount: Int = 0
@ColumnInfo(name = "rebounds_received_count")
@SerializedName("rebounds_received_count")
@Expose
var reboundsReceivedCount: Int = 0
@ColumnInfo(name = "shots_count")
@SerializedName("shots_count")
@Expose
var shotsCount: Int = 0
@ColumnInfo(name = "teams_count")
@SerializedName("teams_count")
@Expose
var teamsCount: Int = 0
@ColumnInfo(name = "can_upload_shot")
@SerializedName("can_upload_shot")
@Expose
var canUploadShot: Boolean = false
@ColumnInfo(name = "type")
@SerializedName("type")
@Expose
var type: String = ""
@ColumnInfo(name = "pro")
@SerializedName("pro")
@Expose
var pro: Boolean = false
@ColumnInfo(name = "buckets_url")
@SerializedName("buckets_url")
@Expose
var bucketsUrl: String = ""
@ColumnInfo(name = "followers_url")
@SerializedName("followers_url")
@Expose
var followersUrl: String = ""
@ColumnInfo(name = "following_url")
@SerializedName("following_url")
@Expose
var followingUrl: String = ""
@ColumnInfo(name = "likes_url")
@SerializedName("likes_url")
@Expose
var likesUrl: String = ""
@ColumnInfo(name = "shots_url")
@SerializedName("shots_url")
@Expose
var shotsUrl: String = ""
@ColumnInfo(name = "teams_url")
@SerializedName("teams_url")
@Expose
var teamsUrl: String? = ""
@ColumnInfo(name = "created_at")
@SerializedName("created_at")
@Expose
var createdAt: String = ""
@ColumnInfo(name = "updated_at")
@SerializedName("updated_at")
@Expose
var updatedAt: String = ""
@ColumnInfo(name = "id")
@field: PrimaryKey
@SerializedName("id")
@Expose
var id: Long = 0L
constructor(parcel: Parcel) : this() {
name = parcel.readString()
username = parcel.readString()
htmlUrl = parcel.readString()
avatarUrl = parcel.readString()
bio = parcel.readString()
location = parcel.readString()
links = parcel.readParcelable(Links::class.java.classLoader)
bucketsCount = parcel.readInt()
commentsReceivedCount = parcel.readInt()
followersCount = parcel.readInt()
followingsCount = parcel.readInt()
likesCount = parcel.readInt()
likesReceivedCount = parcel.readInt()
projectsCount = parcel.readInt()
reboundsReceivedCount = parcel.readInt()
shotsCount = parcel.readInt()
teamsCount = parcel.readInt()
canUploadShot = parcel.readByte() != 0.toByte()
type = parcel.readString()
pro = parcel.readByte() != 0.toByte()
bucketsUrl = parcel.readString()
followersUrl = parcel.readString()
followingUrl = parcel.readString()
likesUrl = parcel.readString()
shotsUrl = parcel.readString()
teamsUrl = parcel.readString()
createdAt = parcel.readString()
updatedAt = parcel.readString()
id = parcel.readLong()
}
companion object CREATOR : Parcelable.Creator<User> {
override fun createFromParcel(parcel: Parcel): User {
return User(parcel)
}
override fun newArray(size: Int): Array<User?> {
return arrayOfNulls(size)
}
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(name)
parcel.writeString(username)
parcel.writeString(htmlUrl)
parcel.writeString(avatarUrl)
parcel.writeString(bio)
parcel.writeString(location)
parcel.writeParcelable(links, flags)
parcel.writeInt(bucketsCount)
parcel.writeInt(commentsReceivedCount)
parcel.writeInt(followersCount)
parcel.writeInt(followingsCount)
parcel.writeInt(likesCount)
parcel.writeInt(likesReceivedCount)
parcel.writeInt(projectsCount)
parcel.writeInt(reboundsReceivedCount)
parcel.writeInt(shotsCount)
parcel.writeInt(teamsCount)
parcel.writeByte(if (canUploadShot) 1.toByte() else 0.toByte())
parcel.writeString(type)
parcel.writeByte(if (pro) 1.toByte() else 0.toByte())
parcel.writeString(bucketsUrl)
parcel.writeString(followersUrl)
parcel.writeString(followingUrl)
parcel.writeString(likesUrl)
parcel.writeString(shotsUrl)
parcel.writeString(teamsUrl)
parcel.writeString(createdAt)
parcel.writeString(updatedAt)
parcel.writeLong(id)
}
override fun describeContents(): Int {
return 0
}
} | 0 | Kotlin | 0 | 0 | 2398034f0de3e44a07fab660bc1bac0dd5d42945 | 8,018 | Mango | MIT License |
builder/src/commonMain/kotlin/pw/binom/builder/node/ThreadReader.kt | caffeine-mgn | 196,877,393 | false | null | package pw.binom.builder.node
import pw.binom.AppendableQueue
import pw.binom.builder.OutType
import pw.binom.io.EOFException
import pw.binom.io.InputStream
import pw.binom.io.Reader
import pw.binom.io.utf8Reader
import pw.binom.job.Task
class Out(val value: String?, val type: OutType)
class ThreadReader(inputStream: InputStream, val type: OutType, val out: AppendableQueue<Out>) : Task() {
private val streamReader = inputStream.utf8Reader()
override fun execute() {
while (!isInterrupted) {
try {
val l = streamReader.readln1()
out.push(Out(l, type))
} catch (e: EOFException) {
out.push(Out(null, type))
break
}
}
}
}
fun Reader.readln1(): String {
val sb = StringBuilder()
var first = true
while (true) {
val r = read()
if (r == null && first)
throw EOFException()
first = false
if (r == null)
break
if (r == 10.toChar())
break
if (r == 13.toChar())
continue
sb.append(r)
}
return sb.toString()
} | 0 | Kotlin | 0 | 0 | 139606a956de5fc41b8cc92243e7e5905fa8b147 | 1,159 | Builder | Apache License 2.0 |
src/main/java/ru/hollowhorizon/hollowengine/common/story/ClientCameraPlayer.kt | HollowHorizon | 586,593,959 | false | {"Kotlin": 236884, "Java": 86740} | package ru.hollowhorizon.hollowengine.common.story
import kotlinx.serialization.Serializable
import net.minecraft.nbt.CompoundTag
import net.minecraft.world.phys.Vec3
import net.minecraftforge.client.event.ViewportEvent.ComputeCameraAngles
import net.minecraftforge.common.MinecraftForge
import net.minecraftforge.eventbus.api.SubscribeEvent
import net.minecraftforge.network.NetworkDirection
import ru.hollowhorizon.hc.client.utils.nbt.ForCompoundNBT
import ru.hollowhorizon.hc.common.network.HollowPacketV2
import ru.hollowhorizon.hc.common.network.Packet
import ru.hollowhorizon.hollowengine.mixins.CameraInvoker
@Serializable
class Container(val tag: @Serializable(ForCompoundNBT::class) CompoundTag)
@HollowPacketV2(NetworkDirection.PLAY_TO_CLIENT)
class StartCameraPlayerPacket: Packet<Container>({ player, container ->
ClientCameraPlayer.start(container.tag)
})
object ClientCameraPlayer : CameraPlayer() {
fun start(nbt: CompoundTag) {
deserializeNBT(nbt)
reset()
MinecraftForge.EVENT_BUS.register(this)
}
@SubscribeEvent
fun updateMovement(event: ComputeCameraAngles) {
val (point, rotation) = update()
(event.camera as CameraInvoker).invokeSetPosition(Vec3(point.x, point.y, point.z))
event.yaw = rotation.x
event.pitch = rotation.y
}
override fun onEnd() {
MinecraftForge.EVENT_BUS.unregister(this)
}
} | 0 | Kotlin | 4 | 7 | 73f12390ae92c570144d74ce0407dad64e10e115 | 1,416 | HollowEngine | MIT License |
app/src/main/java/com/nominalista/expenses/home/presentation/HomeActivity.kt | yesidlazaro | 199,455,882 | true | {"Kotlin": 135809} | package com.nominalista.expenses.home.presentation
import android.os.Bundle
import com.nominalista.expenses.R
import com.nominalista.expenses.common.presentation.BaseActivity
class HomeActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
setSupportActionBar(findViewById(R.id.toolbar))
}
} | 0 | Kotlin | 0 | 1 | 8e43cf30a5bb2b64013a368e895fb73570388659 | 426 | expenses | Apache License 2.0 |
src/main/kotlin/kg/jedi/fourangle/common/Exceptions.kt | zhoodar | 126,834,438 | false | null | package kg.jedi.fourangle.common
class ObjectNotFoundException(message: String): RuntimeException(message) | 0 | Kotlin | 0 | 0 | 3a1c7d25e8b6f7d29e48ca5a4256a1dbb7410928 | 107 | 4angle | Apache License 2.0 |
features/tracker/src/androidMain/kotlin/com/escodro/tracker/TrackerActivity.kt | igorescodro | 116,942,964 | false | {"Kotlin": 553772, "Swift": 2353, "Shell": 1790} | package com.escodro.tracker
import android.content.Context
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.escodro.designsystem.AlkaaTheme
import com.escodro.tracker.presentation.TrackerScreen
import com.google.android.play.core.splitcompat.SplitCompat
internal class TrackerActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
AlkaaTheme {
TrackerScreen(onUpPress = { finish() })
}
}
}
override fun attachBaseContext(context: Context) {
super.attachBaseContext(context)
SplitCompat.installActivity(context)
}
}
| 13 | Kotlin | 130 | 1,323 | 5673efab7b1994e1de5d5058fe6369df19e4b7de | 768 | alkaa | Apache License 2.0 |
src/main/kotlin/com/github/martinsucha/idedynamicsecrets/Notifications.kt | martin-sucha | 316,737,293 | false | null | package com.github.martinsucha.idedynamicsecrets
import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationType
import com.intellij.openapi.project.Project
fun notifyError(project: Project, content: String) {
NotificationGroupManager.getInstance().getNotificationGroup("Dynamic Secrets")
.createNotification(content, NotificationType.ERROR)
.notify(project)
}
| 2 | Kotlin | 0 | 10 | 539bbe2f51d657d38771e4349c67e9ae8fe83e3b | 427 | ide-dynamic-secrets | Apache License 2.0 |
build-logic/convention/src/main/java/com/mburakcakir/convention/extensions/HiltAndroid.kt | mburakcakir | 812,291,624 | false | {"Kotlin": 81965} | package com.mburakcakir.convention.extensions
import org.gradle.api.Project
import org.gradle.kotlin.dsl.dependencies
internal fun Project.configureHiltAndroid() {
pluginManager.apply(libs.plugins.android.hilt.get().pluginId)
dependencies {
implementation(libs.hilt.android)
implementation(libs.hilt.navigation.compose)
ksp(libs.hilt.android.compiler)
}
} | 0 | Kotlin | 0 | 0 | 04961794a58fea1e0ee45a5ad5db9974da6da65f | 394 | Table | Apache License 2.0 |
module_home/src/main/kotlin/com/crow/module_home/network/HomeService.kt | CrowForKotlin | 610,636,509 | false | null | package com.crow.module_home.network
import com.crow.base.current_project.BaseResultResp
import com.crow.base.current_project.BaseStrings
import com.crow.module_home.model.resp.homepage.ComicDatas
import com.crow.module_home.model.resp.homepage.results.RecComicsResult
import com.crow.module_home.model.resp.homepage.results.Results
import kotlinx.coroutines.flow.Flow
import retrofit2.http.GET
import retrofit2.http.Query
/*************************
* @Machine: RedmiBook Pro 15 Win11
* @Path: module_home/src/main/kotlin/com/crow/module_home/network
* @Time: 2023/3/6 9:13
* @Author: CrowForKotlin
* @Description: HomeService
* @formatter:on
**************************/
interface HomeService {
@GET(BaseStrings.URL.HomePage)
fun getHomePage(): Flow<BaseResultResp<Results>>
@GET(BaseStrings.URL.RefreshRec)
fun getRecPage(@Query("limit") limit: Int, @Query("offset") start: Int, @Query("pos") pos:Int = 3200102): Flow<BaseResultResp<ComicDatas<RecComicsResult>>>
} | 0 | Kotlin | 0 | 2 | a89de12c3004f749270a0cfd6cc4b042de332715 | 992 | CopyManga_Crow | Apache License 2.0 |
dp-inntekt-api/src/main/kotlin/no/nav/dagpenger/inntekt/oppslag/PersonOppslag.kt | navikt | 165,044,758 | false | {"Kotlin": 435885, "Dockerfile": 108} | package no.nav.dagpenger.inntekt.oppslag
interface PersonOppslag {
suspend fun hentPerson(ident: String): Person
}
class PersonNotFoundException(val ident: String?, msg: String = "Fant ikke person") : RuntimeException(msg)
data class Person(
val fødselsnummer: String,
val aktørId: String,
val fornavn: String,
val mellomnavn: String? = null,
val etternavn: String,
) {
fun sammensattNavn(): String = "$etternavn, $fornavn" + (mellomnavn?.let { " $it" } ?: "")
}
| 0 | Kotlin | 1 | 0 | 05027169269d1d9718e5663c8147b06d27318207 | 494 | dp-inntekt | MIT License |
utils/src/commonMain/kotlin/io/github/dmitriy1892/kmm/utils/coroutines/flow/FlowExtensions.kt | Dmitriy1892 | 641,006,459 | false | {"Kotlin": 27697, "Swift": 340, "Ruby": 102, "Shell": 84} | package io.github.dmitriy1892.kmm.utils.coroutines.flow
import io.github.dmitriy1892.kmm.utils.coroutines.Closeable
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
fun <T: Any> StateFlow<T>.asWrappedStateFlow(): WrappedStateFlow<T> = WrappedStateFlow(this)
fun <T: Any> MutableStateFlow<T>.asWrappedStateFlow(): WrappedStateFlow<T> =
this.asStateFlow().asWrappedStateFlow()
fun <T: Any> SharedFlow<T>.asWrappedSharedFlow(): WrappedSharedFlow<T> =
WrappedSharedFlow(this)
fun <T: Any> MutableSharedFlow<T>.asWrappedSharedFlow(): WrappedSharedFlow<T> =
this.asSharedFlow().asWrappedSharedFlow()
fun <T : Any> Flow<T>.asWrappedFlow(): WrappedFlow<T> = WrappedFlow(this)
internal fun <T> Flow<T>.subscribeToFlow(block: (T) -> Unit): Closeable {
val context = CoroutineScope(Dispatchers.Main + SupervisorJob())
this.onEach(block).launchIn(context)
return object : Closeable {
override fun close(): Unit = context.cancel()
}
} | 0 | Kotlin | 0 | 0 | 660ff1bfb44a9eb07f8e8cd9d4868fd059b76e42 | 1,450 | KMM-Utils | Apache License 2.0 |
app/src/main/java/com/test/test_firebase/MainActivity.kt | EvanCode20 | 623,327,717 | false | null | package com.test.test_firebase
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
class MainActivity : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val txtUsername = findViewById<EditText>(R.id.etUsername)
val pwPassword = findViewById<EditText>(R.id.etPassword)
val btnSignUp = findViewById<Button>(R.id.btnSignUp)
//this is a comment that will go in testpr branch
auth = Firebase.auth
btnSignUp.setOnClickListener {
val inputUsername = txtUsername.text.toString()
val inputPassword = <PASSWORD>()
auth.createUserWithEmailAndPassword(inputUsername, inputPassword)
.addOnCompleteListener(this)
{ task ->
if (task.isSuccessful) {
Toast.makeText(this, "Success", Toast.LENGTH_LONG).show()
}
}
.addOnFailureListener(this)
{
exception ->
Toast.makeText(this,exception.message, Toast.LENGTH_LONG).show()
}
}
}
} | 0 | Kotlin | 0 | 0 | 626368b9253b29d13ae2269c2cbefdd0568aceb6 | 1,569 | test_firebaseBeta | MIT License |
libraries/security/src/main/java/com/fappslab/libraries/security/bip39colors/BIP39Colors.kt | F4bioo | 693,834,465 | false | {"Kotlin": 312322, "Python": 2789, "Shell": 900} | package com.fappslab.libraries.security.bip39colors
interface BIP39Colors {
suspend fun encodeSeedColor(readableSeed: String): List<Pair<String, String>>
suspend fun decodeSeedColor(coloredSeed: String): String
}
| 0 | Kotlin | 0 | 0 | 41818c7276faca86fa8787cc62ec9fa971ac756f | 222 | Seedcake | MIT License |
app/src/main/java/com/example/visitamonument/ui/screen/AppScreen.kt | 17xr | 840,466,558 | false | {"Kotlin": 69689} | package com.example.visitamonument.ui.screen
import androidx.compose.animation.AnimatedContentTransitionScope
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import com.example.visitamonument.R
import com.example.visitamonument.data.LocalDataProvider
import com.example.visitamonument.model.AppContentType
import com.example.visitamonument.model.AppScreen
import com.example.visitamonument.model.AppUiState
import com.example.visitamonument.model.AppViewModel
@Composable
fun VisitAMonumentApp(
modifier: Modifier = Modifier,
appViewModel: AppViewModel,
navController: NavHostController,
contentType: AppContentType
) {
val appUiState: State<AppUiState> = appViewModel.uiState.collectAsState()
Scaffold(
topBar = {
when (contentType) {
AppContentType.One -> {
when (appUiState.value.currentScreen) {
AppScreen.General -> {
GeneralScreenTopAppBar()
}
AppScreen.List -> {
ListScreenTopAppBar(
onIconClicked = {
appViewModel.navigateToGeneralScreen()
navController.navigateUp()
}
)
}
AppScreen.Details -> {
DetailsScreenTopAppBar(
onIconClicked = {
appViewModel.navigateToListScreen()
navController.navigateUp()
}
)
}
}
}
AppContentType.Two -> {
when (appUiState.value.currentScreen) {
AppScreen.General -> {
GeneralScreenTopAppBar()
}
else -> {
DetailsScreenTopAppBar(
onIconClicked = {
appViewModel.navigateToGeneralScreen()
navController.navigateUp()
}
)
}
}
}
AppContentType.Three -> {
GeneralScreenTopAppBar()
}
}
},
modifier = modifier
.fillMaxSize()
) { innerPadding ->
NavHost(
navController = navController,
startDestination = AppScreen.General.name,
enterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(durationMillis = 300, easing = LinearEasing)
)
},
exitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Left,
animationSpec = tween(durationMillis = 300, easing = LinearEasing)
)
},
popEnterTransition = {
slideIntoContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(durationMillis = 300, easing = LinearEasing)
)
},
popExitTransition = {
slideOutOfContainer(
towards = AnimatedContentTransitionScope.SlideDirection.Right,
animationSpec = tween(durationMillis = 300, easing = LinearEasing)
)
},
modifier = Modifier
.padding(innerPadding)
) {
when (contentType) {
AppContentType.One -> {
composable(route = AppScreen.General.name) {
appViewModel.navigateToGeneralScreen()
Column(
modifier = Modifier
.fillMaxSize()
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.padding(dimensionResource(id = R.dimen.padding_medium))
) {
RandomInformationCard()
Spacer(
modifier = Modifier
.height(dimensionResource(id = R.dimen.padding_medium))
)
GeneralScreenCard(
appViewModel = appViewModel,
onCardClicked = {
appViewModel.updateCurrentCity(city = it)
appViewModel.updateCurrentMonument(monument = appUiState.value.currentCity.monumentsList[0])
navController.navigate(route = AppScreen.List.name)
}
)
}
}
}
composable(route = AppScreen.List.name) {
appViewModel.navigateToListScreen()
Column(
modifier = Modifier
.fillMaxSize()
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.padding(dimensionResource(id = R.dimen.padding_medium))
) {
RandomInformationCard()
Spacer(
modifier = Modifier
.height(dimensionResource(id = R.dimen.padding_medium))
)
ListScreenCard(
appViewModel = appViewModel,
onCardClicked = {
appViewModel.updateCurrentMonument(monument = it)
navController.navigate(route = AppScreen.Details.name)
}
)
}
}
}
composable(route = AppScreen.Details.name) {
appViewModel.navigateToDetailsScreen()
Column(
modifier = Modifier
.fillMaxSize()
) {
LazyColumn(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
item {
DetailsScreenCard(
appViewModel = appViewModel,
modifier = Modifier
.padding(dimensionResource(id = R.dimen.padding_medium))
)
}
}
}
}
}
AppContentType.Two -> {
composable(route = AppScreen.General.name) {
appViewModel.navigateToGeneralScreen()
Column(
modifier = Modifier
.fillMaxSize()
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.padding(dimensionResource(id = R.dimen.padding_medium))
) {
RandomInformationCard()
Spacer(
modifier = Modifier
.height(dimensionResource(id = R.dimen.padding_medium))
)
Row {
GeneralScreenCard(
appViewModel = appViewModel,
onCardClicked = {
appViewModel.updateCurrentCity(city = it)
appViewModel.updateCurrentMonument(monument = appUiState.value.currentCity.monumentsList[0])
},
modifier = Modifier
.weight(1f)
)
Spacer(
modifier = Modifier
.width(dimensionResource(id = R.dimen.padding_medium))
)
ListScreenCard(
appViewModel = appViewModel,
onCardClicked = {
appViewModel.updateCurrentMonument(monument = it)
navController.navigate(route = AppScreen.Details.name)
},
modifier = Modifier
.weight(1f)
)
}
}
}
}
composable(route = AppScreen.Details.name) {
appViewModel.navigateToDetailsScreen()
Column(
modifier = Modifier
.fillMaxSize()
) {
LazyColumn(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
item {
DetailsScreenCard(
appViewModel = appViewModel,
modifier = Modifier
.padding(dimensionResource(id = R.dimen.padding_medium))
)
}
}
}
}
}
AppContentType.Three -> {
composable(route = AppScreen.General.name) {
appViewModel.navigateToGeneralScreen()
Column(
modifier = Modifier
.fillMaxSize()
) {
Row {
Column(
modifier = Modifier
.weight(1f)
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.padding(
start = dimensionResource(id = R.dimen.padding_medium),
top = dimensionResource(id = R.dimen.padding_medium),
bottom = dimensionResource(id = R.dimen.padding_medium)
)
) {
RandomInformationCard()
Spacer(
modifier = Modifier
.height(dimensionResource(id = R.dimen.padding_medium))
)
Row {
GeneralScreenCard(
appViewModel = appViewModel,
onCardClicked = {
appViewModel.updateCurrentCity(city = it)
appViewModel.updateCurrentMonument(monument = appUiState.value.currentCity.monumentsList[0])
},
modifier = Modifier
.weight(1f)
)
Spacer(
modifier = Modifier
.width(dimensionResource(id = R.dimen.padding_medium))
)
ListScreenCard(
appViewModel = appViewModel,
onCardClicked = {
appViewModel.updateCurrentMonument(monument = it)
},
modifier = Modifier
.weight(2f)
)
}
}
}
LazyColumn(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.weight(1f)
) {
item {
DetailsScreenCard(
appViewModel = appViewModel,
modifier = Modifier
.padding(dimensionResource(id = R.dimen.padding_medium))
)
}
}
}
}
}
}
}
}
}
}
@Composable
fun RandomInformationCard(
modifier: Modifier = Modifier
) {
Card(
shape = RoundedCornerShape(dimensionResource(id = R.dimen.padding_large)),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.tertiaryContainer
),
modifier = modifier
.fillMaxWidth()
) {
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(dimensionResource(id = R.dimen.padding_small))
) {
Icon(
painter = painterResource(id = R.drawable.light_bulb),
contentDescription = null,
tint = MaterialTheme.colorScheme.onTertiaryContainer
)
Spacer(
modifier = Modifier
.width(dimensionResource(id = R.dimen.padding_small))
)
Text(
text = stringResource(id = LocalDataProvider.getInformation().random()),
style = MaterialTheme.typography.bodyMedium
)
}
}
} | 0 | Kotlin | 0 | 0 | e8bfc63afe6264eb83428f23ba108a36bea0812b | 18,232 | VisitAMonument | MIT License |
feature_audiobook_enhance_details/src/test/java/com/allsoftdroid/audiobook/feature/feature_audiobook_enhance_details/utils/BestBookDetailsParserTest.kt | pravinyo | 209,936,085 | false | null | package com.allsoftdroid.audiobook.feature.feature_audiobook_enhance_details.utils
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.Matchers.not
import org.junit.Assert
import org.junit.Test
class BestBookDetailsParserTest {
private val systemUnderTest = BestBookDetailsParser()
private val responsePath = "response.html"
private val noResponse = "noResult.html"
@Test
fun getListOfWebDocuments_nonEmpty_returnsList() {
//Arrange
val htmlResponse:String = getResponse(isFound = true)
//Act
val result = systemUnderTest.getList(htmlResponse)
//Assert
Assert.assertThat(result.size, not(0))
}
@Test
fun getListOfWebDocuments_Empty_returnsList() {
//Arrange
val htmlResponse:String = getResponse(isFound = false)
//Act
val result = systemUnderTest.getList(htmlResponse)
//Assert
Assert.assertThat(result.size,`is`(0))
}
@Test
fun getListWithRanks_returnHighRankItem() {
//Arrange
val htmlResponse:String = getResponse(isFound = true)
//Act
val result = systemUnderTest.getList(htmlResponse)
val ranks = systemUnderTest.getListWithRanks(result,"poem","Frank Oliver CALL (1878 - 1956)")
//Assert
Assert.assertThat(ranks.size, not(0))
}
@Test
fun getListWithRanks_returnEmpty() {
//Arrange
val htmlResponse:String = getResponse(isFound = false)
//Act
val result = systemUnderTest.getList(htmlResponse)
val ranks = systemUnderTest.getListWithRanks(result,"poem","Frank Oliver CALL (1878 - 1956)")
//Assert
Assert.assertThat(ranks.size, `is`(0))
}
private fun getResponse(isFound:Boolean):String{
return if (isFound) getHtmlResponse(responsePath) else getHtmlResponse(noResponse)
}
private fun getHtmlResponse(path:String): String {
val response = ClassLoader.getSystemResource(path)
return response.readText(Charsets.UTF_8)
}
} | 3 | null | 4 | 12 | 8358f69c0cf8dbde18904b0c3a304ec89b518c9b | 2,046 | AudioBook | MIT License |
features/home/src/test/java/com/example/movieapp/home/redux/HomeViewModelTest.kt | Ahnset | 539,038,324 | false | {"Kotlin": 138435} | package com.example.movieapp.home.redux
import io.mockk.coVerify
import io.mockk.mockk
import io.mockk.verify
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import okhttp3.OkHttpClient
import org.junit.After
import org.junit.Before
import org.junit.Test
@ExperimentalCoroutinesApi
class HomeViewModelTest {
private val stateMachine: HomeStateMachine = mockk(relaxed = true)
private val client: OkHttpClient = mockk(relaxed = true)
private val viewModel = HomeViewModel(stateMachine, client)
@Before
fun setup() {
Dispatchers.setMain(UnconfinedTestDispatcher())
}
@Test
fun `should call stateMachine dispatch() when start() is invoked`() {
runTest {
// Arrange
val action = HomeAction.GetHomeCatalogs
// Act
viewModel.start()
// Assert
coVerify(exactly = 1) { stateMachine.dispatch(action) }
}
}
@Test
fun `should evict cache when retry() is invoked`() {
runTest {
// Arrange
// Act
viewModel.retry()
// Assert
verify(exactly = 1) { client.cache?.evictAll() }
}
}
@After
fun teardown() {
Dispatchers.resetMain()
}
}
| 0 | Kotlin | 2 | 3 | a5ddc921f8f4df80cc13f17284015086fe6112b0 | 1,484 | movieapp | Apache License 2.0 |
zircon.core/src/main/kotlin/org/codetome/zircon/api/behavior/DrawSurface.kt | opencollective | 119,803,967 | false | null | package org.codetome.zircon.api.behavior
import org.codetome.zircon.api.Position
import org.codetome.zircon.api.TextCharacter
import org.codetome.zircon.api.util.Maybe
/**
* Represents an object which can be drawn upon.
* A [DrawSurface] is the most basic interface for all drawable surfaces
* which exposes simple get and set functions for getting and setting
* [TextCharacter]s.
*/
interface DrawSurface : Boundable {
/**
* Returns the character stored at a particular position on this [DrawSurface].
* Returns an empty [Maybe] if no [TextCharacter] is present at the given [Position].
*/
fun getCharacterAt(position: Position): Maybe<TextCharacter>
/**
* Sets the character at a specific position in the [DrawSurface] to a particular [TextCharacter].
* If the position is outside of the [DrawSurface]'s size, this method has no effect.
* Note that if this [DrawSurface] already has the given [TextCharacter] on the supplied [Position]
* nothing will change and this method will return `false`.
*
* @return true if the character was set, false if the position is outside of the [DrawSurface]
* or if no change happened.
*/
fun setCharacterAt(position: Position, character: TextCharacter): Boolean
/**
* Sets the character at a specific position in the [DrawSurface] to a particular [TextCharacter].
* If the position is outside of the [DrawSurface]'s size, this method has no effect.
* **Note that** this method will use the style information if the [DrawSurface] implements
* [org.codetome.zircon.api.graphics.StyleSet].
*
* If not it will use [org.codetome.zircon.api.TextCharacter.defaultCharacter]
* when it sets the given `character` as a [TextCharacter].
*
* @return true if the character was set, false if the position is outside of the [DrawSurface]
* or if no change happened.
*/
fun setCharacterAt(position: Position, character: Char): Boolean
/**
* Draws a [Drawable] onto this [DrawSurface]. If the destination [DrawSurface] is larger than
* this [Drawable], the areas outside of the area that is written to will be untouched.
* @param offset the starting position of the drawing relative to the [DrawSurface]'s top left corner.
*/
fun draw(drawable: Drawable,
offset: Position = Position.topLeftCorner())
}
| 0 | null | 1 | 1 | 3c1cd8aa4b6ddcbc39b9873c54ac64e3ec6cda4d | 2,408 | zircon | MIT License |
server/nlw-impulse-return/src/main/kotlin/server/impulse/com/nextlevelweek/Application.kt | Henrique-Santos-da-Silva | 533,898,807 | false | null | package server.impulse.com.nextlevelweek
import com.typesafe.config.ConfigFactory
import io.ktor.server.application.*
import io.ktor.server.config.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import kotlinx.coroutines.runBlocking
import server.impulse.com.nextlevelweek.database.DatabaseConfig
import server.impulse.com.nextlevelweek.plugins.*
import server.impulse.com.nextlevelweek.repositories.FeedbackRepositoryImpl
import server.impulse.com.nextlevelweek.services.sendmail.SendMailImpl
fun main(args: Array<String>) {
embeddedServer(Netty, environment = applicationEngineEnvironment {
config = HoconApplicationConfig(ConfigFactory.load())
connector {
port = System.getenv("PORT")?.toInt() ?: 8080
host = "0.0.0.0"
}
}).start(true)
}
@Suppress("unused") // application.conf references the main function. This annotation prevents the IDE from marking it as unused.
fun Application.module() {
runBlocking {
DatabaseConfig.apply {
openDatabaseConnection(environment.config)
createSchemas()
}
}
val feedbackRepository = FeedbackRepositoryImpl()
val sendMail = SendMailImpl()
configureHTTP()
configureMonitoring()
configureSerialization()
configureRouting(feedbackRepository, sendMail)
}
| 0 | Kotlin | 0 | 1 | ceef8fd5803e8a88f75c7898cd435a6822562cc7 | 1,337 | nlw-return-impulse-kotlin | MIT License |
core/domain/src/main/kotlin/org/bmsk/domain/repository/UserRepository.kt | CaZaIt | 594,701,085 | false | null | package org.bmsk.domain.repository
import kotlinx.coroutines.flow.Flow
import org.bmsk.domain.DomainResult
import org.bmsk.domain.model.SignInInfo
import org.bmsk.domain.model.SignUpInfo
import org.cazait.model.local.UserPreference
interface UserRepository {
suspend fun getCurrentUser(): Flow<UserPreference>
suspend fun signIn(loginId: String, password: String): Flow<DomainResult<SignInInfo>>
suspend fun signUp(loginId: String, password: String, nickname: String): Flow<DomainResult<SignUpInfo>>
suspend fun refreshToken(): Flow<DomainResult<String>>
suspend fun isNicknameDup(nickname: String): Flow<DomainResult<Boolean>>
suspend fun isEmailDup(email: String): Flow<DomainResult<Boolean>>
suspend fun saveSignInInfo(signInInfo: SignInInfo)
} | 2 | Kotlin | 0 | 0 | 31b6496d1e028fe002c146319333b3f795e4c1c3 | 779 | CaZaIt-Android-Admin | Apache License 2.0 |
build-logic/src/test/kotlin/me/khol/ChangeNotesTest.kt | Antimonit | 304,047,993 | false | {"Kotlin": 35448, "Lex": 889} | package me.khol
import org.junit.jupiter.api.Test
import strikt.api.expectThat
import strikt.assertions.isEqualTo
import java.time.LocalDate
import java.time.Month
internal class ChangeNotesTest {
@Test
fun toHtml() {
expectThat(
ChangeNotes(
releases = listOf(
Release(
version = SemVer(1, 1, 0),
date = LocalDate.of(2020, Month.NOVEMBER, 2),
notes = listOf(
"Note one.",
)
),
Release(
version = SemVer(1, 0, 1),
date = LocalDate.of(2020, Month.OCTOBER, 21),
notes = listOf(
"Note one.",
)
),
Release(
version = SemVer(1, 0, 0),
date = LocalDate.of(2020, Month.OCTOBER, 14),
notes = listOf(
"Note one.",
"Note two.",
"Note three.",
)
)
)
)
).get(ChangeNotes::toHtml).isEqualTo(
"""
|<b>1.1.0 (2020-11-02)</b>
|<ul>
| <li>Note one.</li>
|</ul>
|<b>1.0.1 (2020-10-21)</b>
|<ul>
| <li>Note one.</li>
|</ul>
|<b>1.0.0 (2020-10-14)</b>
|<ul>
| <li>Note one.</li>
| <li>Note two.</li>
| <li>Note three.</li>
|</ul>
|""".trimMargin()
)
}
}
| 6 | Kotlin | 1 | 5 | 0773550600018d9bb1c9126021d31354014168e5 | 1,786 | Lowlighting | Apache License 2.0 |
mocha/src/jsMain/kotlin/mocha/mocha/reporters/Base.kt | lppedd | 761,812,661 | false | {"Kotlin": 1887051} | @file:JsModule("mocha")
package mocha.mocha.reporters
import mocha.mocha.MochaOptions
import mocha.mocha.Runner
import mocha.mocha.Stats
import mocha.mocha.Test
/**
* Initialize a new `Base` reporter.
*
* All other reporters generally inherit from this reporter, providing stats such as test duration,
* number of tests passed / failed, etc.
*
* See https://mochajs.org/api/Mocha.reporters.Base.html
*/
open external class Base {
constructor(runner: Runner, options: MochaOptions<Any?> = definedExternally)
/**
* Test run statistics
*/
var stats: Stats
/**
* Test failures
*/
var failures: Array<Test>
/**
* The configured runner
*/
var runner: Runner
/**
* Output common epilogue used by many of the bundled reporters.
*
* See https://mochajs.org/api/Mocha.reporters.Base.html#.Base#epilogue
*/
fun epilogue()
open fun done(
failures: Int,
fn: (failures: Int) -> Unit = definedExternally,
)
}
| 0 | Kotlin | 0 | 3 | 0f493d3051afa3de2016e5425a708c7a9ed6699a | 969 | kotlin-externals | MIT License |
backend/src/jvmMain/kotlin/com/monkopedia/konstructor/PathController.kt | Monkopedia | 418,215,448 | false | {"Kotlin": 514602, "JavaScript": 159882, "HTML": 1015} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.monkopedia.konstructor
import java.io.File
class PathController private constructor(private val config: Config) {
data class Paths(
val workspaceId: String,
val konstructionId: String,
val workspaceDir: File,
val infoFile: File,
val compileResultFile: File,
val compileOutput: File,
val renderResultFile: File,
val renderOutput: File,
val contentFile: File,
val kotlinFile: File,
val cacheDir: File,
)
operator fun get(workspaceId: String, id: String): Paths {
val workspaceDir = File(config.dataDir, workspaceId)
val scriptDir = File(workspaceDir, id).also { it.mkdirs() }
return Paths(
workspaceId = workspaceId,
konstructionId = id,
workspaceDir = File(config.dataDir, workspaceId),
infoFile = File(scriptDir, "info.json"),
compileResultFile = File(scriptDir, "compile.json"),
compileOutput = File(scriptDir, "out"),
renderResultFile = File(scriptDir, "result.json"),
renderOutput = File(scriptDir, "renders"),
contentFile = File(scriptDir, "content.csgs"),
kotlinFile = File(scriptDir, "content.kt"),
cacheDir = File(scriptDir, "cacheDir")
)
}
companion object : (Config) -> PathController {
private val managers = mutableMapOf<Config, PathController>()
override fun invoke(config: Config): PathController {
synchronized(managers) {
return managers.getOrPut(config) {
PathController(config)
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 553817a530a5e60913cfa76c7e45c8e3a247b0d3 | 2,293 | Konstructor | Apache License 2.0 |
src/main/java/de/byjoker/myjfql/database/DatabaseRepresentation.kt | joker-games | 311,405,709 | false | {"Maven POM": 1, "Dockerfile": 1, "Text": 1, "Ignore List": 1, "Markdown": 1, "YAML": 1, "Kotlin": 49, "Java": 57} | package de.byjoker.myjfql.database
data class DatabaseRepresentation(val id: String, val name: String, val tables: List<String>, val type: DatabaseType) {
constructor(database: Database) : this(
database.id,
database.name,
database.tables.map { table -> table.name },
database.type
)
}
| 1 | null | 1 | 1 | 7bbd8e77fef477fe24b7edd1bf67a88cb6651287 | 328 | MyJFQL | MIT License |
app/src/main/java/com/example/picsolver/chatgptfiles/response/ChatRequest.kt | samrudha01codespace | 766,197,634 | false | {"Kotlin": 11951} | package com.example.picsolver.chatgptfiles.response
import com.samrudhasolutions.bolo.response.Message
data class ChatRequest(
val messages: List<Message>,
val model: String
) | 0 | Kotlin | 0 | 0 | 70fa2786dc5c0c3822cc8006c6d3ecd4d279c668 | 185 | PicSolver | MIT License |
src/main/kotlin/connectfour/ConnectFour.kt | joseluisgs | 444,960,273 | false | null | package connectfour
fun main() {
println("Connect Four")
println("First player's name: ")
val player1 = readln()
println("Second player's name: ")
val player2 = readln()
val (rows, columns) = analyzeDimensions()
println("$player1 VS $player2")
println("$rows X $columns board")
}
fun analyzeDimensions(): Pair<Int, Int> {
var dim = Pair(0, 0)
do {
println("Set the board dimensions (Rows x Columns)")
println("Press Enter for default (6 x 7)")
val dimensions = readln()
if (dimensions.trim().isEmpty()) {
return Pair(6, 7)
} else {
val split = dimensions.uppercase().split("X")
if (split.size != 2) {
println("Invalid input")
} else {
try {
val rows = split[0].trim().toInt()
val columns = split[1].trim().toInt()
if (rows !in (5..9))
println("Board rows should be from 5 to 9")
if (columns !in (5..9))
println("Board columns should be from 5 to 9")
if (rows in (5..9) && columns in (5..9)) {
dim = Pair(rows, columns)
}
} catch (e: NumberFormatException) {
println("Invalid input")
}
}
}
} while (dim == Pair(0, 0))
return dim
}
| 0 | Kotlin | 1 | 1 | a2e63006ab5024ce56193286a0eb2e0a767a1d8c | 1,467 | Kotlin-Academy | MIT License |
app/src/main/java/uk/ac/aber/dcs/cs31620/faa/model/CatDao.kt | chriswloftus | 317,273,374 | false | null | /**
* A DAO interface to allow access to the underlying Room
* database
* @author <NAME>
* @version 1
*/
package uk.ac.aber.dcs.cs31620.faa.model
import androidx.lifecycle.LiveData
import androidx.room.*
import java.time.LocalDateTime
@Dao
interface CatDao {
@Insert
suspend fun insertSingleCat(cat: Cat)
@Insert
suspend fun insertMultipleCats(catsList: List<Cat>)
@Update(onConflict = OnConflictStrategy.REPLACE)
suspend fun updateCat(cat: Cat)
@Delete
suspend fun deleteCat(cat: Cat)
@Query("DELETE FROM cats")
suspend fun deleteAll()
@Query("SELECT * FROM cats")
fun getAllCats(): LiveData<List<Cat>>
@Query(
"""SELECT * FROM cats WHERE breed = :breed AND
gender = :gender AND dob BETWEEN :startDate AND :endDate"""
)
fun getCats(
breed: String, gender: Gender, startDate: LocalDateTime,
endDate: LocalDateTime
): LiveData<List<Cat>>
@Query(
"SELECT * FROM cats WHERE breed = :breed"
)
fun getCatsByBreed(breed: String): LiveData<List<Cat>>
@Query(
"SELECT * FROM cats WHERE gender = :gender"
)
fun getCatsByGender(gender: Gender): LiveData<List<Cat>>
@Query("SELECT * FROM cats WHERE dob BETWEEN :startDate AND :endDate")
fun getCatsBornBetweenDates(
startDate: LocalDateTime,
endDate: LocalDateTime
): LiveData<List<Cat>>
@Query("SELECT * FROM cats WHERE breed = :breed AND gender = :gender")
fun getCatsByBreedAndGender(breed: String, gender: String): LiveData<List<Cat>>
@Query(
"""SELECT * FROM cats WHERE breed = :breed
AND dob BETWEEN :startDate AND :endDate"""
)
fun getCatsByBreedAndBornBetweenDates(
breed: String,
startDate: LocalDateTime,
endDate: LocalDateTime
): LiveData<List<Cat>>
@Query(
"""SELECT * FROM cats WHERE gender = :gender
AND dob BETWEEN :startDate AND :endDate"""
)
fun getCatsByGenderAndBornBetweenDates(
gender: Gender,
startDate: LocalDateTime,
endDate: LocalDateTime
): LiveData<List<Cat>>
@Query(
"""SELECT * FROM cats WHERE admission_date
BETWEEN :startDate AND :endDate"""
)
fun getCatsAdmittedBetweenDates(
startDate: LocalDateTime,
endDate: LocalDateTime
): LiveData<List<Cat>>
@Query(
"""SELECT * FROM cats WHERE admission_date
BETWEEN :startDate AND :endDate"""
)
fun getCatsAdmittedBetweenDatesSync(
startDate: LocalDateTime,
endDate: LocalDateTime
): List<Cat>
} | 0 | Kotlin | 1 | 0 | 998036392c254d72306185992fc06a6bc00f9502 | 2,639 | faaversion9 | MIT License |
app/src/main/java/com/example/gymtracker/ui/workoutScreen/CopiedExercisesAdapter.kt | EduDA92 | 595,563,950 | false | null | package com.example.gymtracker.ui.workoutScreen
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.gymtracker.data.entities.Exercise
import com.example.gymtracker.databinding.CopyExerciseItemBinding
class CopiedExercisesAdapter: ListAdapter<Exercise, CopiedExercisesAdapter.ExerciseViewHolder>(
DiffCallback) {
class ExerciseViewHolder(
private var binding: CopyExerciseItemBinding
) : RecyclerView.ViewHolder(binding.root) {
private var currentExercise: Exercise? = null
fun bind(exercise: Exercise) {
currentExercise = exercise
binding.copiedExercise.text = exercise.exercise_Name
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ExerciseViewHolder {
return ExerciseViewHolder(
CopyExerciseItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
override fun onBindViewHolder(holder: ExerciseViewHolder, position: Int) {
val current = getItem(position)
holder.bind(current)
}
companion object {
private val DiffCallback = object : DiffUtil.ItemCallback<Exercise>() {
override fun areItemsTheSame(oldItem: Exercise, newItem: Exercise): Boolean {
return oldItem.exercise_Id == newItem.exercise_Id
}
override fun areContentsTheSame(oldItem: Exercise, newItem: Exercise): Boolean {
return oldItem == newItem
}
}
}
} | 0 | Kotlin | 0 | 1 | bf47b0af7f4abf6502964d4b1cd966359a61215d | 1,739 | GymTracker | MIT License |
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/dotnet/commands/test/splitTests/SplitTestsNamesSaver.kt | JetBrains | 49,584,664 | false | null | package jetbrains.buildServer.dotnet.commands.test.splitTests
interface SplitTestsNamesSaver {
fun tryToSave(presumablyTestNameLine: String)
} | 14 | Kotlin | 21 | 88 | 2ff78dc1c479e37c865f8403dd56e57fe0e05556 | 147 | teamcity-dotnet-plugin | Apache License 2.0 |
sample/file-upload/desktop/src/jvmMain/kotlin/Main.kt | supabase-community | 495,084,592 | false | {"Kotlin": 901718} | import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import io.github.jan.supabase.common.App
import io.github.jan.supabase.common.UploadViewModel
import io.github.jan.supabase.common.di.initKoin
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
class RootComponent : KoinComponent {
val viewModel: UploadViewModel by inject()
}
fun main() {
initKoin()
val root = RootComponent()
application {
Window(onCloseRequest = ::exitApplication, title = "File Upload") {
App(root.viewModel)
}
}
}
| 11 | Kotlin | 37 | 395 | 52abcc3d5744ad2703afc40a9d1e6cae5b74b834 | 607 | supabase-kt | MIT License |
data/src/main/java/com/vuxur/khayyam/data/mapper/TranslationEntityMapper.kt | deghat-farhad | 518,348,997 | false | {"Kotlin": 188356} | package com.vuxur.khayyam.data.mapper
import com.vuxur.khayyam.data.entity.TranslationEntity
import com.vuxur.khayyam.domain.model.Translation
import javax.inject.Inject
class TranslationEntityMapper @Inject constructor() {
fun mapToDomain(translationEntityList: List<TranslationEntity>) =
translationEntityList.map { translationEntity ->
mapToDomain(translationEntity)
}
fun mapToDomain(translationEntity: TranslationEntity) =
Translation(
translationEntity.id,
translationEntity.languageTag,
translationEntity.translator,
)
fun mapToData(translation: Translation) =
TranslationEntity(
translation.id,
translation.languageTag,
translation.translator,
)
} | 19 | Kotlin | 0 | 0 | c53d2b56e05b6158d9a2cc58cddd5ea6d1212f93 | 803 | khayam | MIT License |
ui/src/commonMain/kotlin/kosh/ui/component/icon/ChainIcon.kt | niallkh | 855,100,709 | false | {"Kotlin": 1942525, "Swift": 25802} | package kosh.ui.component.icon
import androidx.compose.foundation.Image
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import com.seiko.imageloader.model.ImageRequest
import com.seiko.imageloader.rememberImagePainter
import kosh.domain.entities.NetworkEntity
import kosh.domain.models.ChainId
import kosh.domain.models.Uri
import kosh.domain.models.zeroChain
import kosh.ui.component.colors.chainColor
import kosh.ui.component.placeholder.placeholder
@Composable
fun ChainIcon(
network: NetworkEntity?,
modifier: Modifier = Modifier,
) {
ChainIcon(
modifier = modifier
.placeholder(visible = network == null),
chainId = network?.chainId ?: zeroChain,
symbol = network?.name ?: "Lorem",
icon = network?.icon
)
}
@Composable
fun ChainIcon(
chainId: ChainId,
symbol: String,
icon: Uri?,
modifier: Modifier = Modifier,
) {
val request = remember(icon) {
ImageRequest {
data(icon)
options { maxImageSize = 128 }
}
}
val symbolPainter = @Composable {
val colorScheme = chainColor(chainId, isSystemInDarkTheme())
rememberSymbolIconPainter(
symbol = symbol.substringBefore(" ").uppercase(),
color = colorScheme.primary,
containerColor = colorScheme.secondaryContainer,
)
}
Image(
modifier = modifier
.clip(MaterialTheme.shapes.extraSmall),
painter = rememberImagePainter(
request = request,
errorPainter = symbolPainter,
placeholderPainter = symbolPainter,
),
contentDescription = "ChainIcon",
contentScale = ContentScale.Crop,
)
}
| 0 | Kotlin | 0 | 3 | c08a9f32c0f12bf01eeb366c471b079923ac73ff | 1,977 | kosh | MIT License |
src/jsMain/kotlin/three/WebGLBindingStates.module_three.kt | baaahs | 174,897,412 | false | {"Kotlin": 3355751, "C": 1529197, "C++": 661364, "GLSL": 412680, "JavaScript": 62186, "HTML": 55088, "CMake": 30499, "CSS": 4340, "Shell": 2381, "Python": 1450} | @file:JsModule("three")
@file:JsNonModule
@file:Suppress("PackageDirectoryMismatch")
package three.js
import org.khronos.webgl.WebGLRenderingContext
open external class WebGLBindingStates(gl: WebGLRenderingContext, extensions: WebGLExtensions, attributes: WebGLAttributes, capabilities: WebGLCapabilities) {
open fun setup(obj: Object3D, material: Material, program: WebGLProgram, geometry: BufferGeometry, index: BufferAttribute)
open fun reset()
open fun resetDefaultState()
open fun dispose()
open fun releaseStatesOfGeometry()
open fun releaseStatesOfProgram()
open fun initAttributes()
open fun enableAttribute(attribute: Number)
open fun disableUnusedAttributes()
} | 113 | Kotlin | 12 | 40 | 4dd92e5859d743ed7186caa55409f676d6408c95 | 709 | sparklemotion | MIT License |
common/src/main/java/com/jun/template/common/base/BaseViewModel.kt | Jun19 | 609,916,083 | false | null | package com.jun.template.common.base
import androidx.lifecycle.ViewModel
abstract class BaseViewModel : ViewModel() | 0 | Kotlin | 0 | 6 | 76690da48f2440cfa5ecb4e2b200e1cf6407683e | 117 | ChatGPT-App | MIT License |
sherlock/src/main/java/com/quadible/sherlock/ViewHierarchyRecorder.kt | St4B | 257,113,166 | false | null | package com.quadible.sherlock
import android.app.Activity
import android.graphics.Bitmap
import android.graphics.Rect
import android.os.Handler
import android.view.PixelCopy
import java.io.File
import java.io.FileOutputStream
class ViewHierarchyRecorder : Recorder {
companion object {
private const val PNG_EXTENSION = ".png"
}
override fun record(screenshotName: String, activity: Activity, viewId: Int) {
val rootView = activity.window.decorView.rootView
val view = if (viewId > 0) {
rootView.findViewById(viewId)
} else {
rootView
}
val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
val startingPoints = IntArray(2)
view.getLocationOnScreen(startingPoints)
val rect = Rect(
startingPoints[0],
startingPoints[1],
startingPoints[0] + bitmap.width,
startingPoints[1] + bitmap.height
)
// We can use drawing cache to take screenshot for SDKs < 26.
// Possibly we'll add it to the future
PixelCopy.request(activity.window, rect, bitmap, { copyResult ->
if (copyResult == PixelCopy.SUCCESS) {
val screenshot =
File(activity.getExternalFilesDir(null), screenshotName + PNG_EXTENSION)
FileOutputStream(screenshot).use { out ->
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
}
}
}, Handler())
}
}
| 0 | Kotlin | 0 | 3 | 8a57c2da88899a82c6a456bf326a9f93455795ea | 1,552 | Sherlock | Apache License 2.0 |
lib/src/main/java/com/shencoder/mvvmkit/ext/ShapeDrawableExt.kt | shenbengit | 379,882,523 | false | {"Kotlin": 173545, "Java": 165679} | @file:JvmName("ShapeDrawableExt")
package com.shencoder.mvvmkit.ext
import android.graphics.Color
import android.graphics.Rect
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.GradientDrawable.Orientation
import android.os.Build
import androidx.annotation.ColorInt
import androidx.annotation.Px
/**
*
* @author Shenben
* @date 2024/10/12 20:05
* @description
* @since
*/
@JvmOverloads
fun shapeDrawable(
shape: Int = GradientDrawable.RECTANGLE,
@ColorInt solidColor: Int = Color.TRANSPARENT,
@Px cornerRadius: Float = 0.0f,
@Px cornerTopLeftRadius: Float = cornerRadius,
@Px cornerTopRightRadius: Float = cornerRadius,
@Px cornerBottomRightRadius: Float = cornerRadius,
@Px cornerBottomLeftRadius: Float = cornerRadius,
@Px strokeWidth: Int = 0,
@ColorInt strokeColor: Int = Color.TRANSPARENT,
@Px strokeDashWidth: Float = 0.0f,
@Px strokeDashGap: Float = 0.0f,
padding: Rect? = null,
@Px width: Int = -1,
@Px height: Int = -1
): GradientDrawable {
return GradientDrawable().also { drawable ->
drawable.shape = shape
drawable.setColor(solidColor)
if (shape == GradientDrawable.RECTANGLE) {
// 仅矩形有效
drawable.cornerRadius = cornerRadius
if (cornerTopLeftRadius != cornerRadius
|| cornerTopRightRadius != cornerRadius
|| cornerBottomRightRadius != cornerRadius
|| cornerBottomLeftRadius != cornerRadius
) {
drawable.cornerRadii = floatArrayOf(
cornerTopLeftRadius,
cornerTopLeftRadius,
cornerTopRightRadius,
cornerTopRightRadius,
cornerBottomRightRadius,
cornerBottomRightRadius,
cornerBottomLeftRadius,
cornerBottomLeftRadius
)
}
}
if (strokeWidth > 0 && strokeColor != Color.TRANSPARENT) {
drawable.setStroke(strokeWidth, strokeColor, strokeDashWidth, strokeDashGap)
}
if (padding != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
drawable.setPadding(padding.left, padding.top, padding.right, padding.bottom)
}
drawable.setSize(width, height)
}
}
@JvmOverloads
fun gradientDrawable(
shape: Int = GradientDrawable.RECTANGLE,
colors: IntArray? = null,
orientation: Orientation = Orientation.TOP_BOTTOM,
gradientType: Int = GradientDrawable.LINEAR_GRADIENT,
gradientCenterX: Float = 0.5f,
gradientCenterY: Float = 0.5f,
@Px gradientRadius: Float? = null,
@Px cornerRadius: Float = 0.0f,
@Px cornerTopLeftRadius: Float = cornerRadius,
@Px cornerTopRightRadius: Float = cornerRadius,
@Px cornerBottomRightRadius: Float = cornerRadius,
@Px cornerBottomLeftRadius: Float = cornerRadius,
@Px strokeWidth: Int = 0,
@ColorInt strokeColor: Int = Color.TRANSPARENT,
@Px strokeDashWidth: Float = 0.0f,
@Px strokeDashGap: Float = 0.0f,
padding: Rect? = null,
@Px width: Int = -1,
@Px height: Int = -1
): GradientDrawable {
return GradientDrawable().also { drawable ->
drawable.shape = shape
drawable.orientation = orientation
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val useCenter = colors?.size == 3
var offsets: FloatArray? = null
if (useCenter && gradientType == GradientDrawable.LINEAR_GRADIENT) {
offsets = FloatArray(3)
offsets[0] = 0.0f
// Since 0.5f is default value, try to take the one that isn't 0.5f
offsets[1] = if (gradientCenterX != 0.5f) gradientCenterX else gradientCenterY
offsets[2] = 1f
}
drawable.setColors(colors, offsets)
} else {
// Android 9及以下版本无法设置 offsets,gradientType == GradientDrawable.LINEAR_GRADIENT且需要兼容Android 9及以下版本时,需要使用xml
drawable.colors = colors
}
drawable.gradientType = gradientType
// gradientType != GradientDrawable.LINEAR_GRADIENT 时,无意义
drawable.setGradientCenter(gradientCenterX, gradientCenterY)
if (gradientType == GradientDrawable.RADIAL_GRADIENT && gradientRadius != null) {
drawable.gradientRadius = gradientRadius
}
if (shape == GradientDrawable.RECTANGLE) {
// 仅矩形有效
drawable.cornerRadius = cornerRadius
if (cornerTopLeftRadius != cornerRadius
|| cornerTopRightRadius != cornerRadius
|| cornerBottomRightRadius != cornerRadius
|| cornerBottomLeftRadius != cornerRadius
) {
drawable.cornerRadii = floatArrayOf(
cornerTopLeftRadius,
cornerTopLeftRadius,
cornerTopRightRadius,
cornerTopRightRadius,
cornerBottomRightRadius,
cornerBottomRightRadius,
cornerBottomLeftRadius,
cornerBottomLeftRadius
)
}
}
if (strokeWidth > 0 && strokeColor != Color.TRANSPARENT) {
drawable.setStroke(strokeWidth, strokeColor, strokeDashWidth, strokeDashGap)
}
if (padding != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
drawable.setPadding(padding.left, padding.top, padding.right, padding.bottom)
}
drawable.setSize(width, height)
}
} | 0 | Kotlin | 6 | 23 | bae1d602b636c0547482a3ba884b60b91351233a | 5,622 | MVVMKit | MIT License |
meistercharts-demos/meistercharts-demos/src/commonMain/kotlin/com/meistercharts/demo/descriptors/TweenDemoDescriptor.kt | Neckar-IT | 599,079,962 | false | null | /**
* Copyright 2023 Neckar IT GmbH, Mössingen, Germany
*
* 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.meistercharts.demo.descriptors
import com.meistercharts.algorithms.layers.AbstractLayer
import com.meistercharts.algorithms.layers.LayerPaintingContext
import com.meistercharts.algorithms.layers.LayerType
import com.meistercharts.algorithms.layers.addClearBackground
import com.meistercharts.algorithms.layers.interpolate
import com.meistercharts.algorithms.painter.Color
import com.meistercharts.animation.Easing
import com.meistercharts.canvas.animation.AnimationRepeatType
import com.meistercharts.canvas.animation.Tween
import com.meistercharts.demo.ChartingDemo
import com.meistercharts.demo.ChartingDemoDescriptor
import com.meistercharts.demo.DemoCategory
import com.meistercharts.demo.PredefinedConfiguration
import com.meistercharts.demo.configurableDouble
import com.meistercharts.demo.configurableEnum
import com.meistercharts.demo.configurableList
import com.meistercharts.demo.section
import com.meistercharts.model.Rectangle
import it.neckar.open.time.nowMillis
import it.neckar.open.unit.si.ms
import kotlin.math.max
import kotlin.reflect.KMutableProperty0
/**
*
*/
class TweenDemoDescriptor : ChartingDemoDescriptor<Nothing> {
override val name: String = "Tween"
override val category: DemoCategory = DemoCategory.Calculations
override fun createDemo(configuration: PredefinedConfiguration<Nothing>?): ChartingDemo {
return ChartingDemo {
meistercharts {
configure {
layers.addClearBackground()
val width = 200.0
val height = 200.0
val layer = object : AbstractLayer() {
var tweenX: Tween = Tween(nowMillis() + 500, 2800.0, Easing.inOutQuad, AnimationRepeatType.RepeatAutoReverse)
var tweenY: Tween = Tween(nowMillis(), 2000.0, Easing.inOutQuad, AnimationRepeatType.RepeatAutoReverse)
override val type: LayerType = LayerType.Content
override fun paint(paintingContext: LayerPaintingContext) {
val gc = paintingContext.gc
gc.translate(gc.width / 2.0 - width / 2.0, gc.height / 2.0 - height / 2.0)
gc.stroke(Color.blue)
gc.strokeRect(Rectangle(0.0, 0.0, width, height))
//draw the line
kotlin.run {
val maxDuration = max(tweenX.duration, tweenY.duration) * 8
val startTimeX = tweenX.startTime
@ms var time = startTimeX
while (time <= startTimeX + maxDuration) {
val x = width * tweenX.interpolate(time)
val y = width * tweenY.interpolate(time)
gc.fill(Color.lightgray)
gc.fillOvalCenter(x, y, 1.0, 1.0)
time += 10.0
}
}
//Paint the current position
val x = width * tweenX.interpolate(paintingContext)
val y = width * tweenY.interpolate(paintingContext)
gc.fill(Color.orangered)
gc.fillOvalCenter(x, y, 10.0, 10.0)
chartSupport.markAsDirty()
}
}
layers.addLayer(layer)
section("Tween X")
configureTween(layer::tweenX)
section("Tween Y")
configureTween(layer::tweenY)
}
}
}
}
private fun ChartingDemo.configureTween(tweenProperty: KMutableProperty0<Tween>) {
configurableDouble("Duration", tweenProperty.get().duration) {
max = 10_000.0
onChange {
tweenProperty.set(tweenProperty.get().withDuration(duration = it))
}
}
configurableEnum("Repeat Type", tweenProperty.get().repeatType, enumValues()) {
onChange {
tweenProperty.set(tweenProperty.get().withRepeatType(repeatType = it))
}
}
configurableList("Easing", availableEasings[0], availableEasings) {
onChange {
tweenProperty.set(tweenProperty.get().withEasing(it.easing))
}
converter {
it.description
}
}
declare {
button("Restart") {
tweenProperty.set(tweenProperty.get().copy(startTime = nowMillis()))
}
}
}
}
private fun Tween.withEasing(easing: Easing): Tween {
return this.copy(definition = definition.copy(interpolator = easing))
}
private fun Tween.withRepeatType(repeatType: AnimationRepeatType): Tween {
return this.copy(definition = definition.copy(repeatType = repeatType))
}
private fun Tween.withDuration(duration: Double): Tween {
return this.copy(definition = definition.copy(duration = duration))
}
| 0 | Kotlin | 0 | 4 | af73f0e09e3e7ac9437240e19974d0b1ebc2f93c | 5,143 | meistercharts | Apache License 2.0 |
app/src/main/java/com/kefasjwiryadi/bacaberita/domain/ArticleSearchResult.kt | kefasjwiryadi | 224,442,104 | false | null | package com.kefasjwiryadi.bacaberita.domain
data class ArticleSearchResult(
val query: String,
val articles: List<Article>,
val totalResult: Int,
val page: Int
) | 0 | Kotlin | 0 | 1 | 67a6476272da5e9ee322239049529d58f0e6f11c | 178 | android-baca-berita | MIT License |
kora-app-symbol-processor/src/main/kotlin/ru/tinkoff/kora/kora/app/ksp/interceptor/ComponentInterceptor.kt | kora-projects | 743,624,836 | false | null | package ru.tinkoff.kora.kora.app.ksp.interceptor
import com.google.devtools.ksp.symbol.KSType
import ru.tinkoff.kora.kora.app.ksp.component.ResolvedComponent
import ru.tinkoff.kora.kora.app.ksp.declaration.ComponentDeclaration
data class ComponentInterceptor(
val component: ResolvedComponent,
val declaration: ComponentDeclaration,
val interceptType: KSType
)
| 8 | null | 9 | 63 | bb7d906d3af0ae6f8c68f87327f010b66110f34f | 375 | kora | Apache License 2.0 |
app/src/main/java/vip/yazilim/p2g/android/ui/user/UserViewModelFactory.kt | yazilim-vip | 304,487,567 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 83, "XML": 101, "Java": 1} | package vip.yazilim.p2g.android.ui.user
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
/**
* @author mustafaarifsisman - 21.03.2020
* @contact <EMAIL>
*/
class UserViewModelFactory : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return modelClass.newInstance()
}
} | 1 | null | 1 | 1 | d52cc417e46ee9dab9da3b72de9cb3776043bf46 | 366 | p2g-android | Apache License 2.0 |
src/main/kotlin/org/cryptobiotic/eg/cli/RunCreateTestManifest.kt | JohnLCaron | 760,153,500 | false | {"Kotlin": 1137037} | package org.cryptobiotic.eg.cli
import io.github.oshai.kotlinlogging.KotlinLogging
import kotlinx.cli.ArgParser
import kotlinx.cli.ArgType
import kotlinx.cli.default
import kotlinx.cli.required
import org.cryptobiotic.eg.input.ManifestInputValidation
import org.cryptobiotic.eg.publish.makePublisher
import kotlin.system.exitProcess
/** Create Test Manifest CLI. */
class RunCreateTestManifest {
companion object {
private val logger = KotlinLogging.logger("RunCreateTestManifest")
@JvmStatic
fun main(args: Array<String>) {
val parser = ArgParser("RunCreateTestManifest")
val nstyles by parser.option(
ArgType.Int,
shortName = "nstyles",
description = "number of ballot styles"
).default(3)
val ncontests by parser.option(
ArgType.Int,
shortName = "ncontests",
description = "number of contests"
).required()
val nselections by parser.option(
ArgType.Int,
shortName = "nselections",
description = "number of selections per contest"
).required()
val outputType by parser.option(
ArgType.String,
shortName = "type",
description = "JSON or PROTO"
).default("JSON")
val outputDir by parser.option(
ArgType.String,
shortName = "out",
description = "Directory to write test manifest file"
).required()
val noexit by parser.option(
ArgType.Boolean,
shortName = "noexit",
description = "Dont call System.exit"
).default(false)
parser.parse(args)
println(
"RunCreateTestManifest starting\n" +
" nstyles= $nstyles\n" +
" ncontests= $ncontests\n" +
" nselections= $nselections\n" +
" outputType= $outputType\n" +
" output = $outputDir\n"
)
try {
val manifest = if (nstyles == 1) buildTestManifest(ncontests, nselections)
else buildTestManifest(nstyles, ncontests, nselections)
val validator = ManifestInputValidation(manifest)
val errs = validator.validate()
if (errs.hasErrors()) {
logger.error{"failed $errs"}
if (!noexit) exitProcess(1)
} else {
val publisher = makePublisher(outputDir, true)
publisher.writeManifest(manifest)
logger.info("ManifestInputValidation succeeded")
}
} catch (t: Throwable) {
logger.error { "Exception= ${t.message} ${t.stackTraceToString()}" }
if (!noexit) exitProcess(-1)
}
}
}
} | 15 | Kotlin | 0 | 0 | 81df4781125a132fda744e97d4e15a28f267f1a0 | 3,055 | egk-ec | MIT License |
subprojects/test-runner/plugins-configuration/src/main/kotlin/com/avito/android/plugins/configuration/BuildEnvResolver.kt | avito-tech | 230,265,582 | false | null | package com.avito.android.plugins.configuration
import com.avito.utils.gradle.EnvArgs
import org.gradle.api.provider.Provider
public class BuildEnvResolver(private val envArgs: Provider<EnvArgs>) {
public fun getBuildId(): String {
return envArgs.get().build.id.toString()
}
public fun getBuildType(): String {
return envArgs.get().build.type
}
}
| 10 | null | 50 | 414 | bc94abf5cbac32ac249a653457644a83b4b715bb | 383 | avito-android | MIT License |
Android/src/main/java/com/example/vocab/test/TestSpeechFragment.kt | Arduino13 | 599,629,871 | false | null | package com.example.vocab.test
import android.content.Intent
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.example.vocab.R
import com.example.vocab.databinding.FragmentTestSpeechBinding
import com.example.vocab.mediaUtils.AudioRecorder
import com.example.vocab.thirdParty.PyTorchNN
import com.example.vocab.thirdParty.Translator
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.File
import java.util.*
/**
* Tests pronunciation, doesn't work in reverse order, because it makes no sense
*/
class TestSpeechFragment : GenericTest<FragmentTestSpeechBinding>() {
override val maxWordLength: Int = 3
override val minWordLength: Int = -1
override val numberOfRequiredWords: Int = 1
var counter: Int = 0
var sentence: String? = null
val debug: Boolean = true
var blockRecord: Boolean = false
//prevzato z: https://gist.github.com/ademar111190/34d3de41308389a0d0d8
private fun levenshtein(lhs : CharSequence, rhs : CharSequence) : Int {
val lhsLength = lhs.length + 1
val rhsLength = rhs.length + 1
var cost = Array(lhsLength) { it }
var newCost = Array(lhsLength) { 0 }
for (i in 1..rhsLength-1) {
newCost[0] = i
for (j in 1..lhsLength-1) {
val match = if(lhs[j - 1] == rhs[i - 1]) 0 else 1
val costReplace = cost[j - 1] + match
val costInsert = cost[j] + 1
val costDelete = newCost[j - 1] + 1
newCost[j] = Math.min(Math.min(costInsert, costDelete), costReplace)
}
val swap = cost
cost = newCost
newCost = swap
}
return cost[lhsLength - 1]
}
override fun checkAndPost(): Result {
sentence?.let {
var colapseWordFrom = ""
var temp: Char = ' '
for (c in words[0].from) {
if (c != temp) {
colapseWordFrom += c
temp = c
}
}
val distance = levenshtein(sentence!!, colapseWordFrom.toLowerCase())
val netError: Float = words[0].from.length * 10 / 100f
return if (distance.toFloat() - netError > 2f) {
Result(false, words[0].from, words[0])
} else {
Result(true, words[0].from, words[0])
}
}
return Result(false, words[0].from, words[0])
}
/**
* Starts 3 second recording with evaluation using [PyTorchNN]
*/
private fun record(){
if(!blockRecord) {
binding.runRecording.setBackgroundColor(resources.getColor(R.color.red))
blockRecord = true
val record = AudioRecorder(3)
counter+=1
record.startRecording(counter) { data ->
sentence = PyTorchNN(requireContext()).recognizeSpeech(data)
if (debug) {
CoroutineScope(Dispatchers.Main).launch {
Toast.makeText(
requireContext(),
sentence,
Toast.LENGTH_LONG
).show()
}
}
blockRecord = false
binding.runRecording.setBackgroundColor(resources.getColor(R.color.green))
}
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentTestSpeechBinding.inflate(inflater, container, false)
binding.runRecording.setOnClickListener {
record()
}
binding.runRecording.setBackgroundColor(resources.getColor(R.color.green))
binding.wordToTest.text = words[0].from
val tts = TextToSpeech(context){}
binding.playAudio.setOnClickListener {
tts.language = Locale.US
tts.speak(words[0].from, TextToSpeech.QUEUE_ADD, null)
}
return binding.root
}
} | 0 | Kotlin | 0 | 0 | 5281c5b8281fd3cb06cf670dcaa7e6c858606179 | 4,332 | 3N | MIT License |
src/main/kotlin/no/nav/familie/historikk/domain/HistorikkinnslagRepository.kt | navikt | 357,866,301 | false | {"Kotlin": 44326, "Shell": 1568, "Dockerfile": 957} | package no.nav.familie.historikk.domain
import no.nav.familie.historikk.common.repository.InsertUpdateRepository
import no.nav.familie.historikk.common.repository.RepositoryInterface
import no.nav.familie.kontrakter.felles.Applikasjon
import java.util.UUID
interface HistorikkinnslagRepository : RepositoryInterface<Historikkinnslag, UUID>, InsertUpdateRepository<Historikkinnslag> {
fun findByBehandlingId(behandlingId: String): List<Historikkinnslag>
fun findByBehandlingIdAndApplikasjon(
behandlingId: String,
applikasjon: Applikasjon,
): List<Historikkinnslag>
}
| 0 | Kotlin | 0 | 0 | a1a4a00175147caf3274933b0c37432071ae0b91 | 598 | familie-historikk | MIT License |
tutorials/kotlin-se/se-syntax/src/main/kotlin/se/syntax/func/Practice.kt | Alice52 | 589,441,907 | false | {"Kotlin": 45101, "Java": 1287, "Shell": 362} | package se.syntax.func
class Practice
/**
* 1. private/open 等表示可见范围和是否 final
* 2. inline(不要在class内) | infix | tailrec: 内联 | 中缀 | 尾递归
* 3. fun <I, O>: 泛型
* 4. I.mApply(): 对 I 类型扩展出 mApply() 函数
* 5. T.() -> O | (T) -> R: 匿名函数内持有 this | 匿名函数内持有 it
* 6. return this 可以进行链式调用
*/
inline fun <I, O> I.mApply(lambda: I.(String) -> O): I {
lambda("hh") // 会在 I 内部执行, 且可以获取到 this
return this
}
class Context {
val name = "zack"
fun tip(str: String) {
println(str)
}
}
infix fun Context.apply(lambda: Context.(String) -> Unit): Context {
lambda(name)
return this
}
fun main() {
// 1. 定义复杂函数
"zack".mApply { println(this.capitalize() /*"zack".capitalize()*/) } // I:String, O:Unit
.mApply { this.capitalize() } // I:String, O:String
.mApply { println(it) } // I:String, O:Unit and hh
// 2.测试 Context 相关
Context().apply {
println(this.name) // zack
}.apply {
tip("second") // second
}.apply {
tip(name) // zack
}.apply {
tip(it) // --> name (zack)
}.apply({ it -> tip(it) }) // 传入函数, 且该函数的第一个桉树被当作调用tip的参数, 具体参数有 line-27 决定的
} | 14 | Kotlin | 0 | 0 | b67ef5d51574b6b93115818556834937841e4d66 | 1,156 | kotlin-tutorial | MIT License |
product/web3modal/src/main/kotlin/com/walletconnect/web3/modal/client/models/Exceptions.kt | WalletConnect | 435,951,419 | false | {"Kotlin": 2461647, "Java": 4366, "Shell": 1892} | package com.walletconnect.web3.modal.client.models
import com.walletconnect.android.internal.common.exception.WalletConnectException
class Web3ModelClientAlreadyInitializedException : WalletConnectException("Web3Modal already initialized")
class CoinbaseClientAlreadyInitializedException : WalletConnectException("Coinbase already initialized") | 78 | Kotlin | 70 | 197 | 743ff1e06def59a721a299a8e76c67e96b9441f6 | 346 | WalletConnectKotlinV2 | Apache License 2.0 |
framework/src/main/kotlin/com/chrynan/klutter/rendering/Overflow.kt | chRyNaN | 164,444,924 | false | null | package com.chrynan.klutter.rendering
enum class Overflow {
CLIP,
VISIBLE
} | 0 | Kotlin | 0 | 1 | 3a138f51a327924944fd86cbfb1804820b9c4691 | 85 | klutter | Apache License 2.0 |
test-solve/src/commonTest/kotlin/it/unibo/tuprolog/solve/exception/ResolutionExceptionTest.kt | tuProlog | 230,784,338 | false | null | package it.unibo.tuprolog.solve.exception
import it.unibo.tuprolog.solve.exception.testutils.TuPrologRuntimeExceptionUtils.aCause
import it.unibo.tuprolog.solve.exception.testutils.TuPrologRuntimeExceptionUtils.aContext
import it.unibo.tuprolog.solve.exception.testutils.TuPrologRuntimeExceptionUtils.aDifferentContext
import it.unibo.tuprolog.solve.exception.testutils.TuPrologRuntimeExceptionUtils.aMessage
import it.unibo.tuprolog.solve.exception.testutils.TuPrologRuntimeExceptionUtils.assertSameMessageCauseContext
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertSame
/**
* Test class for [ResolutionException]
*
* @author Enrico
*/
internal class ResolutionExceptionTest {
private val exception = ResolutionException(aMessage, aCause, aContext)
@Test
fun constructorInsertsMessageIfOnlyCauseSpecified() {
val exception = ResolutionException(aCause, aContext)
assertEquals(aCause.toString(), exception.message)
}
@Test
fun logicStackTraceAccessesContextCorrespondingField() {
assertSame(emptyList(), exception.logicStackTrace)
}
@Test
fun updateContextReturnsExceptionWithSameContentsButUpdatedContext() {
val toBeTested = exception.updateContext(aDifferentContext)
assertSameMessageCauseContext(aMessage, aCause, aDifferentContext, toBeTested)
}
}
| 92 | null | 14 | 93 | 3223ffc302e5da0efe2b254045fa1b6a1a122519 | 1,379 | 2p-kt | Apache License 2.0 |
src/main/kotlin/org/rust/cargo/project/model/AttachCargoProjectAction.kt | AtomicInteger | 141,130,701 | true | {"Kotlin": 2185663, "Rust": 76008, "Lex": 18854, "HTML": 9456, "Shell": 760, "Java": 586, "RenderScript": 318} | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.project.model
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.fileChooser.FileChooserFactory
import com.intellij.openapi.ui.Messages
import org.rust.cargo.toolchain.RustToolchain
import org.rust.openapiext.pathAsPath
class AttachCargoProjectAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val descriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor()
.withFileFilter { it.name == RustToolchain.CARGO_TOML }
.withTitle("Select Cargo.toml")
val chooser = FileChooserFactory.getInstance().createFileChooser(descriptor, project, null)
val file = chooser.choose(project).singleOrNull() ?: return
if (!project.cargoProjects.attachCargoProject(file.pathAsPath)) {
Messages.showErrorDialog(
project,
"This Cargo package is already a part of an attached workspace.",
"Unable to attach Cargo project"
)
}
}
}
| 0 | Kotlin | 0 | 0 | c643de560bf543babb42b70d52ffe818b494d21c | 1,315 | intellij-rust | MIT License |
src/test/java/src/ii_collections/_18_Sort.kt | vicboma1 | 45,669,265 | false | null | package ii_collections
import ii_collections.data.shop
import ii_collections.data.sortedCustomers
import junit.framework.Assert
import org.junit.Test
class _18_Sort {
@Test fun testGetCustomersSortedByNumberOfOrders() {
Assert.assertEquals(sortedCustomers, shop.getCustomersSortedByNumberOfOrders())
}
}
| 3 | Kotlin | 27 | 123 | 7f0b16cc5cb38a24f3dae3d65b7978e00a1bbe9b | 322 | Kotlin-Koans | MIT License |
androidApp/src/main/java/com/somabits/spanish/android/menu/AndroidCardMenu.kt | chiljamgossow | 581,781,635 | false | null | package com.somabits.spanish.android.menu
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.MoreVert
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import com.somabits.spanish.android.component.MenuItem
import com.somabits.spanish.ui.menu.Menu
import com.somabits.spanish.ui.menu.MenuItemData
open class AndroidCardMenu(
val items: List<MenuItemData>
) : Menu {
@Composable
override fun Build(
modifier: Modifier,
) {
var expanded by remember { mutableStateOf(false) }
Box(
modifier = modifier.wrapContentSize(Alignment.TopEnd)
) {
IconButton(onClick = { expanded = true }) {
Icon(
Icons.Rounded.MoreVert,
contentDescription = null
)
}
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
items.forEach {
it.imageVector?.let { image ->
MenuItem(
stringResource = it.stringResource,
imageVector = image,
onClick = {
expanded = false
it.onClick()
},
)
}
it.painter?.let { painter ->
MenuItem(
stringResource = it.stringResource,
painter = painter,
onClick = {
expanded = false
it.onClick()
},
)
}
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | d6043027b2af34708a0a4883a0803696d5499260 | 2,346 | Spanish | MIT License |
src/commonMain/kotlin/data/team/AvatarTeamUpdateNotify.kt | Hartie95 | 642,871,918 | false | {"Kotlin": 301622} | package data.team
import annotations.AddedIn
import org.anime_game_servers.annotations.CommandType
import org.anime_game_servers.annotations.ProtoCommand
import messages.VERSION.V3_0_0
import messages.VERSION.VCB2
@AddedIn(VCB2)
@ProtoCommand(CommandType.NOTIFY)
internal interface AvatarTeamUpdateNotify {
var avatarTeamMap: Map<Int, AvatarTeam>
var tempAvatarGuidList: List<Long>
}
| 0 | Kotlin | 2 | 5 | cb458b49dc9618e3826b890689becc0f12585998 | 395 | anime-game-multi-proto | MIT License |
jps-plugin/testData/incremental/pureKotlin/inlineFunctionUsageAdded/foo.kt | JakeWharton | 99,388,807 | true | null | class A {
inline fun foo(f: () -> Unit) {
f()
}
}
| 179 | Kotlin | 5640 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 66 | kotlin | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.