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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/client/kotlin/fyi/fyw/monutils/gui/RedirectedMessageScreen.kt | FYWinds | 796,139,959 | false | {"Kotlin": 75633, "Java": 4802, "Python": 3777} | package fyi.fyw.monutils.gui
import com.mojang.blaze3d.systems.RenderSystem
import net.minecraft.client.MinecraftClient
import net.minecraft.client.gui.DrawableHelper
import net.minecraft.client.util.math.MatrixStack
import net.minecraft.text.Text
object RedirectedMessageScreen {
val messages: MutableList<Text> = mutableListOf(Text.of("Hello World!"))
private val client: MinecraftClient = MinecraftClient.getInstance()
private val textRenderer = client.textRenderer
private val x = 0;
private val y = 0;
private val width = 100; // TODO adapt scale
private val height = 100;
fun render(matrices: MatrixStack) {
// TODO config disable
matrices.push()
matrices.translate(x.toDouble(), y.toDouble(), 0.0)
RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0F);
RenderSystem.enableBlend();
RenderSystem.defaultBlendFunc();
renderBackground(matrices)
renderMessages(matrices)
matrices.pop()
}
fun renderBackground(matrices: MatrixStack) {
// TODO
DrawableHelper.fill(
matrices,
0,
0,
width,
height,
client.options.getTextBackgroundColor(client.options.chatOpacity.value.toFloat())
);
}
fun renderMessages(matrices: MatrixStack) {
// TODO
}
} | 0 | Kotlin | 0 | 0 | 3cd0e7fca4b91398b169972281d3ad5226b249fa | 1,373 | MonutilsFabric | MIT License |
later/core/src/commonMain/kotlin/koncurrent/later/LaterBaseUtils.kt | aSoft-Ltd | 521,074,922 | false | {"Kotlin": 89425, "Java": 1554, "JavaScript": 348} | @file:Suppress(
"NO_ACTUAL_FOR_EXPECT", // removing this will make the K2/JVM not compile,
"EXPECT_ACTUAL_MISMATCH", // removing this will make the K2/JVM not compile
)
package koncurrent.later
import koncurrent.Executor
import koncurrent.Later
import kase.Result
expect fun <T, R> Later<T>.then(executor: Executor, onResolved: (T) -> R): Later<R>
expect fun <T, R> Later<T>.then(onResolved: (T) -> R): Later<R>
expect fun <T, R> Later<T>.andThen(executor: Executor, onResolved: (T) -> Later<R>): Later<R>
expect fun <T, R> Later<T>.andThen(onResolved: (T) -> Later<R>): Later<R>
expect fun <T> Later<T>.catch(executor: Executor, recover: (Throwable) -> T): Later<T>
expect fun <T> Later<T>.catch(recover: (Throwable) -> T): Later<T>
expect fun <T> Later<T>.finally(executor: Executor, cleanUp: (state: Result<T>) -> Unit): Later<T>
expect fun <T> Later<T>.finally(cleanUp: (state: Result<T>) -> Unit): Later<T> | 0 | Kotlin | 0 | 2 | 1344b08431b8a8a8bbe28987c58efe9f45a21c6d | 924 | koncurrent | MIT License |
app/src/main/java/com/application/archelon/screens/login/LoginViewModel.kt | danoc93 | 451,251,171 | false | {"Kotlin": 104143} | package com.application.archelon.screens.login
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.application.archelon.repositories.LoginState
import com.application.archelon.repositories.SessionRepository
import com.application.archelon.system.SharedPrefs
import kotlinx.coroutines.*
class LoginViewModel : ViewModel() {
private val loginState = MutableLiveData<LoginState>()
private val isLoginInProgress = MutableLiveData<Boolean>()
private var viewModelJob = Job()
private val coroutineScope = CoroutineScope(viewModelJob + Dispatchers.Main)
init {
loginState.value = LoginState.NotLoggedIn;
isLoginInProgress.value = false;
}
fun getLoginState(): MutableLiveData<LoginState> {
return loginState
}
fun getIsLoginInProgress(): MutableLiveData<Boolean> {
return isLoginInProgress
}
fun attemptLogin(username: String, password: String, sharedPreferences: SharedPrefs) {
isLoginInProgress.value = true;
coroutineScope.launch {
val resultingLoginState =
SessionRepository.loginUser(
username,
password,
sharedPreferences
);
loginState.value = resultingLoginState;
isLoginInProgress.value = false;
}
}
fun attemptToFindActiveSession(sharedPreferences: SharedPrefs) {
val sessionFound = SessionRepository.getActiveSessionFromPreferences(sharedPreferences);
if (sessionFound != null) {
loginState.value = LoginState.SuccessExistingSession
}
}
override fun onCleared() {
viewModelJob.cancel()
super.onCleared()
}
} | 0 | Kotlin | 0 | 0 | 682cacd8fa5280241e58cb68d8ad5c8df2f02ab8 | 1,757 | archelonpoc | MIT License |
app/src/main/java/com/umc/history/AuthService.kt | duck-positive | 582,929,737 | false | null | package com.umc.history
import android.util.Log
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class AuthService {
private lateinit var existView: ExistView
private lateinit var authView: AuthView
fun setExistView(existView: ExistView){
this.existView = existView
}
fun setAuthView(authView: AuthView){
this.authView = authView
}
fun nickNameExist(nickname: String?){
val retrofit = Retrofit.Builder().baseUrl("http://history-balancer-5405023.ap-northeast-2.elb.amazonaws.com").addConverterFactory(GsonConverterFactory.create()).build()
val authService = retrofit.create(AuthInterface::class.java)
authService.nickNameExist(nickname).enqueue(object : Callback<ExistResponse>{
override fun onResponse(call: Call<ExistResponse>, response: Response<ExistResponse>) {
val resp = response.body()
if(response.code() == 200 || response.code() == 202){
existView.onAuthSuccess(resp!!.body)
} else {
existView.onAuthFailure()
}
}
override fun onFailure(call: Call<ExistResponse>, t: Throwable) {
existView.onAuthFailure()
}
})
}
fun userIdExist(userId : String?){
val retrofit = Retrofit.Builder().baseUrl("http://history-balancer-5405023.ap-northeast-2.elb.amazonaws.com").addConverterFactory(GsonConverterFactory.create()).build()
val authService = retrofit.create(AuthInterface::class.java)
authService.userIdExist(userId).enqueue(object : Callback<ExistResponse>{
override fun onResponse(call: Call<ExistResponse>, response: Response<ExistResponse>){
val resp = response.body()
if(response.code() == 200 || response.code() == 202){
existView.onAuthSuccess(resp!!.body)
} else {
existView.onAuthFailure()
}
}
override fun onFailure(call: Call<ExistResponse>, t: Throwable) {
existView.onAuthFailure()
}
})
}
fun signUp(nickname:String?, id:String?, password:String){
val retrofit = Retrofit.Builder().baseUrl("http://history-balancer-5405023.ap-northeast-2.elb.amazonaws.com").addConverterFactory(GsonConverterFactory.create()).build()
val authService = retrofit.create(AuthInterface::class.java)
authService.signUp(User(id, nickname, password)).enqueue(object : Callback<AuthResponse>{
override fun onResponse(call: Call<AuthResponse>, response: Response<AuthResponse>) {
}
override fun onFailure(call: Call<AuthResponse>, t: Throwable) {
}
})
}
fun login(id:String, password:String){
val retrofit = Retrofit.Builder().baseUrl("http://history-balancer-5405023.ap-northeast-2.elb.amazonaws.com")
.addConverterFactory(GsonConverterFactory.create()).build()
val authService = retrofit.create(AuthInterface::class.java)
authService.login(Login(id, password)).enqueue(object : Callback<LoginResponse>{
override fun onResponse(call: Call<LoginResponse>, response: Response<LoginResponse>) {
val resp = response.body()
if(response.code() == 200 || response.code() == 202){
authView.onAuthSuccess(resp!!.body)
} else{
authView.onAuthFailure()
}
}
override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
authView.onAuthFailure()
}
})
}
fun tokenReissue(accessToken : String, refreshToken : String){
val retrofit = Retrofit.Builder().baseUrl("http://history-balancer-5405023.ap-northeast-2.elb.amazonaws.com")
.addConverterFactory(GsonConverterFactory.create()).build()
val authService = retrofit.create(AuthInterface::class.java)
authService.tokenReissue(Token(accessToken, refreshToken)).enqueue(object : Callback<LoginResponse>{
override fun onResponse(call: Call<LoginResponse>, response: Response<LoginResponse>) {
val resp = response.body()
if(response.code() == 200 || response.code() == 202){
authView.onAuthSuccess(resp!!.body)
} else{
authView.onAuthFailure()
}
}
override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
authView.onAuthFailure()
}
})
}
} | 0 | Kotlin | 0 | 0 | bae06314e26b1e91bedb7b766065f183c562ddae | 4,771 | HiStory_Refactoring | MIT License |
data/src/main/kotlin/com/zeongit/data/database/primary/dao/FollowMessageDao.kt | fuzeongit | 265,537,118 | false | null | package com.zeongit.data.database.primary.dao
import com.zeongit.data.database.primary.entity.FollowMessage
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.JpaSpecificationExecutor
import org.springframework.stereotype.Repository
@Repository
interface FollowMessageDao : JpaRepository<FollowMessage, Int>, JpaSpecificationExecutor<FollowMessage> {
fun findAllByFollowingIdOrderByCreateDateDesc(followingId: Int): List<FollowMessage>
fun countByFollowingIdAndReview(followingId: Int, review: Boolean): Long
fun findAllByFollowingIdAndReviewOrderByCreateDateDesc(followingId: Int, review: Boolean): List<FollowMessage>
} | 2 | Kotlin | 1 | 1 | 695043ba1e5f4a7a7ad662817de77758c97f408e | 694 | zeongit-beauty | MIT License |
parser/src/commonMain/kotlin/com/faendir/om/parser/solution/model/part/Conduit.kt | F43nd1r | 244,249,918 | false | null | package com.faendir.om.parser.solution.model.part
import com.faendir.om.parser.solution.model.Position
data class Conduit(
override var position: Position,
override var rotation: Int,
var id: Int,
var positions: List<Position>
) : Part() {
override val name = "pipe"
} | 0 | Kotlin | 0 | 1 | 5370c9ae632354b3e63e4b04b2d59170467be067 | 290 | omsp | Apache License 2.0 |
app/src/main/java/com/newbiechen/nbreader/ui/page/booklist/BookListViewModel.kt | newbiechen1024 | 239,496,581 | false | null | package com.newbiechen.nbreader.ui.page.booklist
import android.content.Context
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import com.newbiechen.nbreader.data.entity.NetBookEntity
import com.newbiechen.nbreader.data.repository.impl.IBookListRepository
import com.newbiechen.nbreader.ui.page.base.BaseViewModel
import com.newbiechen.nbreader.ui.component.widget.StatusView
import com.newbiechen.nbreader.uilts.LogHelper
import com.newbiechen.nbreader.uilts.NetworkUtil
import com.github.jdsjlzx.view.LoadingFooter
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
// 传递什么呢 error 还有 no more
typealias OnLoadMoreStateChange = (state: LoadingFooter.State) -> Unit
class BookListViewModel @Inject constructor(private val repository: IBookListRepository) : BaseViewModel() {
companion object {
// 每页加载的数据量
private const val PAGE_LIMIT = 21
private const val TAG = "BookListViewModel"
}
// 当前页面状态
val pageStatus = ObservableField(StatusView.STATUS_LOADING)
val bookList = ObservableArrayList<NetBookEntity>()
private var curItemPos = 0
private var totalCount = 0
// 请求参数
private var alias: String? = null
private var sort: Int? = null
private var cat: String? = null
private var isserial: Boolean? = null
private var updated: Int? = null
// 刷新书籍列表
fun refreshBookList(
context: Context,
alias: String,
sort: Int,
cat: String? = null,
isserial: Boolean? = null,
updated: Int? = null
) {
// 存储请求参数
this.alias = alias
this.sort = sort
this.cat = cat
this.isserial = isserial
this.updated = updated
// 检测当前网络状态
if (!NetworkUtil.isNetworkAvaialble(context)) {
pageStatus.set(StatusView.STATUS_ERROR)
return
}
pageStatus.set(StatusView.STATUS_LOADING)
// 请求书籍
addDisposable(
repository.getBookList(alias, sort, curItemPos, PAGE_LIMIT, cat, isserial, updated)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
LogHelper.i(TAG, "result:${it.books.size}")
// 通知完成
bookList.clear()
bookList.addAll(it.books)
// 设置参数
totalCount = it.total
curItemPos += it.books.size
},
{
pageStatus.set(StatusView.STATUS_ERROR)
// 发送 toast 提示?
},
{
// 通知当前状态为完成状态
pageStatus.set(StatusView.STATUS_FINISH)
}
)
)
}
// 加载更多书籍
fun loadMoreBookList(context: Context, onLoadMoreStateChange: OnLoadMoreStateChange) {
if (alias == null || sort == null) {
return
}
// 检测当前网络状态,设置错误回调
if (!NetworkUtil.isNetworkAvaialble(context)) {
onLoadMoreStateChange(LoadingFooter.State.NetWorkError)
return
}
// 请求书籍
addDisposable(
repository.getBookList(alias!!, sort!!, curItemPos, PAGE_LIMIT, cat, isserial, updated)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{
bookList.addAll(it.books)
curItemPos += it.books.size
},
{
onLoadMoreStateChange(LoadingFooter.State.NetWorkError)
},
{
if (curItemPos >= totalCount) {
onLoadMoreStateChange(LoadingFooter.State.NoMore)
}
}
)
)
}
} | 5 | Kotlin | 8 | 37 | e423b13915578ab95c1683bfa7a70e59f19f2eab | 4,125 | NBReader | Apache License 2.0 |
aegaeon-common/src/main/kotlin/ca/n4dev/aegaeonnext/common/repository/AuthorizationCodeRepository.kt | n4devca | 216,624,101 | false | null | /*
* Copyright 2019 <NAME> - n4dev.ca
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package ca.n4dev.aegaeonnext.common.repository
import ca.n4dev.aegaeonnext.common.model.AuthorizationCode
import ca.n4dev.aegaeonnext.common.utils.Page
/**
*
* AuthorizationCodeRepository.java
* TODO(rguillemette) Add description.
*
* @author rguillemette
* @since 2.0.0 - Nov 21 - 2019
*
*/
interface AuthorizationCodeRepository {
fun getById(id: Long) : AuthorizationCode?
fun getByCode(code: String) : AuthorizationCode?
fun getByClientId(clientId: Long, page: Page) : List<AuthorizationCode>
fun getByUserId(userId: Long, page: Page) : List<AuthorizationCode>
fun create(authorizationCode: AuthorizationCode): Long
fun delete(id: Long): Int
} | 8 | Kotlin | 0 | 0 | 0d4f33e49f3bc45895b40bc12fe791663c7cb568 | 1,537 | aegaeon-next | Apache License 2.0 |
app/src/main/java/com/prmto/mova_movieapp/feature_mylist/presentation/ListViewModel.kt | tolgaprm | 541,709,201 | false | {"Kotlin": 522687} | package com.prmto.mova_movieapp.feature_mylist.presentation
import androidx.lifecycle.viewModelScope
import com.prmto.mova_movieapp.core.domain.models.movie.Movie
import com.prmto.mova_movieapp.core.domain.models.tv.TvSeries
import com.prmto.mova_movieapp.core.domain.use_case.database.LocalDatabaseUseCases
import com.prmto.mova_movieapp.core.presentation.base.viewModel.BaseViewModelWithUiEvent
import com.prmto.mova_movieapp.core.presentation.util.UiEvent
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.flow.updateAndGet
import javax.inject.Inject
@HiltViewModel
class ListViewModel @Inject constructor(
private val localDatabaseUseCases: LocalDatabaseUseCases,
) : BaseViewModelWithUiEvent<UiEvent>() {
private val mutableState = MutableStateFlow(ListState())
val state = combine(
mutableState,
localDatabaseUseCases.getFavoriteMoviesUseCase(),
localDatabaseUseCases.getFavoriteTvSeriesUseCase(),
localDatabaseUseCases.getMoviesInWatchListUseCase(),
localDatabaseUseCases.getTvSeriesInWatchListUseCase()
) { listState, favoriteMovies, favoriteTvSeries, moviesInWatchList, tvSeriesInWatchList ->
when (listState.chipType) {
ChipType.MOVIE -> {
if (listState.selectedTab.isFavoriteList()) {
updateListMovieAndLoading(movieList = favoriteMovies)
} else {
updateListMovieAndLoading(movieList = moviesInWatchList)
}
}
ChipType.TVSERIES -> {
if (listState.selectedTab.isFavoriteList()) {
updateListTvSeriesAndLoading(tvSeriesList = favoriteTvSeries)
} else {
updateListTvSeriesAndLoading(tvSeriesList = tvSeriesInWatchList)
}
}
}
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), ListState())
fun onEvent(event: ListEvent) {
when (event) {
is ListEvent.SelectedTab -> {
mutableState.update { it.copy(selectedTab = event.listTab) }
}
is ListEvent.UpdateListType -> {
mutableState.update { it.copy(chipType = event.chipType) }
}
is ListEvent.ClickedMovieItem -> {
navigateToDetailBottomSheet(movie = event.movie)
}
is ListEvent.ClickedTvSeriesItem -> {
navigateToDetailBottomSheet(tvSeries = event.tvSeries)
}
}
}
private fun navigateToDetailBottomSheet(
movie: Movie? = null,
tvSeries: TvSeries? = null,
) {
val directions = ListFragmentDirections.actionMyListFragmentToDetailBottomSheet(
movie,
tvSeries
)
addConsumableViewEvent(UiEvent.NavigateTo(directions))
}
private fun updateListMovieAndLoading(movieList: List<Movie>): ListState {
return mutableState.updateAndGet {
it.copy(
movieList = movieList,
isLoading = false
)
}
}
private fun updateListTvSeriesAndLoading(tvSeriesList: List<TvSeries>): ListState {
return mutableState.updateAndGet {
it.copy(
tvSeriesList = tvSeriesList,
isLoading = false
)
}
}
} | 1 | Kotlin | 3 | 56 | 1936fb736958a2e47e691ae7d694ba56e77e44f5 | 3,594 | Mova-MovieApp | Apache License 2.0 |
custom-vu/src/main/kotlin/jces1209/vu/page/CloudIssuePage.kt | dmewada-atlas | 290,410,294 | true | {"Kotlin": 235838} | package jces1209.vu.page
import com.atlassian.performance.tools.jiraactions.api.page.wait
import jces1209.vu.page.contextoperation.ContextOperationIssue
import jces1209.vu.wait
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.openqa.selenium.WebElement
import org.openqa.selenium.interactions.Actions
import org.openqa.selenium.support.ui.ExpectedConditions.invisibilityOfAllElements
import org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated
import org.openqa.selenium.support.ui.ExpectedConditions
import org.openqa.selenium.support.ui.ExpectedConditions.*
import org.openqa.selenium.support.ui.WebDriverWait
import java.time.Duration
class CloudIssuePage(
private val driver: WebDriver
) : AbstractIssuePage {
private val logger: Logger = LogManager.getLogger(this::class.java)
private val bentoSummary = By.cssSelector("[data-test-id='issue.views.issue-base.foundation.summary.heading']")
private val classicSummary = By.id("key-val")
private val falliblePage = FalliblePage.Builder(
expectedContent = listOf(bentoSummary, classicSummary),
webDriver = driver
)
.cloudErrors()
.build()
override fun waitForSummary(): AbstractIssuePage {
falliblePage.waitForPageToLoad()
return this
}
override fun comment(): Commenting {
return if (isCommentingClassic()) {
ClassicCloudCommenting(driver)
} else {
BentoCommenting(driver)
}
}
override fun editDescription(description: String): CloudIssuePage {
driver
.wait(elementToBeClickable(By.cssSelector("[data-test-id = 'issue.views.field.rich-text.description']")))
.click();
val descriptionForm = driver
.wait(
presenceOfElementLocated(By.cssSelector("[data-test-id='issue.views.field.rich-text.editor-container']"))
)
Actions(driver)
.sendKeys(description)
.perform()
descriptionForm
.findElement(By.cssSelector("[data-testid='comment-save-button']"))
.click()
driver.wait(
invisibilityOfAllElements(descriptionForm)
)
return this;
}
override fun linkIssue(): CloudIssueLinking {
return CloudIssueLinking(driver)
}
override fun addAttachment(): CloudAddScreenShot {
return CloudAddScreenShot(driver)
}
override fun changeAssignee(): CloudIssuePage {
driver
.findElement(By.cssSelector("[data-test-id = 'issue.views.field.user.assignee']"))
.click();
var userList = driver
.wait(
ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[contains(@class,'fabric-user-picker__menu-list')]/*"))
)
if (userList.size == 1 && userList[0].text == "No options") {
logger.debug("No user options for Assignee")
throw InterruptedException("No options for Assignee")
}
val firstUser = driver
.wait(
ExpectedConditions.presenceOfElementLocated(By.id("react-select-assignee-option-0"))
)
var userName = firstUser.text.removeSuffix(" (Assign to me)")
firstUser.click()
driver.wait(
ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@data-test-id='issue.views.field.user.assignee']//*[.='$userName']"))
)
return this;
}
override fun contextOperation(): ContextOperationIssue {
return ContextOperationIssue(driver)
}
override fun isTimeSpentFormAppeared(): Boolean {
try {
driver
.wait(
ExpectedConditions.or(
ExpectedConditions.presenceOfElementLocated(By.id("log-work-time-logged"))
)
)
} catch (e: Exception) {
return false
}
return true
}
override fun cancelTimeSpentForm(): AbstractIssuePage {
val transitionCancelLocator = By.id("issue-workflow-transition-cancel")
driver
.wait(
timeout = Duration.ofSeconds(5),
condition = ExpectedConditions.presenceOfElementLocated(transitionCancelLocator)
)
.click()
driver
.wait(
timeout = Duration.ofSeconds(7),
condition = ExpectedConditions.invisibilityOfElementLocated(transitionCancelLocator)
)
return this
}
override fun fillInTimeSpentForm(): AbstractIssuePage {
driver
.wait(
ExpectedConditions.presenceOfElementLocated(By.id("log-work-time-logged"))
)
.click()
Actions(driver)
.sendKeys("1h")
.perform()
driver
.wait(
ExpectedConditions.presenceOfElementLocated(By.id("comment"))
)
.click()
Actions(driver)
.sendKeys("comment")
.perform()
driver
.wait(
ExpectedConditions.presenceOfElementLocated(By.id("issue-workflow-transition-submit"))
)
.click()
driver
.wait(
timeout = Duration.ofSeconds(7),
condition = ExpectedConditions.invisibilityOfElementLocated(By.id("issue-workflow-transition-cancel"))
)
driver
.wait(
timeout = Duration.ofSeconds(3),
condition = ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@id=\"helpPanelContainer\"]"))
)
return this
}
private fun waitForNotWatchingElement(): WebElement = driver.wait(
timeout = Duration.ofSeconds(7),
condition = ExpectedConditions.elementToBeClickable(By.xpath("//*[@aria-label = 'Not watching']"))
)
private fun waitForTransitionButton(): WebElement = driver.wait(
timeout = Duration.ofSeconds(7),
condition = ExpectedConditions.elementToBeClickable(By.xpath("//*[@data-test-id = 'issue.views.issue-base.foundation.status.status-field-wrapper']//button"))
)
private fun clickOnElementUntilVisible(element: By, conditionOfSuccess: By) {
WebDriverWait(driver, 7)
.until {
try {
driver.wait(ExpectedConditions.elementToBeClickable(element))
.click()
driver.wait(ExpectedConditions.presenceOfElementLocated(conditionOfSuccess))
true
} catch (e: Exception) {
false
}
}
}
override fun transition(): CloudIssuePage {
falliblePage.waitForPageToLoad()
waitForNotWatchingElement()
waitForTransitionButton()
clickOnElementUntilVisible(By.xpath("//*[@data-test-id = 'issue.views.issue-base.foundation.status.status-field-wrapper']//button"),
By.xpath("//*[@data-test-id = 'issue.views.issue-base.foundation.status.status-field-wrapper']//*[contains(@data-test-id,\"issue.fields.status.common.ui.status-lozenge\")]")
)
driver
.wait(
timeout = Duration.ofSeconds(7),
condition = ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@data-test-id = 'issue.views.issue-base.foundation.status.status-field-wrapper']//*[contains(@data-test-id,\"issue.fields.status.common.ui.status-lozenge\")]"))
)
.click()
return this
}
private fun isCommentingClassic(): Boolean = driver
.findElements(By.id("footer-comment-button"))
.isNotEmpty()
}
| 0 | null | 0 | 0 | 93fadc226720c11897fa121492d4d5831697a422 | 7,864 | jces-1209 | Apache License 2.0 |
app/src/main/java/org/listenbrainz/android/viewmodel/SearchViewModel.kt | metabrainz | 550,726,972 | false | {"Kotlin": 941501, "Ruby": 423} | package org.listenbrainz.android.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.combineTransform
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.getAndUpdate
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import org.listenbrainz.android.di.DefaultDispatcher
import org.listenbrainz.android.di.IoDispatcher
import org.listenbrainz.android.model.ResponseError
import org.listenbrainz.android.model.SearchUiState
import org.listenbrainz.android.model.User
import org.listenbrainz.android.model.UserListUiState
import org.listenbrainz.android.repository.social.SocialRepository
import org.listenbrainz.android.util.Resource
import javax.inject.Inject
@HiltViewModel
class SearchViewModel @Inject constructor(
private val repository: SocialRepository,
@DefaultDispatcher private val defaultDispatcher: CoroutineDispatcher,
@IoDispatcher private val ioDispatcher: CoroutineDispatcher
) : ViewModel() {
private val inputQueryFlow = MutableStateFlow("")
@OptIn(FlowPreview::class)
private val queryFlow = inputQueryFlow.asStateFlow().debounce(500).distinctUntilChanged()
private val errorFlow = MutableStateFlow<ResponseError?>(null)
// Result flows
private val userListFlow = MutableStateFlow<List<User>>(emptyList())
private val followStateFlow = MutableStateFlow<List<Boolean>>(emptyList())
private val resultFlow = userListFlow
.combineTransform(followStateFlow) { userList, isFollowedList ->
emit(UserListUiState(userList, isFollowedList))
}
val uiState = createUiStateFlow()
init {
// Engage query flow
viewModelScope.launch(ioDispatcher) {
queryFlow.collectLatest { username ->
if (username.isEmpty()){
userListFlow.emit(emptyList())
return@collectLatest
}
val result = repository.searchUser(username)
when (result.status) {
Resource.Status.SUCCESS -> userListFlow.emit(result.data?.users ?: emptyList())
Resource.Status.FAILED -> emitError(result.error)
else -> return@collectLatest
}
}
}
// Observing changes in userListFlow
viewModelScope.launch(defaultDispatcher) {
userListFlow.collectLatest { userList ->
if (userList.isEmpty()) {
followStateFlow.emit(emptyList())
return@collectLatest
}
val followList = mutableListOf<Boolean>()
userList.forEach {
followList.add(it.isFollowed)
}
followStateFlow.emit(followList)
}
}
}
private fun createUiStateFlow(): StateFlow<SearchUiState> {
return combine(
inputQueryFlow,
resultFlow,
errorFlow
){ query: String, users: UserListUiState, error: ResponseError? ->
return@combine SearchUiState(query, users, error)
}.stateIn(
viewModelScope,
SharingStarted.Eagerly,
SearchUiState("", UserListUiState(), null)
)
}
fun updateQueryFlow(query: String) {
viewModelScope.launch {
inputQueryFlow.emit(query)
}
}
suspend fun toggleFollowStatus(user: User, index: Int) {
if (user.username.isEmpty()) return
if (followStateFlow.value[index])
optimisticallyUnfollowUser(user, index)
else
optimisticallyFollowUser(user, index)
}
private suspend fun optimisticallyFollowUser(user: User, index: Int) {
invertFollowUiState(index)
val result = repository.followUser(user.username)
when (result.status) {
Resource.Status.FAILED -> {
emitError(result.error)
if (userIsAlreadyFollowed(result.error)){
// We won't toggle back follow state if user is already followed.
return
}
invertFollowUiState(index)
}
else -> Unit
}
}
private suspend fun optimisticallyUnfollowUser(user: User, index: Int) {
invertFollowUiState(index)
val result = repository.unfollowUser(user.username)
return when (result.status) {
Resource.Status.FAILED -> {
// Since same response is given by server even if user is unfollowed or not, we
// won't do anything here.
invertFollowUiState(index)
emitError(result.error)
}
else -> Unit
}
}
private fun invertFollowUiState(index: Int) {
followStateFlow.getAndUpdate { list ->
val mutableList = list.toMutableList()
try {
mutableList[index] = !mutableList[index]
} catch (e: IndexOutOfBoundsException){
// This means query has already changed while we were evaluating this function.
return@getAndUpdate list
}
return@getAndUpdate mutableList
}
}
private suspend fun emitError(error: ResponseError?){ errorFlow.emit(error) }
/** Call this function to reset [errorFlow]'s latest emission.*/
fun clearErrorFlow() {
viewModelScope.launch {
errorFlow.emit(null)
}
}
fun clearUi() {
viewModelScope.launch {
userListFlow.emit(emptyList())
inputQueryFlow.emit("")
}
}
/** True if the error states the the user is already being followed.*/
private fun userIsAlreadyFollowed(error: ResponseError?): Boolean =
error == ResponseError.BAD_REQUEST &&
error.actualResponse?.contains("already following") == true
} | 15 | Kotlin | 27 | 53 | ffd438c34594b40a1dd8254391da843085739199 | 6,716 | listenbrainz-android | Apache License 2.0 |
src/main/java/com/alcosi/lib/secured/encrypt/EncryptionContainerConfig.kt | alcosi | 698,911,809 | false | {"Kotlin": 405550, "Java": 82765, "HTML": 3451, "JavaScript": 509, "CSS": 203} | /*
* Copyright (c) 2023 Alcosi Group Ltd. and affiliates.
*
* 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.alcosi.lib.secured.encrypt
import com.alcosi.lib.secured.container.SecuredDataByteArray
import com.alcosi.lib.secured.encrypt.encryption.Decrypter
import com.alcosi.lib.secured.encrypt.encryption.Encrypter
import com.alcosi.lib.serializers.SecuredDataContainerDeSerializer
import com.alcosi.lib.serializers.SecuredDataContainerSerializer
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.AutoConfiguration
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
/**
* Configuration class for the EncryptionContainerConfig.
* This class is responsible for configuring and setting up the encryption, decryption, and serialization components.
*
* @constructor Creates an instance of EncryptionContainerConfig.
*/
@ConditionalOnProperty(
prefix = "common-lib.secured",
name = ["disabled"],
havingValue = "false",
matchIfMissing = true,
)
@AutoConfiguration
class EncryptionContainerConfig {
/**
* Sets the provided Encrypter service to be used for encrypting data in the SecuredDataByteArray class.
*
* @param encrypter The Encrypter service to be set.
*/
@ConditionalOnBean(Encrypter::class)
@Autowired
fun setEncrypterToSecuredDataByteArray(encrypter: Encrypter) {
SecuredDataByteArray.setEncrypter(encrypter)
}
/**
* Sets the provided decrypter service to be used for decrypting data in the SecuredDataByteArray class.
*
* @param decrypter The decrypter service to be set.
*/
@Autowired
@ConditionalOnBean(Decrypter::class)
fun setDecrypterToSecuredDataByteArray(decrypter: Decrypter) {
SecuredDataByteArray.setDecrypter(decrypter)
}
/**
* Sets the provided [SensitiveComponent] instance to be used for serializing and deserializing sensitive data.
*
* @param sensitiveComponent The [SensitiveComponent] instance to be set.
*/
@Autowired
@ConditionalOnBean(SensitiveComponent::class)
fun setSensitiveComponentToSerializers(sensitiveComponent: SensitiveComponent) {
SecuredDataContainerSerializer.setSensitiveComponentPublic(sensitiveComponent)
SecuredDataContainerDeSerializer.setSensitiveComponentPublic(sensitiveComponent)
}
}
| 0 | Kotlin | 0 | 0 | 87c39d8bb8f80c0a5e82252e881af2fc6e363b36 | 2,995 | alcosi_commons_library | Apache License 2.0 |
cli/src/main/kotlin/io/github/legion2/tosca_orchestrator/cli/commands/CreateResources.kt | Legion2 | 350,881,803 | false | null | package io.github.legion2.tosca_orchestrator.cli.commands
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.core.requireObject
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.types.inputStream
import io.github.legion2.tosca_orchestrator.cli.*
import kotlinx.coroutines.runBlocking
class CreateResources : CliktCommand(name = "create") {
private val cliContext by requireObject<CliContext>()
private val resourceType by resourceTypeArgument()
private val inputStream by argument(name = "resource", help = "The file containing the resource definition or - to use stdin").inputStream()
override fun run() = runBlocking {
val resource = inputStream.readResource()
echo(cliContext.ritamClient.getClient(resourceType).createResources(resource.name, resource).echoString)
}
} | 6 | Kotlin | 0 | 3 | fb4ef1a7bf3d79d258da2b6779381a87e0c435e9 | 888 | ritam | Apache License 2.0 |
v2-chatlink/src/commonTest/kotlin/com/bselzer/gw2/v2/chatlink/TraitLinkTests.kt | Woody230 | 388,820,096 | false | {"Kotlin": 750899} | package com.bselzer.gw2.v2.chatlink
class TraitLinkTests : IdLinkTests<TraitLink>() {
override val instance: TraitLink = TraitLink()
override val mapping: Map<String, Int> = mapOf(
"[&B/IDAAA=]" to 1010,
)
} | 2 | Kotlin | 0 | 2 | 7bd43646f94d1e8de9c20dffcc2753707f6e455b | 229 | GW2Wrapper | Apache License 2.0 |
app/src/main/java/com/compose/jreader/utils/Mapper.kt | alinbabu2010 | 493,496,121 | false | null | package com.compose.jreader.utils
interface Mapper<T, V> {
fun map(data: T): V
} | 0 | Kotlin | 0 | 1 | 68770268d55131f87541b2c73ee0d45df1e6ccf4 | 85 | jReader | MIT License |
app/src/test/java/com/tzion/jetpackmovies/presentation/FindMoviesViewModelTest.kt | 4mr0m3r0 | 156,536,164 | false | {"Kotlin": 151737} | package com.tzion.jetpackmovies.presentation
class FindMoviesViewModelTest
| 4 | Kotlin | 4 | 15 | 11b983e57bc1508a6ec5ca738af70c4f9a8ea9aa | 76 | movies-jetpack-sample | MIT License |
subprojects/gradle/build-trace/src/main/kotlin/com/avito/android/build_trace/BuildTracePlugin.kt | sundetova | 287,793,131 | true | {"Kotlin": 2381272, "Shell": 16491, "Python": 14168, "Dockerfile": 7088, "Makefile": 2410} | package com.avito.android.build_trace
import com.avito.android.gradle.metric.GradleCollector
import com.avito.android.gradle.metric.MetricsConsumer
import com.avito.kotlin.dsl.getBooleanProperty
import com.avito.kotlin.dsl.isRoot
import com.avito.utils.gradle.BuildEnvironment
import com.avito.utils.gradle.buildEnvironment
import com.avito.utils.logging.ciLogger
import org.gradle.api.Plugin
import org.gradle.api.Project
import java.io.File
open class BuildTracePlugin : Plugin<Project> {
override fun apply(project: Project) {
check(project.isRoot()) {
"Plugin must be applied to the root project but was applied to ${project.path}"
}
if (isBuildTraceEnabled(project)) {
GradleCollector.initialize(
project, listOf(
buildTraceConsumer(project)
)
)
}
}
private fun buildTraceConsumer(project: Project): MetricsConsumer = BuildTraceConsumer(
// TODO: pass it from an extension
output = File(project.projectDir, "outputs/trace/build.trace"),
logger = project.ciLogger
)
// TODO: enable by a project extension
private fun isBuildTraceEnabled(project: Project): Boolean {
return (project.buildEnvironment is BuildEnvironment.CI)
|| (project.gradle.startParameter.isBuildScan)
|| (project.gradle.startParameter.isProfile)
|| (project.getBooleanProperty("android.enableProfileJson", default = false))
}
}
| 0 | Kotlin | 0 | 0 | 2f65d3005671248068fe734d7fd48ced92192418 | 1,523 | avito-android | MIT License |
app/src/main/java/com/example/android/hilt/MainActivity.kt | komzakdroid | 679,382,103 | false | null | package com.example.android.hilt
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.example.android.hilt.databinding.ActivityMainBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
}
}
| 0 | Kotlin | 0 | 0 | 2cbc5ebe9da25fe3a07d76a0f22718e29ad53e6c | 541 | DevChallange | Apache License 2.0 |
idbdata/src/main/java/com/leperlier/quinquis/lentz/imdb/datasources/OnlineAuthorsDataSource.kt | RomainLENTZ | 773,319,710 | false | {"Kotlin": 119708} | package com.leperlier.quinquis.lentz.imdb.datasources
import AuthorsResponse
import MovieResponse
import SeriesResponse
import com.leperlier.quinquis.lentz.imdb.api.response.toToken
import com.leperlier.quinquis.lentz.imdb.api.service.MovieService
import com.leperlier.quinquis.lentz.imdb.api.service.SerieService
import com.leperlier.quinquis.lentz.imdb.data.Movie
import com.leperlier.quinquis.lentz.imdb.data.Serie
import com.leperlier.quinquis.lentz.imdb.data.Token
import com.leperlier.quinquis.lentz.imdb.data.Video
import com.leperlier.quinquis.lentz.imdb.utils.Result
import com.leperlier.quinquis.lentz.imdb.utils.safeCall // Assurez-vous que ceci est correctement importé.
import retrofit2.Response
import javax.inject.Inject
/**
* Manipule les données de l'application en utilisant un web service
* Cette classe est interne au module, ne peut être initialisé ou exposé aux autres composants
* de l'application.
*/
internal class OnlineAuthorsDataSource @Inject constructor(private val service: MovieService): AuthorsDataSource {
/**
* Récupérer le token du serveur.
* @return [Result<Token>]
* Si [Result.Succes], tout s'est bien passé.
* Sinon, une erreur est survenue.
*/
override suspend fun getToken(): Result<Token> = safeCall {
service.getToken().parse().let { parsedResponse ->
when (parsedResponse) {
is Result.Succes -> Result.Succes(parsedResponse.data.toToken())
is Result.Error -> parsedResponse
}
}
}
/**
* Fonction d'extension pour traiter les réponses HTTP.
*/
internal fun <T : Any> Response<T>.parse(): Result<T> {
return if (isSuccessful) {
body()?.let {
Result.Succes(it)
} ?: Result.Error(
exception = NoDataException(),
message = "Aucune donnée",
code = 404
)
} else {
Result.Error(
exception = Exception(),
message = message(),
code = code()
)
}
}
class NoDataException: Exception()
override suspend fun saveToken(token: Token) {
TODO("I don't know how to save a token, the local datasource probably does")
}
suspend fun getAuthors(): Result<AuthorsResponse> = safeCall {
service.getAuthors().let { response ->
if (response.isSuccessful) {
Result.Succes(response.body()!!)
} else {
Result.Error(
exception = Exception("Erreur lors de la récupération des auteurs"),
message = response.message(),
code = response.code()
)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 674e161a282db8794a306806779fd18b0099380b | 2,788 | mini-projet-group_quinquis_leperlier_lentz | Apache License 2.0 |
app/src/main/java/com/example/diary/domain/activity/DiaryClickListner.kt | 8954sood | 647,554,392 | false | null | package com.example.diary.domain.activity
import com.example.diary.model.entity.Diary
interface DiaryClickListner {
fun cancelBtnEvent()
fun saveBtnEvent(diary: Diary)
} | 0 | Kotlin | 0 | 0 | b2c6e541e56957183d35bd16e5bf3f2815d93d2b | 179 | diary | MIT License |
app/src/main/java/com/example/diary/domain/activity/DiaryClickListner.kt | 8954sood | 647,554,392 | false | null | package com.example.diary.domain.activity
import com.example.diary.model.entity.Diary
interface DiaryClickListner {
fun cancelBtnEvent()
fun saveBtnEvent(diary: Diary)
} | 0 | Kotlin | 0 | 0 | b2c6e541e56957183d35bd16e5bf3f2815d93d2b | 179 | diary | MIT License |
core/data/src/main/kotlin/voodoo/data/Recommendation.kt | twilight-sparkle-irl | 150,922,158 | true | {"Kotlin": 271222, "CSS": 35899, "Shell": 5029, "Ruby": 73} | package voodoo.data
/**
* Created by nikky on 29/03/18.
* @author Nikky
*/
enum class Recommendation {
starred, avoid
} | 0 | Kotlin | 0 | 0 | 747a70d5280c17c2b6f26c88841814a6cfac5732 | 128 | Voodoo | MIT License |
elucidate-common-lib/src/main/kotlin/com/digirati/elucidate/common/infrastructure/constants/RDFConstants.kt | knaw-huc | 326,953,760 | true | {"Java": 601493, "PLpgSQL": 363672, "Kotlin": 106494, "Dockerfile": 1278} | package com.digirati.elucidate.common.infrastructure.constants
object RDFConstants {
const val URI_VALUE = "http://www.w3.org/1999/02/22-rdf-syntax-ns#value"
} | 3 | Java | 0 | 0 | ca1ca27e4bc4942b7d5204a031f7b9381183dbf5 | 164 | elucidate-server | MIT License |
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/api/VimOptionGroupBase.kt | JetBrains | 1,459,486 | false | {"Kotlin": 4968245, "Java": 403572, "ANTLR": 37092, "HTML": 2184} | /*
* Copyright 2003-2023 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.api
import com.maddyhome.idea.vim.options.EffectiveOptionValueChangeListener
import com.maddyhome.idea.vim.options.GlobalOptionChangeListener
import com.maddyhome.idea.vim.options.NumberOption
import com.maddyhome.idea.vim.options.Option
import com.maddyhome.idea.vim.options.OptionAccessScope
import com.maddyhome.idea.vim.options.OptionDeclaredScope.GLOBAL
import com.maddyhome.idea.vim.options.OptionDeclaredScope.GLOBAL_OR_LOCAL_TO_BUFFER
import com.maddyhome.idea.vim.options.OptionDeclaredScope.GLOBAL_OR_LOCAL_TO_WINDOW
import com.maddyhome.idea.vim.options.OptionDeclaredScope.LOCAL_TO_BUFFER
import com.maddyhome.idea.vim.options.OptionDeclaredScope.LOCAL_TO_WINDOW
import com.maddyhome.idea.vim.options.ToggleOption
import com.maddyhome.idea.vim.vimscript.model.datatypes.VimDataType
public abstract class VimOptionGroupBase : VimOptionGroup {
private val globalValues = mutableMapOf<String, VimDataType>()
private val globalParsedValues = mutableMapOf<String, Any>()
private val globalOptionListeners = MultiSet<String, GlobalOptionChangeListener>()
private val effectiveOptionValueListeners = MultiSet<String, EffectiveOptionValueChangeListener>()
private val localOptionsKey = Key<MutableMap<String, VimDataType>>("localOptions")
private val perWindowGlobalOptionsKey = Key<MutableMap<String, VimDataType>>("perWindowGlobalOptions")
private val parsedEffectiveValueKey = Key<MutableMap<String, Any>>("parsedEffectiveOptionValues")
override fun initialiseOptions() {
Options.initialise()
}
override fun initialiseLocalOptions(editor: VimEditor, sourceEditor: VimEditor?, scenario: LocalOptionInitialisationScenario) {
when (scenario) {
// We're initialising the first (hidden) editor. Vim always has at least one window (and buffer); IdeaVim doesn't.
// We fake this with a hidden editor that is created when the plugin first starts. It is used to capture state
// when initially evaluating `~/.ideavimrc`, and then used to initialise subsequent windows. But first, we must
// initialise all local options to the default (global) values
LocalOptionInitialisationScenario.DEFAULTS -> {
check(sourceEditor == null) { "sourceEditor must be null for DEFAULTS scenario" }
initialisePerWindowGlobalValues(editor)
initialiseLocalToBufferOptions(editor)
initialiseLocalToWindowOptions(editor)
}
// The opening window is either:
// a) the fallback window used to evaluate `~/.ideavimrc` during initialisation and potentially before any windows
// are open or:
// b) the "ex" or search command line text field/editor associated with a main editor
// Either way, the target window should be a clone of the source window, copying local to buffer and local to
// window values
LocalOptionInitialisationScenario.FALLBACK,
LocalOptionInitialisationScenario.CMD_LINE -> {
check(sourceEditor != null) { "sourceEditor must not be null for FALLBACK or CMD_LINE scenarios" }
copyPerWindowGlobalValues(editor, sourceEditor)
copyLocalToBufferLocalValues(editor, sourceEditor)
copyLocalToWindowLocalValues(editor, sourceEditor)
}
// The opening/current window is being split. Clone the local-to-window options, both the local values and the
// per-window "global" values. The buffer local options are obviously already initialised
LocalOptionInitialisationScenario.SPLIT -> {
check(sourceEditor != null) { "sourceEditor must not be null for SPLIT scenario" }
copyPerWindowGlobalValues(editor, sourceEditor)
initialiseLocalToBufferOptions(editor) // Should be a no-op
copyLocalToWindowLocalValues(editor, sourceEditor)
}
// Editing a new buffer in the current window (`:edit {file}`). Remove explicitly set local values, which means to
// copy the per-window "global" value of local-to-window options to the local value, and to reset all window
// global-local options. Since it's a new buffer, we initialise buffer local options.
// Note that IdeaVim does not use this scenario for `:edit {file}` because the current implementation will always
// open a new window. It does use it for preview tabs and reusing unmodified tabs
LocalOptionInitialisationScenario.EDIT -> {
check(sourceEditor != null) { "sourceEditor must not be null for EDIT scenario" }
copyPerWindowGlobalValues(editor, sourceEditor)
initialiseLocalToBufferOptions(editor)
resetLocalToWindowOptions(editor)
}
// Editing a new buffer in a new window (`:new {file}`). Vim treats this as a split followed by an edit. That
// means, clone the window, then reset its local values to its global values
LocalOptionInitialisationScenario.NEW -> {
check(sourceEditor != null) { "sourceEditor must not be null for NEW scenario" }
copyPerWindowGlobalValues(editor, sourceEditor)
initialiseLocalToBufferOptions(editor)
copyLocalToWindowLocalValues(editor, sourceEditor) // Technically redundant
resetLocalToWindowOptions(editor)
}
}
}
private fun copyLocalToBufferLocalValues(targetEditor: VimEditor, sourceEditor: VimEditor) {
val localValues = getBufferLocalOptionStorage(targetEditor)
getAllOptions().forEach { option ->
if (option.declaredScope == LOCAL_TO_BUFFER || option.declaredScope == GLOBAL_OR_LOCAL_TO_BUFFER) {
localValues[option.name] = getBufferLocalOptionValue(option, sourceEditor)
}
}
}
/**
* Initialise local-to-buffer options by copying the global value
*
* Note that the buffer might have been previously initialised. The global value is the most recently set value,
* across any buffer and any window. This makes most sense for non-visible options - the user always gets what they
* last set, regardless of where it was set.
*
* Remember that `:set` on a buffer-local option will set both the local value and the global value.
*/
private fun initialiseLocalToBufferOptions(editor: VimEditor) {
injector.vimStorageService.getOrPutBufferData(editor, localOptionsKey) {
mutableMapOf<String, VimDataType>().also { bufferOptions ->
getAllOptions().forEach { option ->
if (option.declaredScope == LOCAL_TO_BUFFER) {
bufferOptions[option.name] = getGlobalOptionValue(option, editor)
} else if (option.declaredScope == GLOBAL_OR_LOCAL_TO_BUFFER) {
bufferOptions[option.name] = option.unsetValue
}
}
}
}
}
protected fun copyPerWindowGlobalValues(targetEditor: VimEditor, sourceEditor: VimEditor) {
getAllOptions().forEach { option ->
if (option.declaredScope == LOCAL_TO_WINDOW) {
val localValue = getGlobalOptionValue(option, sourceEditor)
setGlobalOptionValue(option, targetEditor, localValue)
}
}
}
private fun initialisePerWindowGlobalValues(targetEditor: VimEditor) {
getAllOptions().forEach { option ->
if (option.declaredScope == LOCAL_TO_WINDOW) {
setGlobalOptionValue(option, targetEditor, option.defaultValue)
}
}
}
private fun copyLocalToWindowLocalValues(targetEditor: VimEditor, sourceEditor: VimEditor) {
val localValues = getWindowLocalOptionStorage(targetEditor)
getAllOptions().forEach { option ->
if (option.declaredScope == LOCAL_TO_WINDOW || option.declaredScope == GLOBAL_OR_LOCAL_TO_WINDOW) {
localValues[option.name] = getWindowLocalOptionValue(option, sourceEditor)
}
}
}
private fun resetLocalToWindowOptions(editor: VimEditor) = initialiseLocalToWindowOptions(editor)
private fun initialiseLocalToWindowOptions(editor: VimEditor) {
val localValues = getWindowLocalOptionStorage(editor)
getAllOptions().forEach { option ->
if (option.declaredScope == LOCAL_TO_WINDOW) {
// Remember that this global value is per-window and should be initialised first
localValues[option.name] = getGlobalOptionValue(option, editor)
}
else if (option.declaredScope == GLOBAL_OR_LOCAL_TO_WINDOW) {
localValues[option.name] = option.unsetValue
}
}
}
override fun <T : VimDataType> getOptionValue(option: Option<T>, scope: OptionAccessScope): T = when (scope) {
is OptionAccessScope.EFFECTIVE -> getEffectiveOptionValue(option, scope.editor)
is OptionAccessScope.LOCAL -> getLocalOptionValue(option, scope.editor)
is OptionAccessScope.GLOBAL -> getGlobalOptionValue(option, scope.editor)
}
override fun <T : VimDataType> setOptionValue(option: Option<T>, scope: OptionAccessScope, value: T) {
option.checkIfValueValid(value, value.asString())
when (scope) {
is OptionAccessScope.EFFECTIVE -> setEffectiveOptionValue(option, scope.editor, value)
is OptionAccessScope.LOCAL -> setLocalOptionValue(option, scope.editor, value)
is OptionAccessScope.GLOBAL -> setGlobalOptionValue(option, scope.editor, value)
}
}
override fun <T : VimDataType, TData : Any> getParsedEffectiveOptionValue(
option: Option<T>,
editor: VimEditor?,
provider: (T) -> TData,
): TData {
// TODO: We can't correctly clear global-local options
// We have to cache global-local values locally, because they can be set locally. But if they're not overridden
// locally, we would cache a global value per-window. When the global value is changed with OptionScope.GLOBAL, we
// are unable to clear the per-window cached value, so windows would end up with stale cached (global) values.
check(option.declaredScope != GLOBAL_OR_LOCAL_TO_WINDOW
&& option.declaredScope != GLOBAL_OR_LOCAL_TO_BUFFER
) { "Global-local options cannot currently be cached" }
val cachedValues = if (option.declaredScope == GLOBAL) {
globalParsedValues
}
else {
check(editor != null) { "Editor must be supplied for local options" }
getParsedEffectiveOptionStorage(option, editor)
}
// Unless the user is calling this method multiple times with different providers, we can be confident this cast
// will succeed. Editor will only be null with global options, so it's safe to use null
@Suppress("UNCHECKED_CAST")
return cachedValues.getOrPut(option.name) {
provider(getOptionValue(option, if (editor == null) OptionAccessScope.GLOBAL(null) else OptionAccessScope.EFFECTIVE(editor)))
} as TData
}
override fun getOption(key: String): Option<VimDataType>? = Options.getOption(key)
override fun getAllOptions(): Set<Option<VimDataType>> = Options.getAllOptions()
override fun resetAllOptions(editor: VimEditor) {
// Reset all options to default values at global and local scope. This will fire any listeners and clear any caches
Options.getAllOptions().forEach { option ->
resetDefaultValue(option, OptionAccessScope.GLOBAL(editor))
when (option.declaredScope) {
GLOBAL -> {}
LOCAL_TO_BUFFER, LOCAL_TO_WINDOW -> resetDefaultValue(option, OptionAccessScope.LOCAL(editor))
GLOBAL_OR_LOCAL_TO_BUFFER, GLOBAL_OR_LOCAL_TO_WINDOW -> {
setOptionValue(option, OptionAccessScope.LOCAL(editor), option.unsetValue)
}
}
}
}
override fun resetAllOptionsForTesting() {
// During testing, this collection is usually empty. Just in case, make sure all editors have default options
injector.editorGroup.localEditors().forEach { resetAllOptions(it) }
resetAllOptions(injector.fallbackWindow)
// Make sure we reset global options even if we don't have any editors. This fires listeners and clears caches
Options.getAllOptions().filter { it.declaredScope == GLOBAL }.forEach { resetDefaultValue(it, OptionAccessScope.GLOBAL(null)) }
// Reset global value of other options manually, without firing listeners or clearing caches. This is safe because
// we only cache values or listen to changes for the effective values of local options (and not global-local). But
// local-to-window options will store global values per-window (which we don't have). So this will have the same
// result as resetDefaultValue but without the asserts for setting a local option without a window.
Options.getAllOptions().filter { it.declaredScope != GLOBAL }.forEach { globalValues[it.name] = it.defaultValue }
}
override fun addOption(option: Option<out VimDataType>) {
Options.addOption(option)
// Initialise the values. Cast away the covariance, because it gets in the way of type inference. We want functions
// that are generic on Option<T> to get `VimDataType` and not `out VimDataType`, which we can't use
@Suppress("UNCHECKED_CAST")
initialiseOptionValues(option as Option<VimDataType>)
}
override fun removeOption(optionName: String) {
Options.removeOption(optionName)
globalOptionListeners.removeAll(optionName)
effectiveOptionValueListeners.removeAll(optionName)
}
override fun <T : VimDataType> addGlobalOptionChangeListener(
option: Option<T>,
listener: GlobalOptionChangeListener
) {
check(option.declaredScope == GLOBAL)
globalOptionListeners.add(option.name, listener)
}
override fun <T : VimDataType> removeGlobalOptionChangeListener(
option: Option<T>,
listener: GlobalOptionChangeListener
) {
globalOptionListeners.remove(option.name, listener)
}
override fun <T : VimDataType> addEffectiveOptionValueChangeListener(
option: Option<T>,
listener: EffectiveOptionValueChangeListener
) {
effectiveOptionValueListeners.add(option.name, listener)
}
override fun <T : VimDataType> removeEffectiveOptionValueChangeListener(
option: Option<T>,
listener: EffectiveOptionValueChangeListener
) {
effectiveOptionValueListeners.remove(option.name, listener)
}
final override fun <T : VimDataType> overrideDefaultValue(option: Option<T>, newDefaultValue: T) {
option.overrideDefaultValue(newDefaultValue)
}
// We can pass null as the editor because we are only accessing global options
override fun getGlobalOptions(): GlobalOptions = GlobalOptions(OptionAccessScope.GLOBAL(null))
override fun getEffectiveOptions(editor: VimEditor): EffectiveOptions = EffectiveOptions(OptionAccessScope.EFFECTIVE(editor))
// We can't use StrictMode.assert because it checks an option, which calls into VimOptionGroupBase...
private fun strictModeAssert(condition: Boolean, message: String) {
if (globalValues[Options.ideastrictmode.name]?.asBoolean() == true && !condition) {
error(message)
}
}
private fun initialiseOptionValues(option: Option<VimDataType>) {
// Initialise the values for a new option. Note that we don't call setOptionValue to avoid calling getOptionValue
// in get a non-existent old value to pass to any listeners
globalValues[option.name] = option.defaultValue
injector.editorGroup.localEditors().forEach { editor ->
when (option.declaredScope) {
GLOBAL -> doSetGlobalOptionValue(option, option.defaultValue)
LOCAL_TO_BUFFER -> doSetBufferLocalOptionValue(option, editor, option.defaultValue)
LOCAL_TO_WINDOW -> doSetWindowLocalOptionValue(option, editor, option.defaultValue)
GLOBAL_OR_LOCAL_TO_BUFFER -> doSetBufferLocalOptionValue(option, editor, option.unsetValue)
GLOBAL_OR_LOCAL_TO_WINDOW -> doSetWindowLocalOptionValue(option, editor, option.unsetValue)
}
}
}
private fun getPerWindowGlobalOptionStorage(editor: VimEditor) =
injector.vimStorageService.getOrPutWindowData(editor, perWindowGlobalOptionsKey) { mutableMapOf() }
private fun <T : VimDataType> getGlobalOptionValue(option: Option<T>, editor: VimEditor?): T {
val values = if (option.declaredScope == LOCAL_TO_WINDOW) {
check(editor != null) { "Editor must be provided for local options" }
getPerWindowGlobalOptionStorage(editor)
}
else {
globalValues
}
// We set the value via Option<T> so it's safe to cast to T. But note that the value might be null because we don't
// explicitly populate global option values in the same way we do local options
@Suppress("UNCHECKED_CAST")
return values[option.name] as? T ?: option.defaultValue
}
private fun <T : VimDataType> setGlobalOptionValue(option: Option<T>, editor: VimEditor?, value: T) {
val changed = if (option.declaredScope == LOCAL_TO_WINDOW) {
check(editor != null) { "Editor must be provided for local options" }
doSetPerWindowGlobalOptionValue(option, editor, value)
}
else {
doSetGlobalOptionValue(option, value)
}
when (option.declaredScope) {
GLOBAL -> if (changed) {
onGlobalOptionValueChanged(option)
onGlobalOptionEffectiveValueChanged(option)
}
LOCAL_TO_BUFFER, LOCAL_TO_WINDOW -> { /* Setting global value of a local option. No need to notify anyone */ }
GLOBAL_OR_LOCAL_TO_BUFFER -> onGlobalLocalToBufferOptionGlobalValueChanged(option)
GLOBAL_OR_LOCAL_TO_WINDOW -> onGlobalLocalToWindowOptionGlobalValueChanged(option)
}
}
private fun <T : VimDataType> doSetGlobalOptionValue(option: Option<T>, value: T): Boolean {
val oldValue = globalValues[option.name]
if (oldValue != value) {
globalValues[option.name] = value
globalParsedValues.remove(option.name)
return true
}
return false
}
private fun <T : VimDataType> doSetPerWindowGlobalOptionValue(option: Option<T>, editor: VimEditor, value: T): Boolean {
val values = getPerWindowGlobalOptionStorage(editor)
val oldValue = values[option.name]
if (oldValue != value) {
values[option.name] = value
return true
}
return false
}
/**
* Get the effective value of the option for the given editor. This is the equivalent of `:set {option}?`
*
* For local-to-window and local-to-buffer options, this returns the local value. For global options, it returns the
* global value. For global-local options, it returns the local value if set, and the global value if not.
*/
private fun <T : VimDataType> getEffectiveOptionValue(option: Option<T>, editor: VimEditor) =
when (option.declaredScope) {
GLOBAL -> getGlobalOptionValue(option, editor)
LOCAL_TO_BUFFER -> getBufferLocalOptionValue(option, editor)
LOCAL_TO_WINDOW -> getWindowLocalOptionValue(option, editor)
GLOBAL_OR_LOCAL_TO_BUFFER -> {
tryGetBufferLocalOptionValue(option, editor).takeUnless { it == option.unsetValue }
?: getGlobalOptionValue(option, editor)
}
GLOBAL_OR_LOCAL_TO_WINDOW -> {
tryGetWindowLocalOptionValue(option, editor).takeUnless { it == option.unsetValue }
?: getGlobalOptionValue(option, editor)
}
}
/**
* Set the effective value of the option. This is the equivalent of `:set`
*
* For local-to-buffer and local-to-window options, this function will set the local value of the option. It also sets
* the global value (so that we remember the most recently set value for initialising new windows). For global
* options, this function will also set the global value. For global-local, this function will always set the global
* value, and if the local value is set, it will unset it for string values, and copy the global value for
* number-based options (including toggle options).
*/
private fun <T : VimDataType> setEffectiveOptionValue(option: Option<T>, editor: VimEditor, value: T) {
when (option.declaredScope) {
GLOBAL -> if (doSetGlobalOptionValue(option, value)) {
onGlobalOptionValueChanged(option)
onGlobalOptionEffectiveValueChanged(option)
}
LOCAL_TO_BUFFER -> if (doSetBufferLocalOptionValue(option, editor, value)) {
doSetGlobalOptionValue(option, value)
onBufferLocalOptionEffectiveValueChanged(option, editor)
}
LOCAL_TO_WINDOW -> if (doSetWindowLocalOptionValue(option, editor, value)) {
doSetPerWindowGlobalOptionValue(option, editor, value)
onWindowLocalOptionEffectiveValueChanged(option, editor)
}
GLOBAL_OR_LOCAL_TO_BUFFER -> {
if (tryGetBufferLocalOptionValue(option, editor) != option.unsetValue) {
// Number based options (including boolean) get a copy of the global value. String based options get unset
doSetBufferLocalOptionValue(
option,
editor,
if (option is NumberOption || option is ToggleOption) value else option.unsetValue
)
}
doSetGlobalOptionValue(option, value)
onGlobalLocalToBufferOptionEffectiveValueChanged(option, editor)
}
GLOBAL_OR_LOCAL_TO_WINDOW -> {
if (tryGetWindowLocalOptionValue(option, editor) != option.unsetValue) {
// Number based options (including boolean) get a copy of the global value. String based options get unset
doSetWindowLocalOptionValue(
option,
editor,
if (option is NumberOption || option is ToggleOption) value else option.unsetValue
)
}
doSetGlobalOptionValue(option, value)
onGlobalLocalToWindowOptionEffectiveValueChanged(option, editor)
}
}
}
private fun <T : VimDataType> getLocalOptionValue(option: Option<T>, editor: VimEditor) =
when (option.declaredScope) {
GLOBAL -> getGlobalOptionValue(option, editor)
LOCAL_TO_BUFFER -> getBufferLocalOptionValue(option, editor)
LOCAL_TO_WINDOW -> getWindowLocalOptionValue(option, editor)
GLOBAL_OR_LOCAL_TO_BUFFER -> {
tryGetBufferLocalOptionValue(option, editor).also {
strictModeAssert(it != null, "Global local value is missing: ${option.name}")
} ?: option.unsetValue
}
GLOBAL_OR_LOCAL_TO_WINDOW -> {
tryGetWindowLocalOptionValue(option, editor).also {
strictModeAssert(it != null, "Global local value is missing: ${option.name}")
} ?: option.unsetValue
}
}
/**
* Set the option explicitly at local scope. This is the equivalent of `:setlocal`
*
* This will always set the local option value, even for global-local options (global options obviously only have a
* global value).
*/
private fun <T : VimDataType> setLocalOptionValue(option: Option<T>, editor: VimEditor, value: T) {
when (option.declaredScope) {
GLOBAL -> if (doSetGlobalOptionValue(option, value)) {
onGlobalOptionValueChanged(option)
onGlobalOptionEffectiveValueChanged(option)
}
LOCAL_TO_BUFFER, GLOBAL_OR_LOCAL_TO_BUFFER -> if (doSetBufferLocalOptionValue(option, editor, value)) {
onBufferLocalOptionEffectiveValueChanged(option, editor)
}
LOCAL_TO_WINDOW, GLOBAL_OR_LOCAL_TO_WINDOW -> if (doSetWindowLocalOptionValue(option, editor, value)) {
onWindowLocalOptionEffectiveValueChanged(option, editor)
}
}
}
private fun getBufferLocalOptionStorage(editor: VimEditor) =
injector.vimStorageService.getOrPutBufferData(editor, localOptionsKey) { mutableMapOf() }
private fun <T : VimDataType> doSetBufferLocalOptionValue(option: Option<T>, editor: VimEditor, value: T): Boolean {
val values = getBufferLocalOptionStorage(editor)
val oldValue = values[option.name]
if (oldValue != value) {
values[option.name] = value
getParsedEffectiveOptionStorage(option, editor).remove(option.name)
return true
}
return false
}
private fun <T : VimDataType> getBufferLocalOptionValue(option: Option<T>, editor: VimEditor): T {
check(option.declaredScope == LOCAL_TO_BUFFER || option.declaredScope == GLOBAL_OR_LOCAL_TO_BUFFER)
// This should never return null, because we initialise local options when initialising the editor, even when adding
// options dynamically, e.g. registering an extension. We fall back to global option, just in case
return tryGetBufferLocalOptionValue(option, editor).also {
strictModeAssert(it != null, "Buffer local option value is missing: ${option.name}")
} ?: getGlobalOptionValue(option, editor)
}
private fun <T : VimDataType> tryGetBufferLocalOptionValue(option: Option<T>, editor: VimEditor): T? {
val values = getBufferLocalOptionStorage(editor)
// We set the value via Option<T> so it's safe to cast to T
@Suppress("UNCHECKED_CAST")
return values[option.name] as? T
}
private fun getWindowLocalOptionStorage(editor: VimEditor) =
injector.vimStorageService.getOrPutWindowData(editor, localOptionsKey) { mutableMapOf() }
private fun <T : VimDataType> doSetWindowLocalOptionValue(option: Option<T>, editor: VimEditor, value: T): Boolean {
val values = getWindowLocalOptionStorage(editor)
val oldValue = values[option.name]
if (oldValue != value) {
values[option.name] = value
getParsedEffectiveOptionStorage(option, editor).remove(option.name)
return true
}
return false
}
private fun <T : VimDataType> getWindowLocalOptionValue(option: Option<T>, editor: VimEditor): T {
check(option.declaredScope == LOCAL_TO_WINDOW || option.declaredScope == GLOBAL_OR_LOCAL_TO_WINDOW)
// This should never return null, because we initialise local options when initialising the editor, even when adding
// options dynamically, e.g. registering an extension. We fall back to global option, just in case
val value = tryGetWindowLocalOptionValue(option, editor)
strictModeAssert(value != null, "Window local option value is missing: ${option.name}")
return value ?: getGlobalOptionValue(option, editor)
}
private fun <T : VimDataType> tryGetWindowLocalOptionValue(option: Option<T>, editor: VimEditor): T? {
val values = getWindowLocalOptionStorage(editor)
// We set the value via Option<T> so it's safe to cast to T
@Suppress("UNCHECKED_CAST")
return values[option.name] as? T
}
private fun <T : VimDataType> onGlobalOptionValueChanged(option: Option<T>) {
globalOptionListeners[option.name]?.forEach {
it.onGlobalOptionChanged()
}
}
private inline fun <T : VimDataType> onEffectiveValueChanged(
option: Option<T>,
editorsProvider: () -> Collection<VimEditor>,
) {
val listeners = effectiveOptionValueListeners[option.name] ?: return
val editors = editorsProvider()
listeners.forEach { listener ->
editors.forEach { listener.onEffectiveValueChanged(it) }
}
}
/**
* Notify all editors that a global option value has changed
*
* This will call the listener for all open editors. It will also call the listener with a `null` editor, to provide
* for non-editor related callbacks. E.g. updating `'showcmd'`, tracking default register for `'clipboard'`, etc.
*/
private fun <T : VimDataType> onGlobalOptionEffectiveValueChanged(option: Option<T>) {
onEffectiveValueChanged(option) { injector.editorGroup.localEditors() }
}
/**
* Notify all editors for the current buffer that a local-to-buffer option's effective value has changed
*/
private fun <T : VimDataType> onBufferLocalOptionEffectiveValueChanged(option: Option<T>, editor: VimEditor) {
onEffectiveValueChanged(option) { injector.editorGroup.localEditors(editor.document) }
}
/**
* Notify the given editor that a local-to-window option's effective value has changed
*/
private fun <T : VimDataType> onWindowLocalOptionEffectiveValueChanged(option: Option<T>, editor: VimEditor) {
onEffectiveValueChanged(option) { listOf(editor) }
}
/**
* Notify the affected editors that a global-local local to buffer option's effective value has changed.
*
* When a global-local option's effective value is changed with `:set`, the global value is updated, and copied to the
* local value. This means we need to notify all editors that are using the global value that it has changed, and skip
* any editors that have the value overridden. The editors associated with the current buffer are also notified (their
* local value has been updated).
*
* Note that we make no effort to minimise change notifications for global-local, as the logic is complex enough.
*/
private fun <T : VimDataType> onGlobalLocalToBufferOptionEffectiveValueChanged(option: Option<T>, editor: VimEditor) {
onEffectiveValueChanged(option) {
mutableListOf<VimEditor>().also { editors ->
editors.addAll(injector.editorGroup.localEditors().filter { isUnsetValue(option, it) })
editors.addAll(injector.editorGroup.localEditors(editor.document).filter { !isUnsetValue(option, it) })
}
}
}
private fun <T : VimDataType> onGlobalLocalToBufferOptionGlobalValueChanged(option: Option<T>) {
onEffectiveValueChanged(option) { injector.editorGroup.localEditors().filter { isUnsetValue(option, it) } }
}
/**
* Notify the affected editors that a global-local local to window option's effective value has changed.
*
* When a global-local option's effective value is changed with `:set`, the global value is updated, and copied to the
* local value. This means we need to notify all editors that are using the global value that it has changed, and skip
* any editors that have the value overridden. The editors associated with the current buffer are also notified (their
* local value has been updated).
*
* Note that we make no effort to minimise change notifications for global-local, as the logic is complex enough.
*/
private fun <T : VimDataType> onGlobalLocalToWindowOptionEffectiveValueChanged(option: Option<T>, editor: VimEditor) {
onEffectiveValueChanged(option) {
mutableListOf<VimEditor>().also { editors ->
editors.addAll(injector.editorGroup.localEditors().filter { isUnsetValue(option, it) })
if (!isUnsetValue(option, editor)) {
editors.add(editor)
}
}
}
}
private fun <T : VimDataType> onGlobalLocalToWindowOptionGlobalValueChanged(option: Option<T>) {
onEffectiveValueChanged(option) { injector.editorGroup.localEditors().filter { isUnsetValue(option, it) } }
}
private fun getParsedEffectiveOptionStorage(option: Option<out VimDataType>, editor: VimEditor): MutableMap<String, Any> {
return when (option.declaredScope) {
LOCAL_TO_WINDOW, GLOBAL_OR_LOCAL_TO_WINDOW -> {
injector.vimStorageService.getOrPutWindowData(editor, parsedEffectiveValueKey) { mutableMapOf() }
}
LOCAL_TO_BUFFER, GLOBAL_OR_LOCAL_TO_BUFFER -> {
injector.vimStorageService.getOrPutBufferData(editor, parsedEffectiveValueKey) { mutableMapOf() }
}
else -> {
throw IllegalStateException("Unexpected option declared scope for parsed effective storage: ${option.name}")
}
}
}
}
private class MultiSet<K, V> : HashMap<K, MutableSet<V>>() {
fun add(key: K, value: V) {
getOrPut(key) { mutableSetOf() }.add(value)
}
fun remove(key: K, value: V) {
this[key]?.remove(value)
}
fun removeAll(key: K) {
remove(key)
}
} | 5 | Kotlin | 723 | 8,335 | cc971eb2dfa24ef333059d5fd23211124d45b828 | 31,298 | ideavim | MIT License |
app/src/main/java/com/example/capitalcityquizktx/data/network/register/UserManagementService.kt | JoseGbel | 236,566,370 | false | null | package com.example.capitalcityquizktx.data.network.register
import com.example.capitalcityquizktx.data.models.user.UserDetailsSchema
import com.example.capitalcityquizktx.data.models.user.UserExistenceSchema
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.Query
interface UserManagementService {
@POST("users/sign-up")
suspend fun createUser(@Body body: UserDetailsSchema) : Boolean
@GET
fun findByUsername(username: String) : Call<UserDetailsSchema>
@GET("users/verify")
suspend fun verifyUserIsNotInDatabase(@Query("username") username: String,
@Query("email") email: String) : UserExistenceSchema
}
| 0 | Kotlin | 0 | 0 | def161ef4a080dc388b09b0faa9dc648bae81690 | 742 | capital-city-quiz | Apache License 2.0 |
02-Android/2018MovilesGR2/app/src/main/java/com/example/usrdel/a2018movilesgr2/SegundoFragment.kt | 2018-B-GR2-AplicacionesMoviles | 151,628,031 | false | {"JavaScript": 444666, "HTML": 422568, "Kotlin": 131420, "CSS": 1150} | package com.example.usrdel.a2018movilesgr2
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
class SegundoFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater!!.inflate(
R.layout.tercer_fragmento, // XML A USARSE
container,
false
)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
}
}
| 0 | JavaScript | 0 | 0 | bc8e3f2eeee00c0acd9341b090c74ee3f4648635 | 702 | Velasco-Yepez-Andres-David | MIT License |
common/src/main/kotlin/org/jetbrains/research/common/pyflowgraph/NodeNamesUtils.kt | JetBrains-Research | 281,132,580 | false | null | package org.jetbrains.research.common.pyflowgraph
import com.intellij.psi.util.elementType
import com.jetbrains.python.psi.*
fun PyElement.getFullName(): String =
when (this) {
is PyFunction, is PyNamedParameter -> this.name ?: ""
is PyReferenceExpression, is PyTargetExpression -> {
var fullName = (this as PyQualifiedExpression).referencedName
var currentNode = this.qualifier
while (currentNode is PyReferenceExpression
|| currentNode is PyCallExpression && currentNode.callee is PyReferenceExpression
) {
if (currentNode is PyReferenceExpression) {
fullName = currentNode.referencedName + "." + fullName
currentNode = currentNode.qualifier
} else {
// TODO: add argument reference name inside parenthesis?
fullName = (currentNode as PyCallExpression).callee?.name + "()." + fullName
currentNode = (currentNode.callee as PyReferenceExpression).qualifier
}
}
fullName ?: ""
}
is PySubscriptionExpression -> {
val operand = this.operand.getFullName()
val index = this.indexExpression?.getFullName() ?: ""
"$operand[$index]"
}
is PySliceExpression -> {
val operand = this.operand.getFullName()
val sliceItems = arrayListOf<String>()
// FIXME: getNodeFullName for expressions
this.sliceItem?.lowerBound?.let { sliceItems.add(it.getFullName()) }
this.sliceItem?.stride?.let { sliceItems.add(it.getFullName()) }
this.sliceItem?.upperBound?.let { sliceItems.add(it.getFullName()) }
"$operand[${sliceItems.joinToString(":")}]"
}
is PyLiteralExpression -> "."
is PyEmptyExpression -> ""
else -> this.toString()
}
fun PyElement.getType(): Int = this.elementType?.index?.toInt() ?: -1
fun PyElement.getKey(): String =
when (this) {
is PyFunction, is PyNamedParameter -> this.name ?: ""
is PyReferenceExpression, is PyTargetExpression ->
(this as PyQualifiedExpression).asQualifiedName()?.toString() ?: ""
else -> throw IllegalArgumentException()
}
fun PyElement.getShortName(): String =
when (this) {
is PyNamedParameter, is PyFunction -> this.name ?: ""
is PyReferenceExpression, is PyTargetExpression -> (this as PyQualifiedExpression).referencedName ?: ""
else -> throw IllegalArgumentException()
}
fun PyElement.getOperationName(): String =
when (this) {
is PyAugAssignmentStatement -> {
when (this.operation?.text) {
"+=" -> "add"
"-=" -> "sub"
"*=" -> "mult"
"/=" -> "div"
"%=" -> "mod"
"**=" -> "pow"
">>=" -> "rshift"
"<<-" -> "lshift"
"&=" -> "bitand"
"|=" -> "bitor"
"^=" -> "bitxor"
else -> throw NotImplementedError("Unsupported operation type")
}
}
is PyBinaryExpression -> {
when (this.psiOperator?.text) {
"+" -> "add"
"-" -> "sub"
"*" -> "mult"
"**" -> "pow"
"/" -> "div"
"%" -> "mod"
"and" -> "and"
"or" -> "or"
">" -> "Gt"
">=" -> "GtE"
"<" -> "Lt"
"<=" -> "LtE"
"==" -> "Eq"
"!=" -> "NotEq"
"in" -> "In"
"not in" -> "NotIn"
"is" -> "Is"
"is not" -> "IsNot"
"not" -> "NotIn"
else -> throw NotImplementedError("Unsupported operation type")
}
}
is PyPrefixExpression -> {
when (this.operator.toString()) {
"Py:MINUS" -> "USub"
"Py:PLUS" -> "UAdd"
"Py:NOT_KEYWORD" -> "Not"
else -> throw NotImplementedError("Unsupported operation type")
}
}
else -> {
throw NotImplementedError("Unsupported operation this")
}
}
fun PySequenceExpression.getCollectionLabel(): String =
when (this) {
is PyListLiteralExpression -> "List"
is PyTupleExpression -> "Tuple"
is PySetLiteralExpression -> "Set"
is PyDictLiteralExpression -> "Dict"
else -> throw IllegalArgumentException()
}
class GraphBuildingException(message: String) : Exception(message) | 0 | Kotlin | 1 | 8 | ad189dfd3526633d6075754658af819872bd32cd | 4,748 | revizor | Apache License 2.0 |
lib_base/src/main/java/com/example/lib_base/room/entity/WeatherDayEntity.kt | TReturn | 870,739,949 | false | {"Kotlin": 212586, "Java": 134940} | package com.example.lib_base.room.entity
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
/**
* @CreateDate: 2022/3/15 3:28 下午
* @Author: 青柠
* @Description:
*/
@Entity(tableName = "weather_day")
class WeatherDayEntity() {
@PrimaryKey(autoGenerate = true)
var id: Int = 0
var time: Long = 0
//城市名称
var cityName: String = ""
//天气数据,使用String存储
var dayData: String = ""
@Ignore
constructor(
cityName: String,
dayData: String
) : this() {
time = System.currentTimeMillis()
this.cityName = cityName
this.dayData = dayData
}
} | 0 | Kotlin | 0 | 0 | 4ff7517fc25633e55625d62cd5e9d057f89fd7ad | 653 | JellyWeather | Apache License 2.0 |
common/src/main/kotlin/org/stardustmodding/interstellar/api/registry/RegistryUtil.kt | StardustModding | 703,282,326 | false | {"Kotlin": 83772, "Shell": 5565, "Java": 2839, "GLSL": 2679} | package org.stardustmodding.interstellar.api.registry
import com.google.common.collect.ImmutableList
import com.mojang.serialization.Lifecycle
import net.minecraft.core.DefaultedMappedRegistry
import net.minecraft.core.DefaultedRegistry
import net.minecraft.core.Holder
import net.minecraft.core.MappedRegistry
import net.minecraft.core.Registry
import net.minecraft.resources.ResourceKey
import net.minecraft.resources.ResourceLocation
import org.stardustmodding.interstellar.impl.Interstellar.LOGGER
object RegistryUtil {
@JvmStatic
fun <T> unregister(registry: Registry<T>, key: ResourceLocation) {
if (registry.containsKey(key)) {
if (registry is MappedRegistry<T>) {
if (registry is DefaultedRegistry<*>) {
require(registry.defaultKey != key) { "Cannot remove default value in registry!" }
}
val type = registry.byLocation[key]!!.value()
val byId = registry.byId
if (byId.size <= registry.toId.getInt(type)) {
LOGGER.warn("ID mismatch in registry '{}'", registry.key())
}
registry.toId.removeInt(type)
var success = false
for (i in byId.indices) {
val reference = byId[i]
if (reference != null) {
if (reference.key().location() == key) {
byId[i] = null
success = true
var max = 0
for (i1 in byId.indices) {
max = if (byId[i1] != null) i1 else max
}
byId.size(max + 1)
registry.nextId = max
break
}
}
}
assert(success)
registry.byLocation.remove(key)
registry.byKey.remove(ResourceKey.create(registry.key(), key))
registry.byValue.remove(type)
registry.lifecycles.remove(type)
val base = Lifecycle.stable()
for (value in registry.lifecycles.values) {
base.add(value)
}
registry.registryLifecycle = base
for (holderSet in registry.tags.values) {
val list = ImmutableList.builder<Holder<T>>()
for (content in holderSet.contents) {
if (!content.`is`(key)) list.add(content)
}
holderSet.contents = list.build()
}
registry.byValue.remove(type)
registry.holdersInOrder = null
}
} else {
LOGGER.warn("Tried to remove non-existent key {}", key)
}
}
@JvmStatic
fun <T> registerUnfreeze(registry: Registry<T>, id: ResourceLocation, value: T): Holder.Reference<T> {
if (!registry.containsKey(id)) {
if (registry.javaClass == MappedRegistry::class.java || registry.javaClass == DefaultedMappedRegistry::class.java) {
val mapped = registry as MappedRegistry<T>
val frozen = registry.frozen
if (frozen) registry.frozen = false
val ref = mapped.register(ResourceKey.create(registry.key(), id), value!!, Lifecycle.stable())
if (frozen) registry.freeze()
checkNotNull(registry.byId[registry.toId.getInt(value)])
return ref
} else {
throw IllegalStateException("Non-vanilla '" + registry.key().location() + "' registry! " + registry.javaClass.name)
}
} else {
LOGGER.warn("Tried to add pre-existing key$id")
return registry.getHolderOrThrow(ResourceKey.create(registry.key(), id))
}
}
fun <T> registerUnfreezeExact(
registry: Registry<T?>,
rawId: Int,
id: ResourceLocation,
value: T
): Holder.Reference<T?> {
if (!registry.containsKey(id)) {
if (registry.javaClass == MappedRegistry::class.java || registry.javaClass == DefaultedMappedRegistry::class.java) {
val mapped = registry as MappedRegistry<T?>
val frozen = registry.frozen
if (frozen) registry.frozen = false
val ref = mapped.registerMapping(rawId, ResourceKey.create(registry.key(), id), value!!, Lifecycle.stable())
if (frozen) registry.freeze()
return ref
} else {
throw IllegalStateException("Non-vanilla '" + registry.key().location() + "' registry! " + registry.javaClass.name)
}
} else {
LOGGER.warn(
"Tried to add pre-existing key $id with raw id $rawId (contains: " + registry.getId(
registry[id]
) + ")"
)
return registry.getHolderOrThrow(ResourceKey.create(registry.key(), id))
}
}
}
| 0 | Kotlin | 1 | 3 | 6185d241e7ceae7ab29f8e344d0c19596ad84b05 | 5,152 | Interstellar | MIT License |
app/src/main/java/dev/josejordan/cubo/MainActivity.kt | mundodigitalpro | 869,121,277 | false | {"Kotlin": 7179} | package dev.josejordan.cubo
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.core.*
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.rotate
import kotlin.math.cos
import kotlin.math.sin
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
RotatingCube()
}
}
}
@Composable
fun RotatingCube() {
var rotationX by remember { mutableStateOf(0f) }
var rotationY by remember { mutableStateOf(0f) }
val infiniteTransition = rememberInfiniteTransition(label = "")
rotationX = infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = 360f,
animationSpec = infiniteRepeatable(
animation = tween(6000, easing = LinearEasing),
repeatMode = RepeatMode.Restart
), label = ""
).value
rotationY = infiniteTransition.animateFloat(
initialValue = 0f,
targetValue = 360f,
animationSpec = infiniteRepeatable(
animation = tween(8000, easing = LinearEasing),
repeatMode = RepeatMode.Restart
), label = ""
).value
Canvas(modifier = Modifier.fillMaxSize()) {
val centerX = size.width / 2
val centerY = size.height / 2
val cubeSize = size.minDimension / 4
val points = listOf(
Point3D(-1f, -1f, -1f), Point3D(1f, -1f, -1f),
Point3D(1f, 1f, -1f), Point3D(-1f, 1f, -1f),
Point3D(-1f, -1f, 1f), Point3D(1f, -1f, 1f),
Point3D(1f, 1f, 1f), Point3D(-1f, 1f, 1f)
).map { it.rotateX(rotationX).rotateY(rotationY) }
.map { Offset(it.x * cubeSize + centerX, it.y * cubeSize + centerY) }
// Dibuja las aristas del cubo
val edges = listOf(
0 to 1, 1 to 2, 2 to 3, 3 to 0, // cara frontal
4 to 5, 5 to 6, 6 to 7, 7 to 4, // cara trasera
0 to 4, 1 to 5, 2 to 6, 3 to 7 // conexiones
)
edges.forEach { (start, end) ->
drawLine(
Color.Blue,
points[start],
points[end],
strokeWidth = 5f
)
}
}
}
data class Point3D(val x: Float, val y: Float, val z: Float) {
fun rotateX(angle: Float): Point3D {
val rad = Math.toRadians(angle.toDouble())
val cosa = cos(rad).toFloat()
val sina = sin(rad).toFloat()
val newY = y * cosa - z * sina
val newZ = y * sina + z * cosa
return Point3D(x, newY, newZ)
}
fun rotateY(angle: Float): Point3D {
val rad = Math.toRadians(angle.toDouble())
val cosa = cos(rad).toFloat()
val sina = sin(rad).toFloat()
val newX = x * cosa - z * sina
val newZ = x * sina + z * cosa
return Point3D(newX, y, newZ)
}
} | 0 | Kotlin | 0 | 0 | 772831f567bd0757fadcd047a36d3fed201f52c4 | 3,209 | cubo | MIT License |
server/transfer/src/main/kotlin/com/evidentdb/server/transfer/types.kt | evidentsystems | 481,373,137 | false | {"Kotlin": 274264, "Makefile": 4528} | package com.evidentdb.server.transfer
import arrow.core.Either
import arrow.core.NonEmptyList
import arrow.core.nonEmptyListOf
import arrow.core.raise.either
import arrow.core.raise.zipOrAccumulate
import com.evidentdb.dto.v1.proto.BatchConstraint.ConstraintCase.*
import com.evidentdb.server.domain_model.*
import com.google.protobuf.Timestamp
import io.cloudevents.protobuf.toTransfer
import java.time.Instant
import com.evidentdb.dto.v1.proto.Batch as ProtoBatch
import com.evidentdb.dto.v1.proto.BatchConstraint as ProtoBatchConstraint
import com.evidentdb.dto.v1.proto.BatchSummary as ProtoBatchSummary
import com.evidentdb.dto.v1.proto.Database as ProtoDatabase
import io.cloudevents.v1.proto.CloudEvent as ProtoCloudEvent
fun Instant.toTimestamp(): Timestamp =
Timestamp.newBuilder()
.setSeconds(epochSecond)
.setNanos(nano)
.build()
fun Database.toTransfer(): ProtoDatabase = ProtoDatabase.newBuilder()
.setName(name.value)
.setRevision(revision.toLong())
.build()
// For returning AcceptedBatch from transaction
fun IndexedBatch.toTransfer(): ProtoBatch = ProtoBatch.newBuilder()
.setDatabase(database.value)
.addAllEvents(events.map { it.event.toTransfer() })
.setTimestamp(timestamp.toTimestamp())
.setBasis(basis.toLong())
.build()
// For fetching BatchSummary for log, etc.
fun Batch.toTransfer(): ProtoBatchSummary = ProtoBatchSummary.newBuilder()
.setDatabase(database.value)
.setBasis(basis.toLong())
.setRevision(revision.toLong())
.setTimestamp(timestamp.toTimestamp())
.build()
fun Event.toTransfer(): ProtoCloudEvent = event.toTransfer()
fun BatchConstraint.toTransfer(): ProtoBatchConstraint {
val builder = ProtoBatchConstraint.newBuilder()
when (this) {
is BatchConstraint.DatabaseMinRevision ->
builder.databaseMinRevisionBuilder.revision = this.revision.toLong()
is BatchConstraint.DatabaseMaxRevision ->
builder.databaseMaxRevisionBuilder.revision = this.revision.toLong()
is BatchConstraint.DatabaseRevisionRange -> {
builder.databaseRevisionRangeBuilder.min = this.min.toLong()
builder.databaseRevisionRangeBuilder.max = this.max.toLong()
}
is BatchConstraint.StreamMinRevision -> {
builder.streamMinRevisionBuilder.stream = this.stream.value
builder.streamMinRevisionBuilder.revision = this.revision.toLong()
}
is BatchConstraint.StreamMaxRevision -> {
builder.streamMaxRevisionBuilder.stream = this.stream.value
builder.streamMaxRevisionBuilder.revision = this.revision.toLong()
}
is BatchConstraint.StreamRevisionRange -> {
builder.streamRevisionRangeBuilder.stream = this.stream.value
builder.streamRevisionRangeBuilder.min = this.min.toLong()
builder.streamRevisionRangeBuilder.max = this.max.toLong()
}
is BatchConstraint.SubjectMinRevision -> {
builder.subjectMinRevisionBuilder.subject = this.subject.value
builder.subjectMinRevisionBuilder.revision = this.revision.toLong()
}
is BatchConstraint.SubjectMaxRevision -> {
builder.subjectMaxRevisionBuilder.subject = this.subject.value
builder.subjectMaxRevisionBuilder.revision = this.revision.toLong()
}
is BatchConstraint.SubjectRevisionRange -> {
builder.subjectRevisionRangeBuilder.subject = this.subject.value
builder.subjectRevisionRangeBuilder.min = this.min.toLong()
builder.subjectRevisionRangeBuilder.max = this.max.toLong()
}
is BatchConstraint.SubjectMinRevisionOnStream -> {
builder.subjectMinRevisionOnStreamBuilder.stream = this.stream.value
builder.subjectMinRevisionOnStreamBuilder.subject = this.subject.value
builder.subjectMinRevisionOnStreamBuilder.revision = this.revision.toLong()
}
is BatchConstraint.SubjectMaxRevisionOnStream -> {
builder.subjectMaxRevisionOnStreamBuilder.stream = this.stream.value
builder.subjectMaxRevisionOnStreamBuilder.subject = this.subject.value
builder.subjectMaxRevisionOnStreamBuilder.revision = this.revision.toLong()
}
is BatchConstraint.SubjectStreamRevisionRange -> {
builder.subjectStreamRevisionRangeBuilder.stream = this.stream.value
builder.subjectStreamRevisionRangeBuilder.subject = this.subject.value
builder.subjectStreamRevisionRangeBuilder.min = this.min.toLong()
builder.subjectStreamRevisionRangeBuilder.max = this.max.toLong()
}
}
return builder.build()
}
fun ProtoBatchConstraint.toDomain(): Either<NonEmptyList<BatchConstraintInvalidation>, BatchConstraint> =
either {
val proto = this@toDomain
when (proto.constraintCase) {
DATABASE_MIN_REVISION ->
BatchConstraint.DatabaseMinRevision(proto.databaseMinRevision.revision.toULong())
DATABASE_MAX_REVISION ->
BatchConstraint.DatabaseMaxRevision(proto.databaseMaxRevision.revision.toULong())
DATABASE_REVISION_RANGE ->
BatchConstraint.DatabaseRevisionRange(
proto.databaseRevisionRange.min.toULong(),
proto.databaseRevisionRange.max.toULong()
).mapLeft { nonEmptyListOf(it) }.bind()
STREAM_MIN_REVISION -> {
val streamName = StreamName(proto.streamMinRevision.stream)
.mapLeft { nonEmptyListOf(it) }
.bind()
BatchConstraint.StreamMinRevision(
streamName,
proto.streamMinRevision.revision.toULong()
)
}
STREAM_MAX_REVISION -> {
val streamName = StreamName(proto.streamMaxRevision.stream)
.mapLeft { nonEmptyListOf(it) }
.bind()
BatchConstraint.StreamMaxRevision(
streamName,
proto.streamMaxRevision.revision.toULong()
)
}
STREAM_REVISION_RANGE -> either {
val streamName = StreamName(proto.streamRevisionRange.stream).bind()
BatchConstraint.StreamRevisionRange(
streamName,
proto.streamRevisionRange.min.toULong(),
proto.streamRevisionRange.max.toULong(),
).bind()
}.mapLeft { nonEmptyListOf(it) }.bind()
SUBJECT_MIN_REVISION -> {
val subjectName = EventSubject(proto.subjectMinRevision.subject)
.mapLeft { nonEmptyListOf(it) }
.bind()
BatchConstraint.SubjectMinRevision(
subjectName,
proto.subjectMinRevision.revision.toULong()
)
}
SUBJECT_MAX_REVISION -> {
val subjectName = EventSubject(proto.subjectMaxRevision.subject)
.mapLeft { nonEmptyListOf(it) }
.bind()
BatchConstraint.SubjectMaxRevision(
subjectName,
proto.subjectMaxRevision.revision.toULong()
)
}
SUBJECT_REVISION_RANGE -> either {
val subjectName = EventSubject(proto.subjectRevisionRange.subject).bind()
BatchConstraint.SubjectRevisionRange(
subjectName,
proto.subjectRevisionRange.min.toULong(),
proto.subjectRevisionRange.max.toULong()
).bind()
}.mapLeft { nonEmptyListOf(it) }.bind()
SUBJECT_MIN_REVISION_ON_STREAM -> zipOrAccumulate(
{ StreamName(proto.subjectMinRevisionOnStream.stream).bind() },
{ EventSubject(proto.subjectMinRevisionOnStream.subject).bind() }
) { streamName, subject ->
BatchConstraint.SubjectMinRevisionOnStream(
streamName,
subject,
proto.subjectMinRevisionOnStream.revision.toULong(),
)
}
SUBJECT_MAX_REVISION_ON_STREAM -> zipOrAccumulate(
{ StreamName(proto.subjectMaxRevisionOnStream.stream).bind() },
{ EventSubject(proto.subjectMaxRevisionOnStream.subject).bind() }
) { streamName, subject ->
BatchConstraint.SubjectMaxRevisionOnStream(
streamName,
subject,
proto.subjectMaxRevisionOnStream.revision.toULong(),
)
}
SUBJECT_STREAM_REVISION_RANGE -> zipOrAccumulate(
{ StreamName(proto.subjectStreamRevisionRange.stream).bind() },
{ EventSubject(proto.subjectStreamRevisionRange.subject).bind() }
) { streamName, subject ->
BatchConstraint.SubjectStreamRevisionRange(
streamName,
subject,
proto.subjectStreamRevisionRange.min.toULong(),
proto.subjectStreamRevisionRange.max.toULong(),
).mapLeft { nonEmptyListOf(it) }.bind()
}
CONSTRAINT_NOT_SET, null ->
throw IllegalArgumentException("constraintCase enum cannot be null")
}
}
| 25 | Kotlin | 1 | 5 | c12933391af87eaea2f1e209f2dfb6b736359f7e | 9,523 | evident-db | Apache License 2.0 |
src/medium/_198HouseRobber.kt | ilinqh | 390,190,883 | false | {"Kotlin": 369834, "Java": 31849} | package medium
class _198HouseRobber {
class Solution {
fun rob(nums: IntArray): Int {
if (nums.isEmpty()) {
return 0
}
val length = nums.size
if (length == 1) {
return nums[0]
}
var first = nums[0]
var second = Math.max(first, nums[1])
for (i in 2 until length) {
val temp = second
second = Math.max(second, first + nums[i])
first = temp
}
return second
}
}
} | 0 | Kotlin | 0 | 0 | 2ebe91593ee55c0250ce34b13a25fa0d7508e4e3 | 585 | AlgorithmsProject | Apache License 2.0 |
src/main/kotlin/org/wagham/db/scopes/KabotDBLabelScope.kt | kaironbot | 540,862,397 | false | {"Kotlin": 176625} | package org.wagham.db.scopes
import com.mongodb.client.model.UpdateOptions
import org.litote.kmongo.coroutine.CoroutineCollection
import org.litote.kmongo.eq
import org.wagham.db.KabotMultiDBClient
import org.wagham.db.enums.CollectionNames
import org.wagham.db.enums.LabelType
import org.wagham.db.models.embed.Label
import org.wagham.db.utils.isSuccessful
class KabotDBLabelScope(
override val client: KabotMultiDBClient
) : KabotDBScope<Label> {
override val collectionName = CollectionNames.LABELS.stringValue
override fun getMainCollection(guildId: String): CoroutineCollection<Label> =
client.getGuildDb(guildId).getCollection(collectionName)
suspend fun createOrUpdateLabel(guildId: String, label: Label) =
getMainCollection(guildId)
.updateOne(
Label::id eq label.id,
label,
UpdateOptions().upsert(true)
).isSuccessful()
fun getLabels(guildId: String, labelType: LabelType? = null) =
getMainCollection(guildId).find(labelType?.let { Label::type eq it }).toFlow()
suspend fun getLabel(guildId: String, labelId: String) =
getMainCollection(guildId).findOne(Label::id eq labelId)
} | 1 | Kotlin | 0 | 0 | 01095594df248c29e30778f102dae8d162d260e2 | 1,222 | kabot-db-connector | MIT License |
.legacy/app/src/main/java/com/makentoshe/booruchan/screen/posts/view/PostsUiToolbar.kt | Makentoshe | 147,361,920 | false | null | package com.makentoshe.booruchan.screen.posts.view
import android.graphics.PorterDuff
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.RelativeLayout
import com.makentoshe.booruchan.R
import com.makentoshe.booruchan.style
import com.makentoshe.booruchan.style.getColorFromStyle
import org.jetbrains.anko.*
class PostsUiToolbar : AnkoComponent<ViewGroup> {
override fun createView(ui: AnkoContext<ViewGroup>): View = with(ui.owner) {
themedRelativeLayout(style.toolbar) {
elevation = dip(4).toFloat()
createToolbarView()
createDrawerIcon().also { it.visibility = View.GONE }
createSearchIcon()
}
}
private fun _RelativeLayout.createSearchIcon() = themedFrameLayout(style.toolbar) {
id = R.id.posts_toolbar_search
lparams(dip(56), dip(56))
themedImageView(style.toolbar) {
setImageResource(R.drawable.avd_cross_magnify)
setColorFilter(getColorFromStyle(android.R.attr.textColorPrimary), PorterDuff.Mode.SRC_ATOP)
}.lparams(dip(24), dip(24)) {
gravity = Gravity.CENTER
}
}.lparams(dip(56), dip(56)) {
addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
addRule(RelativeLayout.CENTER_VERTICAL)
}
private fun _RelativeLayout.createDrawerIcon() = themedFrameLayout(style.toolbar) {
id = R.id.booru_toolbar_drawermenu
themedImageView(style.toolbar) {
setImageResource(R.drawable.ic_menu_vector)
setColorFilter(getColorFromStyle(android.R.attr.textColorPrimary), PorterDuff.Mode.SRC_ATOP)
}.lparams(dip(24), dip(24)) {
gravity = Gravity.CENTER
}
}.lparams(dip(56), dip(56)) {
addRule(RelativeLayout.ALIGN_PARENT_LEFT)
addRule(RelativeLayout.CENTER_VERTICAL)
}
private fun _RelativeLayout.createToolbarView() = themedToolbar(style.toolbar) {
id = R.id.booru_toolbar
}.lparams(width = matchParent) {
alignWithParent = true
rightOf(R.id.booru_toolbar_drawermenu)
}
} | 0 | Kotlin | 1 | 6 | d0f40fb8011967e212df1f21beb43e4c4ec03356 | 2,117 | Booruchan | Apache License 2.0 |
kotlinpoet/main/kotlin/com/meowbase/toolkit/kotlinpoet/declaration/Code.kt | siylt007 | 336,180,880 | true | {"Kotlin": 1405824, "Java": 474434, "Dart": 14190, "HTML": 70} | @file:Suppress("OVERRIDE_BY_INLINE")
package com.meowbase.toolkit.kotlinpoet.declaration
import com.meowbase.toolkit.kotlinpoet.annotation.DslApi
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.ParameterSpec
typealias DeclareCode = Coding.() -> Unit
@DslApi
interface Coding {
/**
* 添加代码语句
*
* @param format 需要格式化的语句
* @param args 格式化参数
* @param line 如果为 true, 则代表这是一行语句,在尾端将换行
*/
fun add(format: String, vararg args: Any?, line: Boolean = true)
/** 添加代码块 [codeBlock] */
fun add(codeBlock: CodeBlock)
/**
* 添加一个缩进后的代码块
*
* @param coding 缩进的代码块
*/
fun indent(coding: DeclareCode)
/**
* 创建一个流式 Api
*
* @param controlFlow 控制流开始的语句
* @param args 格式化 [controlFlow]
* @param coding 这个控制流内的代码
* @return see [FlowDeclaration]
*/
fun flow(controlFlow: String, vararg args: Any?, coding: DeclareCode): FlowDeclaration
/**
* 创建调用语句
*
* @param target 调用的目标方法名称
* @param declareParameters 声明调用的目标方法的参数
*/
fun call(target: String, declareParameters: DeclareCall)
}
/**
* [ParameterSpec.Builder] 的 DSL 包装器
*
* @author 凛
* @github https://github.com/oh-Rin
* @date 2020/12/12 - 15:31
*/
@DslApi
class CodeDeclaration(
@PublishedApi
internal val builder: CodeBlock.Builder = CodeBlock.builder()
) : SpecDeclaration<CodeBlock>, Coding {
override fun add(format: String, vararg args: Any?, line: Boolean) {
if(line) {
builder.addStatement(format, *args)
} else {
builder.add(format, *args)
}
}
override fun add(codeBlock: CodeBlock) {
builder.add(codeBlock)
}
override fun indent(coding: DeclareCode) {
builder.indent()
coding()
builder.unindent()
}
override inline fun flow(controlFlow: String, vararg args: Any?, coding: DeclareCode): FlowDeclaration {
builder.beginControlFlow(controlFlow, *args)
coding()
builder.endControlFlow()
return FlowDeclaration(this)
}
override inline fun call(target: String, crossinline declareParameters: DeclareCall) {
add("$target(")
indent { CallDeclaration(this@CodeDeclaration).also(declareParameters) }
add(")")
}
override fun get(): CodeBlock = builder.build()
} | 0 | null | 0 | 0 | df82f0588beb13fbd22308b3d015852c25781612 | 2,209 | toolkit | Apache License 2.0 |
kmmtshared/core/src/commonMain/kotlin/com/kmmt/core/architecture/presenter/async/Async.kt | jittya | 361,707,096 | false | null | package com.kmmt.core.architecture.presenter.async
import com.kmmt.common.expectations.DispatcherDefault
import com.kmmt.common.expectations.DispatcherMain
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
abstract class Async {
private val exceptionHandler = CoroutineExceptionHandler { coroutineContext, throwable ->
println("CoroutineExceptionHandler : " + throwable.stackTraceToString())
throw throwable
}
private val backgroundCoroutineScope = CoroutineScope(DispatcherDefault + exceptionHandler)
private val uiCoroutineScope = CoroutineScope(DispatcherMain + exceptionHandler)
fun getBackgroundCoroutineScope(): CoroutineScope {
return backgroundCoroutineScope
}
fun getUICoroutineScope(): CoroutineScope {
return uiCoroutineScope
}
protected fun <OUT> Flow<OUT>.resultOnUI(function: (OUT) -> Unit) {
uiCoroutineScope.launch {
collect {
function.invoke(it)
}
}
}
protected fun <OUT> Flow<OUT>.resultOnBackground(function: suspend (OUT) -> Unit) {
backgroundCoroutineScope.launch {
collect {
function.invoke(it)
}
}
}
fun cancelAllRunningCoroutines(reason: String) {
backgroundCoroutineScope.coroutineContext.cancelChildren(CancellationException(reason))
}
fun <OUT> runOnBackgroundWithResult(function: suspend () -> OUT): Flow<OUT> = flow {
val result = withContext(backgroundCoroutineScope.coroutineContext) {
return@withContext function.invoke()
}
emit(result)
}
fun runOnBackground(function: suspend () -> Unit) {
backgroundCoroutineScope.launch {
function.invoke()
}
}
fun runOnUI(function: suspend () -> Unit) {
uiCoroutineScope.launch {
function.invoke()
}
}
} | 0 | Kotlin | 10 | 221 | 2faa5eb1fdd785cc1b07f03b9c186af1a3acfc40 | 1,961 | KMMT | MIT License |
app/src/main/kotlin/com/bapspatil/elon/api/model/NasaData.kt | bapspatil | 202,559,929 | false | null | package com.bapspatil.elon.api.model
import com.google.gson.annotations.SerializedName
data class NasaData(
@SerializedName("album")
val album: List<String>,
@SerializedName("center")
val center: String, // GSFC
@SerializedName("date_created")
val dateCreated: String, // 2017-12-08T00:00:00Z
@SerializedName("description")
val description: String, // Description of the image goes here.
@SerializedName("keywords")
val keywords: List<String>,
@SerializedName("location")
val location: String, // Greenbelt, MD
@SerializedName("media_type")
val mediaType: String, // image
@SerializedName("nasa_id")
val nasaId: String, // GSFC_20171208_Archive_e002105
@SerializedName("title")
val title: String // NASA's Hubble Universe in 3-D
) | 0 | Kotlin | 1 | 4 | 45b497a09e3ad4391f0d72d0eda10aec64de6826 | 805 | Elon | Apache License 2.0 |
src/main/kotlin/abc/298-b.kt | kirimin | 197,707,422 | false | null | package abc
import utilities.debugLog
import java.util.*
fun main(args: Array<String>) {
val sc = Scanner(System.`in`)
val n = sc.nextInt()
val a = (0 until n).map { (0 until n).map { sc.next().toInt() } }
val b = (0 until n).map { (0 until n).map { sc.next().toInt() } }
println(problem298b(n, a, b))
}
fun problem298b(n: Int, a: List<List<Int>>, b: List<List<Int>>): String {
val a2 = a.map { it.toMutableList() }.toMutableList()
var ans = "Yes"
for (i in 0 until n) {
for (j in 0 until n) {
if (a2[i][j] == 1 && b[i][j] != 1) {
ans = "No"
}
}
}
if (ans == "Yes") return ans
ans = "Yes"
// a2を90度回転
for (i in 0 until n) {
for (j in 0 until n) {
a2[i][j] = a[n - j - 1][i]
}
}
for (i in 0 until n) {
for (j in 0 until n) {
if (a2[i][j] == 1 && b[i][j] != 1) {
ans = "No"
}
}
}
if (ans == "Yes") return ans
ans = "Yes"
// a2を180度回転
for (i in 0 until n) {
for (j in 0 until n) {
a2[i][j] = a[n - i - 1][n - j - 1]
}
}
for (i in 0 until n) {
for (j in 0 until n) {
if (a2[i][j] == 1 && b[i][j] != 1) {
ans = "No"
}
}
}
if (ans == "Yes") return ans
ans = "Yes"
// a2を270度回転
for (i in 0 until n) {
for (j in 0 until n) {
a2[i][j] = a[j][n - i - 1]
}
}
for (i in 0 until n) {
for (j in 0 until n) {
if (a2[i][j] == 1 && b[i][j] != 1) {
ans = "No"
}
}
}
if (ans == "Yes") return ans
return ans
} | 0 | Kotlin | 1 | 5 | d639ff1baa5a7c7cfa33ef293863d58c558bbbfc | 1,728 | AtCoderLog | The Unlicense |
subprojects/gradle/module-types-validator/src/main/kotlin/com/avito/android/module_type/validation/configurations/missings/implementations/internal/MissingFakeModuleRootTaskDelegate.kt | avito-tech | 230,265,582 | false | {"Kotlin": 3752627, "Java": 67252, "Shell": 27892, "Dockerfile": 12799, "Makefile": 8086} | package com.avito.android.module_type.validation.configurations.missings.implementations.internal
import com.avito.android.module_type.FunctionalType
import java.util.SortedSet
internal class MissingFakeModuleRootTaskDelegate {
fun validate(
projectsTaskOutputText: String,
ignoreLogicalModuleRegexesText: String,
): Result<Unit> {
val allProjects = ProjectListFileReader(
reportFileText = projectsTaskOutputText
).readProjectList()
val ignoreLogicalModuleRegexes = ignoreLogicalModuleRegexesText.lines().map(::Regex)
val logicalModulesWithPublic = getLogicalModulesWithModule(allProjects, FunctionalType.Public)
val logicalModulesWithImpl = getLogicalModulesWithModule(allProjects, FunctionalType.Impl)
val logicalModulesWithFake = getLogicalModulesWithModule(allProjects, FunctionalType.Fake)
val incorrectLogicalModules =
logicalModulesWithPublic.intersect(logicalModulesWithImpl) - logicalModulesWithFake
val logicalModulesToReport = incorrectLogicalModules.filterNot { logicalModule ->
ignoreLogicalModuleRegexes.any { it.matches(logicalModule) }
}
return if (logicalModulesToReport.isEmpty()) {
Result.success(Unit)
} else {
Result.failure(Exception(
"""
The following logical modules have :public and :impl modules,
but do not have :fake modules. Create :fake modules for them.
See docs for details: https://links.k.avito.ru/android-missing-fake-modules
""".trimIndent() + logicalModulesToReport.joinToString("\n")
))
}
}
private fun getLogicalModulesWithModule(
projects: List<String>,
moduleType: FunctionalType
): SortedSet<String> {
val moduleTypeRegex = moduleType.asRegex()
return projects
.filter { it.substringAfterLast(':').matches(moduleTypeRegex) }
.map { it.substringBeforeLast(':') }
.toSortedSet()
}
}
| 10 | Kotlin | 50 | 414 | 4dc43d73134301c36793e49289305768e68e645b | 2,141 | avito-android | MIT License |
subprojects/gradle/module-types-validator/src/main/kotlin/com/avito/android/module_type/validation/configurations/missings/implementations/internal/MissingFakeModuleRootTaskDelegate.kt | avito-tech | 230,265,582 | false | {"Kotlin": 3752627, "Java": 67252, "Shell": 27892, "Dockerfile": 12799, "Makefile": 8086} | package com.avito.android.module_type.validation.configurations.missings.implementations.internal
import com.avito.android.module_type.FunctionalType
import java.util.SortedSet
internal class MissingFakeModuleRootTaskDelegate {
fun validate(
projectsTaskOutputText: String,
ignoreLogicalModuleRegexesText: String,
): Result<Unit> {
val allProjects = ProjectListFileReader(
reportFileText = projectsTaskOutputText
).readProjectList()
val ignoreLogicalModuleRegexes = ignoreLogicalModuleRegexesText.lines().map(::Regex)
val logicalModulesWithPublic = getLogicalModulesWithModule(allProjects, FunctionalType.Public)
val logicalModulesWithImpl = getLogicalModulesWithModule(allProjects, FunctionalType.Impl)
val logicalModulesWithFake = getLogicalModulesWithModule(allProjects, FunctionalType.Fake)
val incorrectLogicalModules =
logicalModulesWithPublic.intersect(logicalModulesWithImpl) - logicalModulesWithFake
val logicalModulesToReport = incorrectLogicalModules.filterNot { logicalModule ->
ignoreLogicalModuleRegexes.any { it.matches(logicalModule) }
}
return if (logicalModulesToReport.isEmpty()) {
Result.success(Unit)
} else {
Result.failure(Exception(
"""
The following logical modules have :public and :impl modules,
but do not have :fake modules. Create :fake modules for them.
See docs for details: https://links.k.avito.ru/android-missing-fake-modules
""".trimIndent() + logicalModulesToReport.joinToString("\n")
))
}
}
private fun getLogicalModulesWithModule(
projects: List<String>,
moduleType: FunctionalType
): SortedSet<String> {
val moduleTypeRegex = moduleType.asRegex()
return projects
.filter { it.substringAfterLast(':').matches(moduleTypeRegex) }
.map { it.substringBeforeLast(':') }
.toSortedSet()
}
}
| 10 | Kotlin | 50 | 414 | 4dc43d73134301c36793e49289305768e68e645b | 2,141 | avito-android | MIT License |
{{ cookiecutter.repo_name }}/core/src/main/java/{{ cookiecutter.core_package_dir }}/utils/configuration/StringConstants.kt | DominikJura | 143,721,226 | true | {"Kotlin": 24192} | package {{ cookiecutter.core_package_name }}.utils.configuration
object StringConstants {
const val BASE_URL = "base url"
{% if cookiecutter.amplitude_lib == "y" %}const val AMPLITUDE_KEY = "amplitude key"{% endif %}
} | 0 | Kotlin | 0 | 0 | 2aba27343da04e0c06c2d7b8876d3d9354b8a2b0 | 227 | android-kotlin-template | Apache License 2.0 |
src/main/kotlin/com/flamagames/ping/models/entities/UserEntity.kt | NahuelToloza | 398,418,103 | false | null | package com.flamagames.ping.models.entities
import javax.persistence.*
@Entity
@Table(name = "user")
data class UserEntity(
@Column(name = "name", unique = true) val name: String,
@Column(name = "password") val password: String,
@Column(name = "role") val role: Byte,
@Column(name = "active") val isActive: Boolean
) {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id", unique = true)
var id: Long = 0
} | 0 | Kotlin | 0 | 0 | 4a13f2cd6724dcc864fbba741f651c6ac5bb9cf3 | 465 | BackendKotlin | Apache License 2.0 |
common/src/commonMain/kotlin/org/orca/htmltext/util/nonEmptyChildren.kt | thennothinghappened | 603,730,874 | false | {"Kotlin": 23015} | package org.orca.htmltext.util
import org.jsoup.nodes.Node
internal fun Node.nonEmptyChildren() = childNodes()
.filter { it.toString().isNotBlank() }
| 1 | Kotlin | 1 | 5 | 016d7f0726028c18cde75e1df43d3438aec63386 | 156 | HtmlText | MIT License |
modules/viform-compose/src/commonMain/kotlin/Composable.kt | windedge | 661,911,964 | false | {"Kotlin": 55268, "Shell": 548, "HTML": 294} | package io.github.windedge.viform.compose
import androidx.compose.runtime.*
import io.github.windedge.viform.core.*
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.flow.*
import kotlin.reflect.*
@Composable
public fun <T : Any> FormHost<T>.useForm(content: @Composable FormScope<T>.(T) -> Unit) {
val state = this.stateFlow.collectAsState()
FormScope(this).content(state.value)
}
@Composable
public fun <T : Any> Form<T>.use(content: @Composable FormScope<T>.(T) -> Unit) {
val formHost = DefaultFormHost(this)
formHost.useForm(content)
}
public class FormScope<T : Any>(private val formHost: FormHost<T>) {
private val form: Form<T> = formHost.form
@Composable
public fun <V : Any?> field(property: KProperty0<V>): FormField<V> {
return form.getOrRegisterField(property)
}
@Composable
public inline fun <reified V> field(
property: KProperty0<V>, noinline content: @Composable FieldScope<T, V>.() -> Unit
) {
val wrappedType = typeOf<V>()
field(property).wrapAsType(wrappedType, { it }, { it }, content = content)
}
@Composable
public inline fun <reified V, reified R> FormField<V>.wrapAs(
noinline wrap: FormField<V>.(V) -> R,
noinline unwrap: FormField<V>.(R) -> V,
noinline constraints: ValidatorContainer<R>.() -> Unit = {},
noinline content: @Composable FieldScope<T, R>.() -> Unit,
) {
val wrappedType = typeOf<R>()
this.wrapAsType(wrappedType, wrap, unwrap, constraints, content)
}
@Composable
public fun <V, R> FormField<V>.wrapAsType(
wrappedType: KType,
wrap: FormField<V>.(V) -> R,
unwrap: FormField<V>.(R) -> V,
constraints: ValidatorContainer<R>.() -> Unit = {},
content: @Composable() (FieldScope<T, R>.() -> Unit),
) {
@Suppress("UNCHECKED_CAST")
val wrappedFormField = this as? WrappedFormField<V, R> ?: remember(this.name) {
WrappedFormField(this, wrappedType, wrap, unwrap).apply {
form.replaceField(this)
applyConstraints(constraints)
}
}
if (wrappedFormField.wrappedType != wrappedType) {
error("Can't wrap as another type!")
}
DisposableEffect(name) {
onDispose { form.replaceField(wrappedFormField.origin) }
}
val resultState = this.resultFlow.collectAsState(ValidateResult.None)
val fieldScope: FieldScope<T, R> = with(wrappedFormField) {
FieldScope(
wrappedState.value,
resultState.value,
::setWrappedSate,
::validate,
::showError,
formHost::pop
)
}
fieldScope.content()
}
}
public class FieldScope<T : Any, V : Any?>(
value: V,
result: ValidateResult,
private val onValueChanged: (V, Boolean) -> Unit,
private val onValidate: () -> Boolean,
private val onShowError: (String) -> Unit,
private val onSubmitted: () -> Unit,
) {
public val currentValue: V = value
public val hasError: Boolean = result.isError
public val errorMessage: String? = result.errorMessage
public fun setValue(value: V, validate: Boolean = false) {
onValueChanged(value, validate)
}
public fun submit() {
onSubmitted()
}
public fun validate(): Boolean {
return onValidate()
}
public fun showError(message: String) {
onShowError(message)
}
@OptIn(FlowPreview::class)
@Composable
public fun watchLazily(debouncedTimeoutMills: Long = 800, block: (V) -> Unit) {
LaunchedEffect(currentValue) {
snapshotFlow { currentValue }.distinctUntilChanged().debounce(debouncedTimeoutMills).collectLatest {
block(it)
}
}
}
}
internal class WrappedFormField<V, R>(
val origin: FormField<V>,
val wrappedType: KType,
val wrap: FormField<V>.(V) -> R,
val unwrap: FormField<V>.(R) -> V
) : FormField<V> by origin {
private val wrappedValidators = mutableListOf<FieldValidator<R>>()
private val _wrappedState: MutableState<R> = mutableStateOf(wrap(currentValue))
val wrappedState: State<R> get() = _wrappedState
override fun setValue(value: V, validate: Boolean) {
origin.setValue(value, false)
_wrappedState.value = wrap(value)
if (validate) validate()
}
override fun validate(): Boolean {
val results = listOf(
origin.getValidators().validateAndGet(unwrap(_wrappedState.value)),
wrappedValidators.validateAndGet(_wrappedState.value)
)
return results.find { it.isError }?.also { origin.setResult(it) }?.isSuccess ?: true
}
fun setWrappedSate(value: R, validate: Boolean = false) {
_wrappedState.value = value
val unwrapValue = unwrap(value)
origin.setValue(unwrapValue, false)
if (validate) validate()
}
fun applyConstraints(constraints: ValidatorContainer<R>.() -> Unit) {
val container = SimpleValidatorContainer<R>().apply(constraints)
wrappedValidators.addAll(container.getValidators())
}
}
internal class SimpleValidatorContainer<V> : ValidatorContainer<V> {
private val validators = mutableListOf<FieldValidator<V>>()
override fun addValidator(validator: FieldValidator<V>) {
validators.add(validator)
}
override fun getValidators(): List<FieldValidator<V>> = validators.toList()
override fun clearValidators(): Unit = validators.clear()
}
internal class ValidateException(override val message: String) : Exception(message) | 0 | Kotlin | 0 | 0 | 5b6d44ecf5860b27dc93055674f6405d31afe530 | 5,723 | viform-multiplatform | MIT License |
app/src/main/java/com/avex/ragraa/ui/calculator/CalculatorCourse.kt | avexxx3 | 778,981,508 | false | {"Kotlin": 224969} | package com.avex.ragraa.ui.calculator
data class CalculatorCourse(
val name: String = "",
val credits: String = "",
val mca: String = "",
val obtained: String = "",
val gpa: Float = 0f,
val grade: String = "",
val isRelative: Boolean = false,
val locked: Boolean = false,
val isCustom: Boolean = false
) | 0 | Kotlin | 0 | 5 | f313c15cb8d334489b864215bd3be02f149f1eb3 | 340 | Ragraa | Apache License 2.0 |
ask-api/src/main/kotlin/com/fluxtah/ask/api/clients/openai/assistants/model/CreateAssistantRequest.kt | fluxtah | 794,032,032 | false | {"Kotlin": 126833, "Shell": 387} | /*
* Copyright (c) 2024 <NAME>
* Released under the MIT license
* https://opensource.org/licenses/MIT
*/
package com.fluxtah.ask.api.clients.openai.assistants.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class CreateAssistantRequest(
@SerialName("model") val model: String? = null,
@SerialName("name") val name: String? = null,
@SerialName("description") val description: String? = null,
@SerialName("instructions") val instructions: String? = null,
@SerialName("tools") val tools: List<AssistantTool> = emptyList(),
@SerialName("tool_resources") val toolResource: ToolResources? = null,
@SerialName("metadata") val metadata: Map<String, String> = emptyMap(),
@SerialName("temperature") val temperature: Float? = null,
@SerialName("top_p") val topP: Float? = null,
@SerialName("response_format") val responseFormat: ResponseFormat? = null
)
@Serializable
data class ResponseFormat(
@SerialName("type") val type: String,
) {
companion object {
val JSON = ResponseFormat("json_object")
}
}
@Serializable
data class ModifyAssistantRequest(
@SerialName("model") val model: String? = null,
@SerialName("name") val name: String? = null,
@SerialName("description") val description: String? = null,
@SerialName("instructions") val instructions: String? = null,
@SerialName("tools") val tools: List<AssistantTool> = emptyList(),
@SerialName("tool_resources") val toolResource: ToolResources? = null,
@SerialName("metadata") val metadata: Map<String, String> = emptyMap(),
@SerialName("temperature") val temperature: Float? = null
) | 0 | Kotlin | 0 | 1 | 327cdc0651ec331c5cf22a9da157da2a8e3dc43b | 1,687 | ask | MIT License |
youtubeextractor/src/main/java/com/commit451/youtubeextractor/ItagItem.kt | khamidjon-khamidov | 273,750,253 | true | {"Kotlin": 29487} | package com.commit451.youtubeextractor
internal data class ItagItem(
val id: Int,
val type: StreamType,
val format: String,
val resolution: String? = null
) {
companion object {
/**
* https://github.com/ytdl-org/youtube-dl/blob/master/youtube_dl/extractor/youtube.py#L431
*/
private val ITAG_MAP = mapOf(
17 to ItagItem(17, StreamType.VIDEO, Stream.FORMAT_v3GPP, Stream.VideoStream.RESOLUTION_144p),
18 to ItagItem(18, StreamType.VIDEO, Stream.FORMAT_MPEG_4, Stream.VideoStream.RESOLUTION_360p),
34 to ItagItem(34, StreamType.VIDEO, Stream.FORMAT_MPEG_4, Stream.VideoStream.RESOLUTION_360p),
35 to ItagItem(35, StreamType.VIDEO, Stream.FORMAT_MPEG_4, Stream.VideoStream.RESOLUTION_480p),
36 to ItagItem(36, StreamType.VIDEO, Stream.FORMAT_v3GPP, Stream.VideoStream.RESOLUTION_240p),
59 to ItagItem(59, StreamType.VIDEO, Stream.FORMAT_MPEG_4, Stream.VideoStream.RESOLUTION_480p),
78 to ItagItem(78, StreamType.VIDEO, Stream.FORMAT_MPEG_4, Stream.VideoStream.RESOLUTION_480p),
22 to ItagItem(22, StreamType.VIDEO, Stream.FORMAT_MPEG_4, Stream.VideoStream.RESOLUTION_720p),
37 to ItagItem(37, StreamType.VIDEO, Stream.FORMAT_MPEG_4, Stream.VideoStream.RESOLUTION_1080p),
38 to ItagItem(38, StreamType.VIDEO, Stream.FORMAT_MPEG_4, Stream.VideoStream.RESOLUTION_1080p),
43 to ItagItem(43, StreamType.VIDEO, Stream.FORMAT_WEBM, Stream.VideoStream.RESOLUTION_360p),
44 to ItagItem(44, StreamType.VIDEO, Stream.FORMAT_WEBM, Stream.VideoStream.RESOLUTION_480p),
45 to ItagItem(45, StreamType.VIDEO, Stream.FORMAT_WEBM, Stream.VideoStream.RESOLUTION_720p),
46 to ItagItem(46, StreamType.VIDEO, Stream.FORMAT_WEBM, Stream.VideoStream.RESOLUTION_1080p),
171 to ItagItem(171, StreamType.AUDIO, Stream.FORMAT_WEBMA),
172 to ItagItem(172, StreamType.AUDIO, Stream.FORMAT_WEBMA),
139 to ItagItem(139, StreamType.AUDIO, Stream.FORMAT_M4A),
140 to ItagItem(140, StreamType.AUDIO, Stream.FORMAT_M4A),
141 to ItagItem(141, StreamType.AUDIO, Stream.FORMAT_M4A),
249 to ItagItem(249, StreamType.AUDIO, Stream.FORMAT_WEBMA_OPUS),
250 to ItagItem(250, StreamType.AUDIO, Stream.FORMAT_WEBMA_OPUS),
251 to ItagItem(251, StreamType.AUDIO, Stream.FORMAT_WEBMA_OPUS),
160 to ItagItem(160, StreamType.VIDEO_ONLY, Stream.FORMAT_MPEG_4, Stream.VideoStream.RESOLUTION_144p),
133 to ItagItem(133, StreamType.VIDEO_ONLY, Stream.FORMAT_MPEG_4, Stream.VideoStream.RESOLUTION_240p),
135 to ItagItem(135, StreamType.VIDEO_ONLY, Stream.FORMAT_MPEG_4, Stream.VideoStream.RESOLUTION_480p),
212 to ItagItem(212, StreamType.VIDEO_ONLY, Stream.FORMAT_MPEG_4, Stream.VideoStream.RESOLUTION_480p),
298 to ItagItem(298, StreamType.VIDEO_ONLY, Stream.FORMAT_MPEG_4, Stream.VideoStream.RESOLUTION_720p60),
137 to ItagItem(137, StreamType.VIDEO_ONLY, Stream.FORMAT_MPEG_4, Stream.VideoStream.RESOLUTION_1080p),
299 to ItagItem(299, StreamType.VIDEO_ONLY, Stream.FORMAT_MPEG_4, Stream.VideoStream.RESOLUTION_1080p60),
266 to ItagItem(266, StreamType.VIDEO_ONLY, Stream.FORMAT_MPEG_4, Stream.VideoStream.RESOLUTION_2160p),
278 to ItagItem(278, StreamType.VIDEO_ONLY, Stream.FORMAT_WEBM, Stream.VideoStream.RESOLUTION_144p),
242 to ItagItem(242, StreamType.VIDEO_ONLY, Stream.FORMAT_WEBM, Stream.VideoStream.RESOLUTION_240p),
244 to ItagItem(244, StreamType.VIDEO_ONLY, Stream.FORMAT_WEBM, Stream.VideoStream.RESOLUTION_480p),
245 to ItagItem(245, StreamType.VIDEO_ONLY, Stream.FORMAT_WEBM, Stream.VideoStream.RESOLUTION_480p),
246 to ItagItem(246, StreamType.VIDEO_ONLY, Stream.FORMAT_WEBM, Stream.VideoStream.RESOLUTION_480p),
247 to ItagItem(247, StreamType.VIDEO_ONLY, Stream.FORMAT_WEBM, Stream.VideoStream.RESOLUTION_720p),
248 to ItagItem(248, StreamType.VIDEO_ONLY, Stream.FORMAT_WEBM, Stream.VideoStream.RESOLUTION_1080p),
271 to ItagItem(271, StreamType.VIDEO_ONLY, Stream.FORMAT_WEBM, Stream.VideoStream.RESOLUTION_1440p),
272 to ItagItem(272, StreamType.VIDEO_ONLY, Stream.FORMAT_WEBM, Stream.VideoStream.RESOLUTION_2160p),
302 to ItagItem(302, StreamType.VIDEO_ONLY, Stream.FORMAT_WEBM, Stream.VideoStream.RESOLUTION_720p60),
303 to ItagItem(303, StreamType.VIDEO_ONLY, Stream.FORMAT_WEBM, Stream.VideoStream.RESOLUTION_1080p60),
308 to ItagItem(308, StreamType.VIDEO_ONLY, Stream.FORMAT_WEBM, Stream.VideoStream.RESOLUTION_1440p60),
313 to ItagItem(313, StreamType.VIDEO_ONLY, Stream.FORMAT_WEBM, Stream.VideoStream.RESOLUTION_2160p),
315 to ItagItem(315, StreamType.VIDEO_ONLY, Stream.FORMAT_WEBM, Stream.VideoStream.RESOLUTION_2160p60)
)
fun isSupported(itag: Int?): Boolean {
return ITAG_MAP.containsKey(itag)
}
fun getItag(itagId: Int?): ItagItem {
return ITAG_MAP[itagId] ?: throw YouTubeExtractionException("itag=$itagId not supported")
}
}
}
| 0 | null | 0 | 1 | 1ba377fd32c590d58eeb9a26e29fc46fcc72c69d | 5,448 | YouTubeExtractor | Apache License 2.0 |
telegram-bot/src/main/kotlin/eu/vendeli/tgbot/interfaces/SimpleAction.kt | vendelieu | 496,567,172 | false | null | package eu.vendeli.tgbot.interfaces
import eu.vendeli.tgbot.TelegramBot
import eu.vendeli.tgbot.types.internal.Response
import eu.vendeli.tgbot.utils.makeRequestAsync
import eu.vendeli.tgbot.utils.makeSilentRequest
import kotlinx.coroutines.Deferred
/**
* Simple action, see [Actions article](https://github.com/vendelieu/telegram-bot/wiki/Actions)
*
* @param ReturnType response type.
*/
interface SimpleAction<ReturnType> : TgAction, ParametersBase {
/**
* Send request for action.
*
* @param to recipient.
*/
suspend fun send(to: TelegramBot) {
to.makeSilentRequest(method, parameters)
}
}
/**
* Send async request for action.
*
* @param ReturnType response type.
* @param to recipient.
*/
suspend inline fun <reified ReturnType> SimpleAction<ReturnType>.sendAsync(
to: TelegramBot,
): Deferred<Response<out ReturnType>> =
to.makeRequestAsync(method, parameters, ReturnType::class.java, wrappedDataType)
| 0 | Kotlin | 2 | 70 | e35d51216afdd5748d6ee9ac8fce4aca6539f241 | 967 | telegram-bot | Apache License 2.0 |
app/src/main/java/com/example/note_app/Db.kt | enesulkerr | 651,983,924 | false | null | package com.example.note_app
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class DB(context: Context) : SQLiteOpenHelper(context, DBName, null, Version ) {
companion object {
private val DBName = "notes.db"
private val Version = 1
}
override fun onCreate(p0: SQLiteDatabase?) {
val noteTable = "CREATE TABLE \"note\" (\n" +
"\t\"nid\"\tINTEGER,\n" +
"\t\"title\"\tTEXT,\n" +
"\t\"detail\"\tTEXT,\n" +
"\tPRIMARY KEY(\"nid\" AUTOINCREMENT)\n" +
");"
p0?.execSQL(noteTable)
}
override fun onUpgrade(p0: SQLiteDatabase?, p1: Int, p2: Int) {
val noteTableDrop = "DROP TABLE IF EXISTS note"
p0?.execSQL(noteTableDrop)
onCreate(p0)
}
fun addNote( title:String, detail: String) : Long {
val db = this.writableDatabase
val values = ContentValues()
values.put("title", title)
values.put("detail", detail)
val effectRow = db.insert("note", null, values)
db.close()
return effectRow
}
fun deleteNote(nid: Int) : Int {
val db = this.writableDatabase
val status = db.delete("note", "nid = $nid", null )
db.close()
return status
}
fun updateNote(title:String, detail: String, nid: Int) : Int {
val db = this.writableDatabase
val content = ContentValues()
content.put("title", title)
content.put("detail", detail)
val status = db.update("note", content, "nid = $nid", null)
db.close()
return status
}
fun allNote() : List<Note> {
val db = this.readableDatabase
val arr = mutableListOf<Note>()
val cursor = db.query("note",null, null, null, null, null, null)
while (cursor.moveToNext()) {
val nid = cursor.getInt(0)
val title = cursor.getString(1)
val detail = cursor.getString(2)
val note = Note(nid, title, detail)
arr.add(note)
}
db.close()
return arr
}
} | 0 | Kotlin | 0 | 0 | fdea31fd19f17a4ba76ad5f8b946ad601bbddc7e | 2,226 | Note-App | MIT License |
app/src/main/java/com/wei/picquest/MainActivityViewModel.kt | azrael8576 | 725,428,435 | false | {"Kotlin": 361445} | package com.wei.picquest
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.wei.picquest.core.data.repository.UserDataRepository
import com.wei.picquest.core.model.data.UserData
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject
@HiltViewModel
class MainActivityViewModel
@Inject
constructor(
userDataRepository: UserDataRepository,
) : ViewModel() {
val uiState: StateFlow<MainActivityUiState> =
userDataRepository.userData.map {
MainActivityUiState.Success(it)
}.stateIn(
scope = viewModelScope,
initialValue = MainActivityUiState.Loading,
started = SharingStarted.WhileSubscribed(5_000),
)
}
sealed interface MainActivityUiState {
data object Loading : MainActivityUiState
data class Success(val userData: UserData) : MainActivityUiState
}
| 7 | Kotlin | 0 | 13 | a8deb6aee5ef3c2b252fe710e010223f5b971f5f | 1,060 | picquest | Apache License 2.0 |
presentation/measurements/src/main/kotlin/ru/vt/presentation/measurements/weight/summary/ViewModelWeightSummary.kt | magic-goop | 522,567,133 | false | {"Kotlin": 484480, "Shell": 117} | package ru.vt.presentation.measurements.weight.summary
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.*
import org.threeten.bp.LocalDate
import ru.vt.core.common.LoaderHandler
import ru.vt.core.common.ResourceManger
import ru.vt.core.common.event.EventHandler
import ru.vt.core.common.extension.flowOnDefault
import ru.vt.core.common.extension.lazyNone
import ru.vt.core.dependency.androidDeps
import ru.vt.core.dependency.annotation.DependencyAccessor
import ru.vt.core.dependency.dataDeps
import ru.vt.core.navigation.contract.Navigator
import ru.vt.core.navigation.contract.ScreenWeightToCreate
import ru.vt.core.ui.viewmodel.BaseViewModel
import ru.vt.core.ui.viewmodel.ViewModelFactory
import ru.vt.domain.measurement.entity.WeightEntity
import ru.vt.domain.measurement.repository.WeightRepository
import ru.vt.domain.measurement.usecase.weight.DeleteWeightUseCase
import ru.vt.domain.measurement.usecase.weight.GetWeightMinMaxUseCase
import ru.vt.domain.measurement.usecase.weight.GetWeightUseCase
import ru.vt.presentation.measurements.common.entity.*
import ru.vt.presentation.measurements.weight.summary.ActionWeightSummary as Action
import ru.vt.presentation.measurements.weight.summary.StateWeightSummary as State
@OptIn(DependencyAccessor::class, kotlinx.coroutines.ExperimentalCoroutinesApi::class)
internal class ViewModelWeightSummary(
savedStateHandle: SavedStateHandle,
eventHandler: EventHandler?,
resourceManger: ResourceManger,
navigator: Navigator,
private val repository: WeightRepository,
private val loaderHandler: LoaderHandler?
) : BaseViewModel<State, Action>(
savedStateHandle = savedStateHandle,
eventHandler = eventHandler,
resourceManger = resourceManger,
navigator = navigator
) {
private companion object {
const val LIMIT: Int = 20
}
private val getUseCase: GetWeightUseCase by lazyNone {
GetWeightUseCase(repository)
}
private val deleteUseCase: DeleteWeightUseCase by lazyNone {
DeleteWeightUseCase(repository)
}
private val minMaxUseCase: GetWeightMinMaxUseCase by lazyNone {
GetWeightMinMaxUseCase(repository)
}
private val loadDataFlow: MutableSharedFlow<Pair<Period, Int>> = MutableSharedFlow()
private val loadGraphFlow: MutableSharedFlow<Period> = MutableSharedFlow()
override val initialState: State by lazyNone {
State(anchorDate = LocalDate.now().toAnchorDate())
}
override suspend fun processAction(action: ru.vt.presentation.measurements.weight.summary.ActionWeightSummary) {
when (action) {
is Action.Init -> {
render(state.copy(profileId = action.profileId, data = null, graphData = null))
loadDataFlow.emit(state.period to 0)
loadGraphFlow.emit(state.period)
}
is Action.SetPeriod -> {
render(state.copy(period = action.period, data = null, graphData = null))
loadDataFlow.emit(action.period to 0)
loadGraphFlow.emit(action.period)
}
is Action.Delete -> deleteEntity(action.entity)
Action.OnBackPressed -> navigator.onBackPressed()
Action.Create -> navigator.navigate(ScreenWeightToCreate(state.profileId))
Action.LoadMore -> loadDataFlow.emit(state.period to (state.data?.size ?: 0))
}
}
init {
loadDataFlow
.onEach { loaderHandler?.setLoading(true) }
.flatMapLatest { p ->
val anchorLocalDate = LocalDate.of(
state.anchorDate.year,
state.anchorDate.month,
state.anchorDate.day
)
val (from, to) = p.first.getFromToValues(anchorLocalDate)
getUseCase(
GetWeightUseCase.Params(
profileId = state.profileId,
from = from,
to = to,
offset = p.second,
limit = LIMIT
)
)
}
.flowOnDefault()
.onEach { loaderHandler?.setLoading(false) }
.handle { data ->
val newData = state.data?.toMutableList() ?: mutableListOf()
newData.addAll(data)
render(state.copy(data = newData, canLoadMore = data.size == LIMIT))
}
.launchIn(viewModelScope)
loadGraphFlow
.onEach { loaderHandler?.setLoading(true) }
.flatMapLatest { period ->
val anchorLocalDate = LocalDate.of(
state.anchorDate.year,
state.anchorDate.month,
state.anchorDate.day
)
val bounds = period.getBounds(anchorLocalDate)
minMaxUseCase(
GetWeightMinMaxUseCase.Params(
profileId = state.profileId,
bounds = bounds
)
).map { result ->
if (result.isSuccess) {
Result.success(WeightGraphMapper.map(result.getOrDefault(emptyList())))
} else {
Result.failure(result.exceptionOrNull() ?: IllegalStateException())
}
}.catch { exception -> Result.failure<List<GraphSection>>(exception) }
}
.flowOnDefault()
.onEach { loaderHandler?.setLoading(false) }
.handle { graphSections ->
render(state.copy(graphData = graphSections))
}
.launchIn(viewModelScope)
}
private fun deleteEntity(entity: WeightEntity) {
deleteUseCase(DeleteWeightUseCase.Params(entity.profileId, entity.timestamp))
.handle {
loadGraphFlow.emit(state.period)
render(state.copy(data = state.data?.filter { it != entity }))
}
.launchIn(viewModelScope)
}
class Factory : ViewModelFactory<ViewModelWeightSummary> {
override fun create(handle: SavedStateHandle): ViewModelWeightSummary =
ViewModelWeightSummary(
savedStateHandle = handle,
eventHandler = androidDeps.eventHandler,
resourceManger = androidDeps.resourceManger,
navigator = androidDeps.navigator,
repository = dataDeps.weightRepository,
loaderHandler = androidDeps.loaderHandler
)
}
} | 0 | Kotlin | 0 | 2 | b7ff60f72cc67f43755a75b05ef4ba6a06d02315 | 6,663 | vitals-tracker | Apache License 2.0 |
ktor-http/jvm/src/io/ktor/http/HttpMessagePropertiesJvm.kt | LloydFinch | 166,520,021 | true | {"Kotlin": 2419371, "Lua": 280, "HTML": 112} | package io.ktor.http
import java.text.*
import java.util.*
private val HTTP_DATE_FORMAT: SimpleDateFormat
get() = SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US).apply {
timeZone = TimeZone.getTimeZone("GMT")
}
private fun parseHttpDate(date: String): Date = HTTP_DATE_FORMAT.parse(date)
private fun formatHttpDate(date: Date): String = HTTP_DATE_FORMAT.format(date)
/**
* Set `If-Modified-Since` header
*/
fun HttpMessageBuilder.ifModifiedSince(date: Date) = headers.set(HttpHeaders.IfModifiedSince, formatHttpDate(date))
/**
* Parse `Last-Modified` header
*/
fun HttpMessageBuilder.lastModified(): Date? = headers[HttpHeaders.LastModified]?.let { parseHttpDate(it) }
/**
* Parse `Expires` header
*/
fun HttpMessageBuilder.expires(): Date? = headers[HttpHeaders.Expires]?.let { parseHttpDate(it) }
/**
* Parse `Last-Modified` header
*/
fun HttpMessage.lastModified(): Date? = headers[HttpHeaders.LastModified]?.let { parseHttpDate(it) }
/**
* Parse `Expires` header
*/
fun HttpMessage.expires(): Date? = headers[HttpHeaders.Expires]?.let { parseHttpDate(it) }
| 0 | Kotlin | 0 | 2 | 9b9fc6c3b853c929a806c65cf6bf7c104b4c07fc | 1,107 | ktor | Apache License 2.0 |
api/src/main/kotlin/br/com/gamemods/minecity/api/id/TrustLevelId.kt | GameModsBR | 723,707,184 | false | {"Kotlin": 109716, "Java": 1275} | package br.com.gamemods.minecity.api.id
import br.com.gamemods.minecity.api.serializer.UniqueId
import kotlinx.serialization.Serializable
import java.util.*
/**
* UUID identifier that identifies a custom trust level registered on MineCity
*/
@Serializable
@JvmInline
public value class TrustLevelId(public val uuid: UniqueId): Comparable<TrustLevelId> {
public constructor(): this(UUID.randomUUID())
override fun compareTo(other: TrustLevelId): Int = uuid.compareTo(other.uuid)
override fun toString(): String = uuid.toString()
public companion object {
public val EVERYONE: TrustLevelId = TrustLevelId(UniqueId(0L, 0L))
}
}
| 1 | Kotlin | 0 | 6 | 81abd62fc7724d99ec48d90a8eb3c87ad3c03dde | 657 | MineCity2 | MIT License |
IPassPlusSdk/src/main/java/com/sdk/ipassplussdk/utils/Errors.kt | yazanalqasem | 808,584,767 | false | {"Kotlin": 308101, "Java": 4759} | package com.sdk.ipassplussdk.utils
enum class Errors {
INVALID_KEY, WRONG_API_SPECIFIER, EMPTY_X_API_KEY, API_URL_NOT_FOUND, EMAIL_EMPTY, FNAME_EMPTY, LNAME_EMPTY, MEMBERSHIPID_EMPTY, DOB_EMPTY, GENDER_EMPTY, HEALTH_CON_EMPTY, CUS_FIELDS_EMPTY, INVALID_EMAIL_FROMAT, HEALTH_METRIC_EMPTY, EMAILNOT_UNIQUE
}
| 0 | Kotlin | 0 | 0 | 1fc3247607811f7f52e1d401c252b82e2c98c3a8 | 311 | iPass2.0NativeAndroidSDK | Apple MIT License |
solar/src/main/java/com/chiksmedina/solar/linear/transportpartsservice/ElectricRefueling.kt | CMFerrer | 689,442,321 | false | {"Kotlin": 36591890} | package com.chiksmedina.solar.linear.transportpartsservice
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.chiksmedina.solar.linear.TransportPartsServiceGroup
val TransportPartsServiceGroup.ElectricRefueling: ImageVector
get() {
if (_electricRefueling != null) {
return _electricRefueling!!
}
_electricRefueling = Builder(
name = "ElectricRefueling", defaultWidth = 24.0.dp,
defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF1C274C)),
strokeLineWidth = 1.5f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(16.0f, 22.0f)
verticalLineTo(8.0f)
curveTo(16.0f, 5.1716f, 16.0f, 3.7574f, 15.1213f, 2.8787f)
curveTo(14.2426f, 2.0f, 12.8284f, 2.0f, 10.0f, 2.0f)
horizontalLineTo(9.0f)
curveTo(6.1716f, 2.0f, 4.7574f, 2.0f, 3.8787f, 2.8787f)
curveTo(3.0f, 3.7574f, 3.0f, 5.1716f, 3.0f, 8.0f)
verticalLineTo(22.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF1C274C)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(9.5f, 10.0f)
lineTo(8.0f, 12.5f)
horizontalLineTo(11.0f)
lineTo(9.5f, 15.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF1C274C)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(17.0f, 22.0f)
horizontalLineTo(2.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF1C274C)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(19.5f, 4.0f)
lineTo(20.7331f, 4.9865f)
curveTo(20.8709f, 5.0967f, 20.9398f, 5.1519f, 21.0025f, 5.208f)
curveTo(21.5937f, 5.7381f, 21.9508f, 6.4809f, 21.9953f, 7.2736f)
curveTo(22.0f, 7.3577f, 22.0f, 7.4459f, 22.0f, 7.6224f)
verticalLineTo(18.5f)
curveTo(22.0f, 19.3284f, 21.3284f, 20.0f, 20.5f, 20.0f)
curveTo(19.6716f, 20.0f, 19.0f, 19.3284f, 19.0f, 18.5f)
verticalLineTo(18.4286f)
curveTo(19.0f, 17.6396f, 18.3604f, 17.0f, 17.5714f, 17.0f)
horizontalLineTo(16.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF1C274C)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(22.0f, 8.0f)
horizontalLineTo(20.5f)
curveTo(19.6716f, 8.0f, 19.0f, 8.6716f, 19.0f, 9.5f)
verticalLineTo(11.9189f)
curveTo(19.0f, 12.5645f, 19.4131f, 13.1377f, 20.0257f, 13.3419f)
lineTo(22.0f, 14.0f)
}
}
.build()
return _electricRefueling!!
}
private var _electricRefueling: ImageVector? = null
| 0 | Kotlin | 0 | 0 | 3414a20650d644afac2581ad87a8525971222678 | 4,299 | SolarIconSetAndroid | MIT License |
solar/src/main/java/com/chiksmedina/solar/linear/transportpartsservice/ElectricRefueling.kt | CMFerrer | 689,442,321 | false | {"Kotlin": 36591890} | package com.chiksmedina.solar.linear.transportpartsservice
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.chiksmedina.solar.linear.TransportPartsServiceGroup
val TransportPartsServiceGroup.ElectricRefueling: ImageVector
get() {
if (_electricRefueling != null) {
return _electricRefueling!!
}
_electricRefueling = Builder(
name = "ElectricRefueling", defaultWidth = 24.0.dp,
defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF1C274C)),
strokeLineWidth = 1.5f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(16.0f, 22.0f)
verticalLineTo(8.0f)
curveTo(16.0f, 5.1716f, 16.0f, 3.7574f, 15.1213f, 2.8787f)
curveTo(14.2426f, 2.0f, 12.8284f, 2.0f, 10.0f, 2.0f)
horizontalLineTo(9.0f)
curveTo(6.1716f, 2.0f, 4.7574f, 2.0f, 3.8787f, 2.8787f)
curveTo(3.0f, 3.7574f, 3.0f, 5.1716f, 3.0f, 8.0f)
verticalLineTo(22.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF1C274C)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(9.5f, 10.0f)
lineTo(8.0f, 12.5f)
horizontalLineTo(11.0f)
lineTo(9.5f, 15.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF1C274C)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(17.0f, 22.0f)
horizontalLineTo(2.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF1C274C)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(19.5f, 4.0f)
lineTo(20.7331f, 4.9865f)
curveTo(20.8709f, 5.0967f, 20.9398f, 5.1519f, 21.0025f, 5.208f)
curveTo(21.5937f, 5.7381f, 21.9508f, 6.4809f, 21.9953f, 7.2736f)
curveTo(22.0f, 7.3577f, 22.0f, 7.4459f, 22.0f, 7.6224f)
verticalLineTo(18.5f)
curveTo(22.0f, 19.3284f, 21.3284f, 20.0f, 20.5f, 20.0f)
curveTo(19.6716f, 20.0f, 19.0f, 19.3284f, 19.0f, 18.5f)
verticalLineTo(18.4286f)
curveTo(19.0f, 17.6396f, 18.3604f, 17.0f, 17.5714f, 17.0f)
horizontalLineTo(16.0f)
}
path(
fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF1C274C)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(22.0f, 8.0f)
horizontalLineTo(20.5f)
curveTo(19.6716f, 8.0f, 19.0f, 8.6716f, 19.0f, 9.5f)
verticalLineTo(11.9189f)
curveTo(19.0f, 12.5645f, 19.4131f, 13.1377f, 20.0257f, 13.3419f)
lineTo(22.0f, 14.0f)
}
}
.build()
return _electricRefueling!!
}
private var _electricRefueling: ImageVector? = null
| 0 | Kotlin | 0 | 0 | 3414a20650d644afac2581ad87a8525971222678 | 4,299 | SolarIconSetAndroid | MIT License |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/StoreBuyer.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Filled.StoreBuyer: ImageVector
get() {
if (_storeBuyer != null) {
return _storeBuyer!!
}
_storeBuyer = Builder(name = "StoreBuyer", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(23.0f, 24.0f)
horizontalLineToRelative(-8.0f)
curveToRelative(-0.311f, 0.0f, -0.604f, -0.145f, -0.793f, -0.391f)
curveToRelative(-0.189f, -0.247f, -0.254f, -0.567f, -0.173f, -0.868f)
curveToRelative(0.591f, -2.203f, 2.633f, -3.741f, 4.966f, -3.741f)
reflectiveCurveToRelative(4.375f, 1.538f, 4.966f, 3.741f)
curveToRelative(0.081f, 0.301f, 0.017f, 0.621f, -0.173f, 0.868f)
curveToRelative(-0.188f, 0.247f, -0.482f, 0.391f, -0.793f, 0.391f)
close()
moveTo(19.0f, 18.0f)
curveToRelative(-1.379f, 0.0f, -2.5f, -1.121f, -2.5f, -2.5f)
reflectiveCurveToRelative(1.121f, -2.5f, 2.5f, -2.5f)
reflectiveCurveToRelative(2.5f, 1.121f, 2.5f, 2.5f)
reflectiveCurveToRelative(-1.121f, 2.5f, -2.5f, 2.5f)
close()
moveTo(23.962f, 7.725f)
lineToRelative(-1.172f, -4.099f)
curveToRelative(-0.61f, -2.135f, -2.588f, -3.626f, -4.808f, -3.626f)
horizontalLineToRelative(-0.982f)
verticalLineToRelative(4.0f)
curveToRelative(0.0f, 0.552f, -0.447f, 1.0f, -1.0f, 1.0f)
reflectiveCurveToRelative(-1.0f, -0.448f, -1.0f, -1.0f)
lineTo(15.0f, 0.0f)
horizontalLineToRelative(-6.0f)
verticalLineToRelative(4.0f)
curveToRelative(0.0f, 0.552f, -0.448f, 1.0f, -1.0f, 1.0f)
reflectiveCurveToRelative(-1.0f, -0.448f, -1.0f, -1.0f)
lineTo(7.0f, 0.0f)
horizontalLineToRelative(-0.983f)
curveTo(3.797f, 0.0f, 1.82f, 1.491f, 1.209f, 3.626f)
lineTo(0.039f, 7.725f)
curveToRelative(-0.025f, 0.089f, -0.039f, 0.182f, -0.039f, 0.275f)
curveToRelative(0.0f, 2.206f, 1.794f, 4.0f, 4.0f, 4.0f)
horizontalLineToRelative(1.0f)
curveToRelative(1.2f, 0.0f, 2.266f, -0.542f, 3.0f, -1.382f)
curveToRelative(0.734f, 0.84f, 1.8f, 1.382f, 3.0f, 1.382f)
horizontalLineToRelative(2.0f)
curveToRelative(1.201f, 0.0f, 2.266f, -0.542f, 3.0f, -1.382f)
curveToRelative(0.734f, 0.84f, 1.799f, 1.382f, 3.0f, 1.382f)
horizontalLineToRelative(1.0f)
curveToRelative(2.206f, 0.0f, 4.0f, -1.794f, 4.0f, -4.0f)
curveToRelative(0.0f, -0.093f, -0.013f, -0.186f, -0.038f, -0.275f)
close()
moveTo(12.103f, 22.22f)
curveToRelative(0.481f, -1.794f, 1.659f, -3.256f, 3.192f, -4.176f)
curveToRelative(-0.499f, -0.725f, -0.795f, -1.6f, -0.795f, -2.545f)
curveToRelative(0.0f, -0.652f, 0.146f, -1.268f, 0.396f, -1.827f)
curveToRelative(-0.607f, 0.207f, -1.244f, 0.327f, -1.896f, 0.327f)
horizontalLineToRelative(-2.0f)
curveToRelative(-1.062f, 0.0f, -2.095f, -0.288f, -3.0f, -0.819f)
curveToRelative(-0.905f, 0.531f, -1.938f, 0.819f, -3.0f, 0.819f)
horizontalLineToRelative(-1.0f)
curveToRelative(-1.093f, 0.0f, -2.116f, -0.299f, -3.0f, -0.812f)
verticalLineToRelative(6.812f)
curveToRelative(0.0f, 2.206f, 1.794f, 4.0f, 4.0f, 4.0f)
horizontalLineToRelative(7.192f)
curveToRelative(-0.201f, -0.568f, -0.248f, -1.189f, -0.089f, -1.78f)
close()
}
}
.build()
return _storeBuyer!!
}
private var _storeBuyer: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 4,826 | icons | MIT License |
CoordinatorLayout/app/src/main/java/eduardo/gladzik/coordinatorlayout/LayoutBased.kt | EduardoGladzik | 289,071,387 | false | null | package eduardo.gladzik.coordinatorlayout
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class LayoutBased : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_layout_based)
}
} | 0 | Kotlin | 0 | 0 | 7854c98a604dc4b436583ae0143e86c96ced739f | 321 | kotlin-android | MIT License |
app/src/main/java/com/rewardtodo/presentation/models/UserView.kt | mattrob33 | 241,623,871 | false | null | package com.rewardtodo.presentation.models
import java.util.*
data class UserView (
var name: String = "",
var points: Int = 0,
var id: String = UUID.randomUUID().toString()
) | 0 | Kotlin | 0 | 0 | eefb7aade1c43be3e32dedc83bffb6145fcc37e1 | 189 | reward | Apache License 2.0 |
src/Day09.kt | jinie | 572,223,871 | false | {"Kotlin": 76283} | import kotlin.math.sign
//Advent of Code 2022 Day 9, Rope Physics
class Day09 {
private class Rope(knotAmt: Int){
val knots = mutableListOf<Point2d>()
val tailPositions = mutableSetOf<Pair<Int,Int>>()
val maxKnotDistance = 1
init {
tailPositions.add(Pair(0,0))
for(i in 1..knotAmt){
val knot = Point2d(0,0)
knots.add(knot)
tailPositions.add(Pair(knot.x,knot.y))
}
}
fun move(dir: String, amt: Int){
for(j in 0 until amt){
when(dir){
"U" -> knots[0].y++
"D" -> knots[0].y--
"R" -> knots[0].x++
"L" -> knots[0].x--
}
for(i in 1 until knots.size){
if(knots[i-1].chebyshevDistance(knots[i]) > maxKnotDistance){
val knot = knots[i]
val prevKnot = knots[i-1]
val xDelta = (prevKnot.x - knot.x).sign
val yDelta = (prevKnot.y - knot.y).sign
knot.x += xDelta
knot.y += yDelta
}
}
tailPositions.add(Pair(knots.last().x,knots.last().y))
}
}
}
fun part1(input: List<String>): Int {
val rope = Rope(2)
input.forEach {
val (d,v) = it.trim().split(" ")
rope.move(d, v.toInt())
}
return rope.tailPositions.size
}
fun part2(input: List<String>): Int {
val rope = Rope(10)
input.forEach {
val (d,v) = it.trim().split(" ")
rope.move(d, v.toInt())
}
return rope.tailPositions.size
}
}
fun main(){
val testInput = readInput("Day09_test")
check(Day09().part1(testInput) == 13)
measureTimeMillisPrint {
val input = readInput("Day09")
println("Part 1: ${Day09().part1(input)}")
println("Part 2: ${Day09().part2(input)}")
}
} | 0 | Kotlin | 0 | 0 | 4b994515004705505ac63152835249b4bc7b601a | 2,096 | aoc-22-kotlin | Apache License 2.0 |
voice-search/voice-search-impl/src/main/java/com/duckduckgo/voice/impl/remoteconfig/VoiceSearchFeatureModels.kt | hojat72elect | 822,396,044 | false | {"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784} |
package com.duckduckgo.voice.impl.remoteconfig
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class VoiceSearchSetting(
@field:Json(name = "excludedManufacturers")
val excludedManufacturers: List<Manufacturer>,
@field:Json(name = "excludedLocales")
val excludedLocales: List<Locale> = emptyList(),
@field:Json(name = "minVersion")
val minVersion: Int,
)
@JsonClass(generateAdapter = true)
data class Manufacturer(
@field:Json(name = "name")
val name: String,
)
@JsonClass(generateAdapter = true)
data class Locale(
@field:Json(name = "name")
val name: String,
)
| 0 | Kotlin | 0 | 0 | b89591136b60933d6a03fac43a38ee183116b7f8 | 668 | DuckDuckGo | Apache License 2.0 |
ui/src/main/java/app/allever/android/lib/demo/ui/RippleFragment.kt | devallever | 522,186,250 | false | {"Kotlin": 581282, "Java": 333458, "C++": 14228, "Makefile": 1672, "CMake": 1635, "C": 1050} | package app.allever.android.lib.demo.ui
import app.allever.android.lib.common.BaseFragment
import app.allever.android.lib.demo.databinding.FragmentRippleBinding
import app.allever.android.lib.mvvm.base.BaseViewModel
class RippleFragment: BaseFragment<FragmentRippleBinding, BaseViewModel>() {
override fun inflate() = FragmentRippleBinding.inflate(layoutInflater)
override fun init() {
}
} | 1 | Kotlin | 0 | 2 | 6d781e9e3d1754784712986e597ffbac518f4764 | 405 | AndroidSampleLibs | Apache License 2.0 |
ui/src/main/java/app/allever/android/lib/demo/ui/RippleFragment.kt | devallever | 522,186,250 | false | {"Kotlin": 581282, "Java": 333458, "C++": 14228, "Makefile": 1672, "CMake": 1635, "C": 1050} | package app.allever.android.lib.demo.ui
import app.allever.android.lib.common.BaseFragment
import app.allever.android.lib.demo.databinding.FragmentRippleBinding
import app.allever.android.lib.mvvm.base.BaseViewModel
class RippleFragment: BaseFragment<FragmentRippleBinding, BaseViewModel>() {
override fun inflate() = FragmentRippleBinding.inflate(layoutInflater)
override fun init() {
}
} | 1 | Kotlin | 0 | 2 | 6d781e9e3d1754784712986e597ffbac518f4764 | 405 | AndroidSampleLibs | Apache License 2.0 |
DiscernoPet/app/src/main/java/com/mobile/discernopet/MyAppNavigation.kt | discerno-pet | 804,957,302 | false | {"Kotlin": 49918} | package com.mobile.discernopet
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.mobile.discernopet.ui.screens.HomeScreen
import com.mobile.discernopet.ui.screens.LoginPage
import com.mobile.discernopet.ui.screens.SignUpPage
@Composable
fun MyAppNavigation(modifier: Modifier = Modifier, authViewModel: AuthViewModel) {
val navController = rememberNavController()
NavHost(navController = navController, startDestination = "login", builder = {
composable("login") {
LoginPage(modifier, navController, authViewModel)
}
composable("signup") {
SignUpPage(modifier, navController, authViewModel)
}
composable("home") {
HomeScreen(modifier, navController, authViewModel)
}
})
} | 0 | Kotlin | 0 | 1 | 58f8e6aa8b4add6b027c91c3bc957da3de880cfd | 957 | mobile-android | MIT License |
imx-core-sdk-kotlin-jvm/generated/src/main/kotlin/com/immutable/sdk/api/WithdrawalsApi.kt | immutable | 467,767,205 | false | {"Kotlin": 668106, "Java": 131024, "Mustache": 29745, "Solidity": 10068} | /**
* Immutable X API
*
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 0.1
* Contact: <EMAIL>
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package com.immutable.sdk.api
import com.immutable.sdk.api.model.CreateWithdrawalRequest
import com.immutable.sdk.api.model.CreateWithdrawalResponse
import com.immutable.sdk.api.model.GetSignableWithdrawalRequest
import com.immutable.sdk.api.model.GetSignableWithdrawalResponse
import com.immutable.sdk.api.model.ListWithdrawalsResponse
import com.immutable.sdk.api.model.Withdrawal
import org.openapitools.client.infrastructure.ApiClient
import org.openapitools.client.infrastructure.ApiErrorModel
import org.openapitools.client.infrastructure.ClientException
import org.openapitools.client.infrastructure.ClientError
import org.openapitools.client.infrastructure.ServerException
import org.openapitools.client.infrastructure.ServerError
import org.openapitools.client.infrastructure.MultiValueMap
import org.openapitools.client.infrastructure.RequestConfig
import org.openapitools.client.infrastructure.RequestMethod
import org.openapitools.client.infrastructure.ResponseType
import org.openapitools.client.infrastructure.Success
import org.openapitools.client.infrastructure.toMultiValue
class WithdrawalsApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) {
companion object {
@JvmStatic
val defaultBasePath: String by lazy {
System.getProperties().getProperty("org.openapitools.client.baseUrl", "https://api.ropsten.x.immutable.com")
}
}
/**
* Creates a withdrawal of a token
* Creates a withdrawal
* @param createWithdrawalRequest create a withdrawal
* @param xImxEthAddress eth address (optional)
* @param xImxEthSignature eth signature (optional)
* @return CreateWithdrawalResponse
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun createWithdrawal(createWithdrawalRequest: CreateWithdrawalRequest, xImxEthAddress: kotlin.String? = null, xImxEthSignature: kotlin.String? = null) : CreateWithdrawalResponse {
val localVariableConfig = createWithdrawalRequestConfig(createWithdrawalRequest = createWithdrawalRequest, xImxEthAddress = xImxEthAddress, xImxEthSignature = xImxEthSignature)
val localVarResponse = request<CreateWithdrawalRequest, CreateWithdrawalResponse>(
localVariableConfig
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as CreateWithdrawalResponse
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
val errorModel = localVarError.body?.let { ApiErrorModel(localVarError.body) }
throw ClientException("${localVarError.statusCode} ${errorModel?.message ?: localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse, errorModel)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
val errorModel = localVarError.body?.let { ApiErrorModel(localVarError.body) }
throw ServerException("${localVarError.statusCode} ${errorModel?.message ?: localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse, errorModel)
}
}
}
/**
* To obtain the request config of the operation createWithdrawal
*
* @param createWithdrawalRequest create a withdrawal
* @param xImxEthAddress eth address (optional)
* @param xImxEthSignature eth signature (optional)
* @return RequestConfig
*/
fun createWithdrawalRequestConfig(createWithdrawalRequest: CreateWithdrawalRequest, xImxEthAddress: kotlin.String?, xImxEthSignature: kotlin.String?) : RequestConfig<CreateWithdrawalRequest> {
val localVariableBody = createWithdrawalRequest
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
xImxEthAddress?.apply { localVariableHeaders["x-imx-eth-address"] = this.toString() }
xImxEthSignature?.apply { localVariableHeaders["x-imx-eth-signature"] = this.toString() }
return RequestConfig(
method = RequestMethod.POST,
path = "/v1/withdrawals",
query = localVariableQuery,
headers = localVariableHeaders,
body = localVariableBody
)
}
/**
* Gets details of a signable withdrawal
* Gets details of a signable withdrawal
* @param getSignableWithdrawalRequest get details of signable withdrawal
* @return GetSignableWithdrawalResponse
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getSignableWithdrawal(getSignableWithdrawalRequest: GetSignableWithdrawalRequest) : GetSignableWithdrawalResponse {
val localVariableConfig = getSignableWithdrawalRequestConfig(getSignableWithdrawalRequest = getSignableWithdrawalRequest)
val localVarResponse = request<GetSignableWithdrawalRequest, GetSignableWithdrawalResponse>(
localVariableConfig
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as GetSignableWithdrawalResponse
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
val errorModel = localVarError.body?.let { ApiErrorModel(localVarError.body) }
throw ClientException("${localVarError.statusCode} ${errorModel?.message ?: localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse, errorModel)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
val errorModel = localVarError.body?.let { ApiErrorModel(localVarError.body) }
throw ServerException("${localVarError.statusCode} ${errorModel?.message ?: localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse, errorModel)
}
}
}
/**
* To obtain the request config of the operation getSignableWithdrawal
*
* @param getSignableWithdrawalRequest get details of signable withdrawal
* @return RequestConfig
*/
fun getSignableWithdrawalRequestConfig(getSignableWithdrawalRequest: GetSignableWithdrawalRequest) : RequestConfig<GetSignableWithdrawalRequest> {
val localVariableBody = getSignableWithdrawalRequest
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
return RequestConfig(
method = RequestMethod.POST,
path = "/v1/signable-withdrawal-details",
query = localVariableQuery,
headers = localVariableHeaders,
body = localVariableBody
)
}
/**
* Gets details of withdrawal with the given ID
* Gets details of withdrawal with the given ID
* @param id Withdrawal ID
* @return Withdrawal
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun getWithdrawal(id: kotlin.String) : Withdrawal {
val localVariableConfig = getWithdrawalRequestConfig(id = id)
val localVarResponse = request<Unit, Withdrawal>(
localVariableConfig
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as Withdrawal
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
val errorModel = localVarError.body?.let { ApiErrorModel(localVarError.body) }
throw ClientException("${localVarError.statusCode} ${errorModel?.message ?: localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse, errorModel)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
val errorModel = localVarError.body?.let { ApiErrorModel(localVarError.body) }
throw ServerException("${localVarError.statusCode} ${errorModel?.message ?: localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse, errorModel)
}
}
}
/**
* To obtain the request config of the operation getWithdrawal
*
* @param id Withdrawal ID
* @return RequestConfig
*/
fun getWithdrawalRequestConfig(id: kotlin.String) : RequestConfig<Unit> {
val localVariableBody = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
return RequestConfig(
method = RequestMethod.GET,
path = "/v1/withdrawals/{id}".replace("{"+"id"+"}", "$id"),
query = localVariableQuery,
headers = localVariableHeaders,
body = localVariableBody
)
}
/**
* Get a list of withdrawals
* Get a list of withdrawals
* @param withdrawnToWallet Withdrawal has been transferred to user's Layer 1 wallet (optional)
* @param rollupStatus Status of the on-chain batch confirmation for this withdrawal (optional)
* @param pageSize Page size of the result (optional)
* @param cursor Cursor (optional)
* @param orderBy Property to sort by (optional)
* @param direction Direction to sort (asc/desc) (optional)
* @param user Ethereum address of the user who submitted this withdrawal (optional)
* @param status Status of this withdrawal (optional)
* @param minTimestamp Minimum timestamp for this deposit, in ISO 8601 UTC format. Example: '2022-05-27T00:10:22Z' (optional)
* @param maxTimestamp Maximum timestamp for this deposit, in ISO 8601 UTC format. Example: '2022-05-27T00:10:22Z' (optional)
* @param tokenType Token type of the withdrawn asset (optional)
* @param tokenId ERC721 Token ID of the minted asset (optional)
* @param assetId Internal IMX ID of the minted asset (optional)
* @param tokenAddress Token address of the withdrawn asset (optional)
* @param tokenName Token name of the withdrawn asset (optional)
* @param minQuantity Min quantity for the withdrawn asset (optional)
* @param maxQuantity Max quantity for the withdrawn asset (optional)
* @param metadata JSON-encoded metadata filters for the withdrawn asset (optional)
* @return ListWithdrawalsResponse
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun listWithdrawals(withdrawnToWallet: kotlin.Boolean? = null, rollupStatus: kotlin.String? = null, pageSize: kotlin.Int? = null, cursor: kotlin.String? = null, orderBy: kotlin.String? = null, direction: kotlin.String? = null, user: kotlin.String? = null, status: kotlin.String? = null, minTimestamp: kotlin.String? = null, maxTimestamp: kotlin.String? = null, tokenType: kotlin.String? = null, tokenId: kotlin.String? = null, assetId: kotlin.String? = null, tokenAddress: kotlin.String? = null, tokenName: kotlin.String? = null, minQuantity: kotlin.String? = null, maxQuantity: kotlin.String? = null, metadata: kotlin.String? = null) : ListWithdrawalsResponse {
val localVariableConfig = listWithdrawalsRequestConfig(withdrawnToWallet = withdrawnToWallet, rollupStatus = rollupStatus, pageSize = pageSize, cursor = cursor, orderBy = orderBy, direction = direction, user = user, status = status, minTimestamp = minTimestamp, maxTimestamp = maxTimestamp, tokenType = tokenType, tokenId = tokenId, assetId = assetId, tokenAddress = tokenAddress, tokenName = tokenName, minQuantity = minQuantity, maxQuantity = maxQuantity, metadata = metadata)
val localVarResponse = request<Unit, ListWithdrawalsResponse>(
localVariableConfig
)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as ListWithdrawalsResponse
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
val errorModel = localVarError.body?.let { ApiErrorModel(localVarError.body) }
throw ClientException("${localVarError.statusCode} ${errorModel?.message ?: localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse, errorModel)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
val errorModel = localVarError.body?.let { ApiErrorModel(localVarError.body) }
throw ServerException("${localVarError.statusCode} ${errorModel?.message ?: localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse, errorModel)
}
}
}
/**
* To obtain the request config of the operation listWithdrawals
*
* @param withdrawnToWallet Withdrawal has been transferred to user's Layer 1 wallet (optional)
* @param rollupStatus Status of the on-chain batch confirmation for this withdrawal (optional)
* @param pageSize Page size of the result (optional)
* @param cursor Cursor (optional)
* @param orderBy Property to sort by (optional)
* @param direction Direction to sort (asc/desc) (optional)
* @param user Ethereum address of the user who submitted this withdrawal (optional)
* @param status Status of this withdrawal (optional)
* @param minTimestamp Minimum timestamp for this deposit, in ISO 8601 UTC format. Example: '2022-05-27T00:10:22Z' (optional)
* @param maxTimestamp Maximum timestamp for this deposit, in ISO 8601 UTC format. Example: '2022-05-27T00:10:22Z' (optional)
* @param tokenType Token type of the withdrawn asset (optional)
* @param tokenId ERC721 Token ID of the minted asset (optional)
* @param assetId Internal IMX ID of the minted asset (optional)
* @param tokenAddress Token address of the withdrawn asset (optional)
* @param tokenName Token name of the withdrawn asset (optional)
* @param minQuantity Min quantity for the withdrawn asset (optional)
* @param maxQuantity Max quantity for the withdrawn asset (optional)
* @param metadata JSON-encoded metadata filters for the withdrawn asset (optional)
* @return RequestConfig
*/
fun listWithdrawalsRequestConfig(withdrawnToWallet: kotlin.Boolean?, rollupStatus: kotlin.String?, pageSize: kotlin.Int?, cursor: kotlin.String?, orderBy: kotlin.String?, direction: kotlin.String?, user: kotlin.String?, status: kotlin.String?, minTimestamp: kotlin.String?, maxTimestamp: kotlin.String?, tokenType: kotlin.String?, tokenId: kotlin.String?, assetId: kotlin.String?, tokenAddress: kotlin.String?, tokenName: kotlin.String?, minQuantity: kotlin.String?, maxQuantity: kotlin.String?, metadata: kotlin.String?) : RequestConfig<Unit> {
val localVariableBody = null
val localVariableQuery: MultiValueMap = mutableMapOf<kotlin.String, List<kotlin.String>>()
.apply {
if (withdrawnToWallet != null) {
put("withdrawn_to_wallet", listOf(withdrawnToWallet.toString()))
}
if (rollupStatus != null) {
put("rollup_status", listOf(rollupStatus.toString()))
}
if (pageSize != null) {
put("page_size", listOf(pageSize.toString()))
}
if (cursor != null) {
put("cursor", listOf(cursor.toString()))
}
if (orderBy != null) {
put("order_by", listOf(orderBy.toString()))
}
if (direction != null) {
put("direction", listOf(direction.toString()))
}
if (user != null) {
put("user", listOf(user.toString()))
}
if (status != null) {
put("status", listOf(status.toString()))
}
if (minTimestamp != null) {
put("min_timestamp", listOf(minTimestamp.toString()))
}
if (maxTimestamp != null) {
put("max_timestamp", listOf(maxTimestamp.toString()))
}
if (tokenType != null) {
put("token_type", listOf(tokenType.toString()))
}
if (tokenId != null) {
put("token_id", listOf(tokenId.toString()))
}
if (assetId != null) {
put("asset_id", listOf(assetId.toString()))
}
if (tokenAddress != null) {
put("token_address", listOf(tokenAddress.toString()))
}
if (tokenName != null) {
put("token_name", listOf(tokenName.toString()))
}
if (minQuantity != null) {
put("min_quantity", listOf(minQuantity.toString()))
}
if (maxQuantity != null) {
put("max_quantity", listOf(maxQuantity.toString()))
}
if (metadata != null) {
put("metadata", listOf(metadata.toString()))
}
}
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
return RequestConfig(
method = RequestMethod.GET,
path = "/v1/withdrawals",
query = localVariableQuery,
headers = localVariableHeaders,
body = localVariableBody
)
}
}
| 2 | Kotlin | 2 | 5 | 4a823d30db92356c325140874f5ba708547585ca | 20,439 | imx-core-sdk-kotlin-jvm | Apache License 2.0 |
src/rider/main/kotlin/com/jetbrains/rider/plugins/unreal/actions/InstallActions.kt | SmelJey | 280,050,545 | true | {"C++": 225577, "C#": 76880, "Kotlin": 68267, "CMake": 797, "C": 198, "Batchfile": 41} | package com.jetbrains.rider.plugins.unreal.actions
import com.intellij.notification.Notification
import com.intellij.notification.NotificationAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.jetbrains.rider.model.PluginInstallLocation
import com.jetbrains.rider.model.rdRiderModel
import com.jetbrains.rider.projectView.solution
open class InstallEditorPluginToEngineAction(private val text: String = "Install in Engine") : NotificationAction(text) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
notification.expire()
val project = e.project ?: return
e.presentation.isEnabled = false
project.solution.rdRiderModel.installEditorPlugin.fire(PluginInstallLocation.Engine)
}
}
open class InstallEditorPluginToGameAction(private val text: String = "Install in Game") : NotificationAction(text) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
notification.expire()
val project = e.project ?: return
e.presentation.isEnabled = false
project.solution.rdRiderModel.installEditorPlugin.fire(PluginInstallLocation.Game)
}
} | 0 | null | 0 | 0 | 591c42c9b7a0bf6f7c97121d6982ca118ec68f96 | 1,183 | UnrealLink | Apache License 2.0 |
src/test/kotlin/year2022/day06/ProblemTest.kt | Ddxcv98 | 573,823,241 | false | {"Kotlin": 164514} | package year2022.day06
import kotlin.test.Test
import kotlin.test.assertEquals
class ProblemTest {
private val problem = Problem()
@Test
fun part1() {
assertEquals(7, problem.part1())
}
@Test
fun part2() {
assertEquals(19, problem.part2())
}
}
| 0 | Kotlin | 0 | 0 | 0164fa1eca1660fcaeb15a9e17e5ce779d2f7b61 | 292 | advent-of-code | The Unlicense |
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/Teleop/Testing/TestSlide.kt | MostlyOperational18119 | 792,554,577 | false | {"Git Config": 1, "Gradle": 7, "Java Properties": 1, "Shell": 1, "Text": 10, "Ignore List": 2, "Batchfile": 1, "Markdown": 7, "INI": 1, "YAML": 1, "Java": 116, "XML": 12, "Kotlin": 53} | package org.firstinspires.ftc.teamcode.Teleop.Testing
import com.qualcomm.robotcore.hardware.DcMotor
import org.firstinspires.ftc.teamcode.DriveMethods
import org.firstinspires.ftc.teamcode.Variables
class testSlide: DriveMethods() {
override fun runOpMode() {
initMotorsSecondBot()
Variables.slideMotor?.mode = DcMotor.RunMode.STOP_AND_RESET_ENCODER
Variables.slideMotor?.mode = DcMotor.RunMode.RUN_USING_ENCODER
Variables.slideMotor?.zeroPowerBehavior = DcMotor.ZeroPowerBehavior.BRAKE
while (opModeIsActive()) {
Variables.slideMotor?.power = 1.0
}
}
} | 0 | Java | 0 | 0 | eabd8a0691079c43e61f9ff65a811cc2c6d8ce25 | 626 | Mostly-Operational-Center-Stage | BSD 3-Clause Clear License |
src/dorkbox/console/input/MacOsTerminal.kt | dorkbox | 25,707,709 | false | {"Gradle Kotlin DSL": 2, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 27, "INI": 1, "Java": 9} | /*
* Copyright 2023 dorkbox, llc
*
* 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 dorkbox.console.input
import com.sun.jna.ptr.IntByReference
import dorkbox.jna.linux.CLibraryPosix
import dorkbox.jna.macos.CLibraryApple
import dorkbox.jna.macos.CLibraryApple.TIOCGWINSZ
import dorkbox.jna.macos.structs.Termios
import dorkbox.jna.macos.structs.Termios.*
import dorkbox.jna.macos.structs.Termios.Input
import dorkbox.jna.macos.structs.WindowSize
import dorkbox.os.OS
import java.io.IOException
import java.util.concurrent.*
/**
* Terminal that is used for unix platforms. Terminal initialization is handled via JNA and ioctl/tcgetattr/tcsetattr/cfmakeraw.
*
* This implementation should work for Apple osx.
*/
class MacOsTerminal : SupportedTerminal() {
// stty size logic via Mordent: https://github.com/ajalt/mordant/blob/master/mordant/src/jvmMain/kotlin/com/github/ajalt/mordant/internal/JnaMppImplsMacos.kt
// apache 2.0
// Copyright 2018 AJ Alt
companion object {
private fun runCommand(vararg args: String): Process? {
return try {
ProcessBuilder(*args).redirectInput(ProcessBuilder.Redirect.INHERIT).start()
}
catch (e: IOException) {
null
}
}
private fun parseSttySize(output: String): Pair<Int, Int>? {
val dimens = output.split(" ").mapNotNull { it.toIntOrNull() }
if (dimens.size != 2) return null
return dimens[1] to dimens[0]
}
private fun getSttySize(timeoutMs: Long): Pair<Int, Int>? {
val process = when {
// Try running stty both directly and via env, since neither one works on all systems
else -> runCommand("stty", "size") ?: runCommand("/usr/bin/env", "stty", "size")
} ?: return null
try {
if (!process.waitFor(timeoutMs, TimeUnit.MILLISECONDS)) {
return null
}
}
catch (e: InterruptedException) {
return null
}
val output = process.inputStream.bufferedReader().readText().trim()
return parseSttySize(output)
}
}
private val original = Termios()
private val termInfo = Termios()
private val inputRef = IntByReference()
init {
// save off the defaults
if (CLibraryApple.tcgetattr(0, original) != 0) {
throw IOException(CONSOLE_ERROR_INIT)
}
original.read()
// CTRL-I (tab), CTRL-M (enter) do not work
if (CLibraryApple.tcgetattr(0, termInfo) != 0) {
throw IOException(CONSOLE_ERROR_INIT)
}
termInfo.read()
and(termInfo.inputFlags, Input.IXON.inv()) // DISABLE - output flow control mediated by ^S and ^Q
and(termInfo.inputFlags, Input.IXOFF.inv()) // DISABLE - input flow control mediated by ^S and ^Q
and(termInfo.inputFlags, Input.BRKINT.inv()) // DISABLE - map BREAK to SIGINTR
and(termInfo.inputFlags, Input.INPCK.inv()) // DISABLE - enable checking of parity errors
and(termInfo.inputFlags, Input.PARMRK.inv()) // DISABLE - mark parity and framing errors
and(termInfo.inputFlags, Input.ISTRIP.inv()) // DISABLE - strip 8th bit off chars
or(termInfo.inputFlags, Input.IGNBRK) // ignore BREAK condition
and(termInfo.localFlags, Local.ICANON.inv()) // DISABLE - pass chars straight through to terminal instantly
or(termInfo.localFlags, Local.ECHOCTL) // echo control chars as ^(Char)
and(termInfo.controlFlags, Control.CSIZE.inv()) // REMOVE character size mask
and(termInfo.controlFlags, Control.PARENB.inv()) // DISABLE - parity enable
or(termInfo.controlFlags, Control.CS8) // set character size mask 8 bits
or(termInfo.controlFlags, Control.CREAD) // enable receiver
if (CLibraryApple.tcsetattr(0, TCSANOW, termInfo) != 0) {
throw IOException("Can not set terminal flags")
}
}
/**
* Restore the original terminal configuration, which can be used when shutting down the console reader. The ConsoleReader cannot be
* used after calling this method.
*/
@Throws(IOException::class)
override fun restore() {
if (CLibraryApple.tcsetattr(0, TCSANOW, original) != 0) {
throw IOException("Can not reset terminal to defaults")
}
}
/**
* Returns number of columns in the terminal.
*/
override val width: Int
get() {
return if (OS.is64bit && OS.isArm) {
//M1 doesn't work for whatever reason!
// https://github.com/ajalt/mordant/issues/86
// see https://github.com/search?q=repo%3Aajalt%2Fmordant%20detectTerminalSize&type=code
return getSttySize(100)?.first ?: DEFAULT_WIDTH
} else {
val size = WindowSize()
if (CLibraryApple.ioctl(0, TIOCGWINSZ, size) == -1) {
DEFAULT_WIDTH
}
else {
size.read()
size.ws_row.toInt()
}
}
}
/**
* Returns number of rows in the terminal.
*/
override val height: Int
get() {
return if (OS.is64bit && OS.isArm) {
//M1 doesn't work for whatever reason!
// https://github.com/ajalt/mordant/issues/86
// see https://github.com/search?q=repo%3Aajalt%2Fmordant%20detectTerminalSize&type=code
return getSttySize(100)?.second ?: DEFAULT_HEIGHT
} else {
val size = WindowSize()
if (CLibraryApple.ioctl(0, TIOCGWINSZ, size) == -1) {
DEFAULT_HEIGHT
}
else {
size.read()
size.ws_col.toInt()
}
}
}
override fun doSetEchoEnabled(enabled: Boolean) {
// have to re-get them, since flags change everything
if (CLibraryApple.tcgetattr(0, termInfo) != 0) {
logger.error("Failed to get terminal info")
}
if (enabled) {
or(termInfo.localFlags, Local.ECHO) // ENABLE Echo input characters.
}
else {
and(termInfo.localFlags, Local.ECHO.inv()) // DISABLE Echo input characters.
}
if (CLibraryApple.tcsetattr(0, TCSANOW, termInfo) != 0) {
logger.error("Can not set terminal flags")
}
}
override fun doSetInterruptEnabled(enabled: Boolean) {
// have to re-get them, since flags change everything
if (CLibraryApple.tcgetattr(0, termInfo) != 0) {
logger.error("Failed to get terminal info")
}
if (enabled) {
or(termInfo.localFlags, Local.ISIG) // ENABLE ctrl-C
}
else {
and(termInfo.localFlags, Local.ISIG.inv()) // DISABLE ctrl-C
}
if (CLibraryApple.tcsetattr(0, TCSANOW, termInfo) != 0) {
logger.error("Can not set terminal flags")
}
}
override fun doRead(): Int {
CLibraryPosix.read(0, inputRef, 1)
return inputRef.value
}
}
| 1 | null | 1 | 1 | 30b800de83d7cb06ecf33b0829120aea2c848e08 | 7,808 | Console | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/tfm/musiccommunityapp/data/repository/CommonPostRepositoryImpl.kt | luiscruzr8 | 613,985,223 | false | null | package com.tfm.musiccommunityapp.data.repository
import arrow.core.Either
import com.tfm.musiccommunityapp.data.datasource.GenericPostDatasource
import com.tfm.musiccommunityapp.domain.model.CommentDomain
import com.tfm.musiccommunityapp.domain.model.DomainError
import com.tfm.musiccommunityapp.domain.model.GenericPostDomain
import com.tfm.musiccommunityapp.domain.repository.CommonPostRepository
import java.io.File
class CommonPostRepositoryImpl(
private val commonDatasource: GenericPostDatasource
): CommonPostRepository {
override suspend fun getUserPosts(login: String, type: String?, keyword: String?):
Either<DomainError, List<GenericPostDomain>> =
commonDatasource.getUserPosts(login, type, keyword)
override suspend fun getPostsByCoordinates(
latitude: Double,
longitude: Double,
checkClosest: Boolean
): Either<DomainError, List<GenericPostDomain>> =
commonDatasource.getPostsByCoordinates(latitude, longitude, checkClosest)
override suspend fun getPostsByCity(city: String): Either<DomainError, List<GenericPostDomain>> =
commonDatasource.getPostsByCity(city)
override suspend fun getPostImage(postId: Long): Either<DomainError, String> =
commonDatasource.getPostImage(postId)
override suspend fun uploadPostImage(postId: Long, image: File): Either<DomainError, Long> =
commonDatasource.uploadPostImage(postId, image)
override suspend fun getPostComments(postId: Long): Either<DomainError, List<CommentDomain>> =
commonDatasource.getPostComments(postId)
override suspend fun postComment(postId: Long, commentId: Long?, comment: CommentDomain):
Either<DomainError, Long> =
commonDatasource.postComment(postId, commentId, comment)
override suspend fun deleteComment(postId: Long, commentId: Long): Either<DomainError, Unit> =
commonDatasource.deleteComment(postId, commentId)
} | 28 | Kotlin | 0 | 1 | e852d00c4b26e54a3f232e1d19b46446dbba4811 | 1,951 | android-musiccommunity | MIT License |
tools-java-gen/src/main/kotlin/com/afoxer/javagen/Main.kt | NeoChow | 187,137,725 | true | {"Rust": 152601, "Swift": 138377, "Kotlin": 26421, "C": 7920, "Java": 2939, "Objective-C": 1004, "Shell": 881} | package com.afoxer.javagen
import java.io.File
fun main(args: Array<String>) {
if (args.size < 5) {
println("Usage: javabind package_name so_name ext_libs ast_path out_path")
return
}
val pkg = args[0]
val soName = args[1]
val extLibs = args[2]
val astPath = args[3]
val outPath = args[4]
val parser = AstParser(astPath)
val astResult = parser.parseAst()
val traits = astResult.traits
val structs = astResult.structs;
val callbacks = traits.filter { it.is_callback }
for (desc in traits) {
if (desc.is_callback) {
val generator = CallbackGenerator(desc, pkg)
val javaFile = generator.generate()
javaFile.build().writeTo(File(outPath))
} else {
val generator = TraitGenerator(desc, pkg, soName, extLibs, callbacks)
val javaFile = generator.generate()
javaFile.build().writeTo(File(outPath))
}
}
for (struct in structs) {
val generator = StructGenerator(struct, pkg)
val javaFile = generator.generate()
javaFile.build().writeTo(File(outPath))
}
} | 0 | Rust | 0 | 0 | 9399c9c8c811dcfe44b12f9930f10c8748c71621 | 1,150 | rsbind | Apache License 2.0 |
week10/MovieViewer/app/src/test/java/com/wmw/movieviewer/di/ModuleTests.kt | wmwprogrammer | 268,119,454 | false | null | package com.wmw.movieviewer.di
import com.wmw.movieviewer.di.dbModule
import com.wmw.movieviewer.di.networkModule
import com.wmw.movieviewer.di.repositoryModule
import com.wmw.movieviewer.di.viewModelModule
import org.junit.Test
import org.koin.core.context.startKoin
import org.koin.core.context.stopKoin
import org.koin.test.KoinTest
import org.koin.test.check.checkModules
class ModuleTests : KoinTest {
@Test
fun `Test Koin`() {
startKoin {
modules(listOf(networkModule, viewModelModule, repositoryModule, dbModule))
}.checkModules()
stopKoin()
}
} | 0 | Kotlin | 0 | 0 | 45615152f94198900495edec827552f7f3504ac7 | 603 | RWAndroidBootcamp2020 | MIT License |
sugar-processor/src/main/kotlin/team/duckie/quackquack/sugar/processor/SugarComponentRegistrar.kt | duckie-team | 523,387,054 | false | null | /*
* Designed and developed by Duckie Team 2023.
*
* Licensed under the MIT.
* Please see full license: https://github.com/duckie-team/quack-quack-android/blob/main/LICENSE
*/
@file:Suppress("DEPRECATION")
@file:OptIn(ExperimentalCompilerApi::class)
package team.duckie.quackquack.sugar.processor
import com.google.auto.service.AutoService
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.backend.common.extensions.IrGenerationExtension
import org.jetbrains.kotlin.com.intellij.mock.MockProject
import org.jetbrains.kotlin.com.intellij.openapi.extensions.LoadingOrder
import org.jetbrains.kotlin.compiler.plugin.CompilerPluginRegistrar
import org.jetbrains.kotlin.compiler.plugin.ComponentRegistrar
import org.jetbrains.kotlin.compiler.plugin.ExperimentalCompilerApi
import org.jetbrains.kotlin.config.CompilerConfiguration
import team.duckie.quackquack.sugar.processor.ir.SugarIrExtension
import team.duckie.quackquack.sugar.processor.ir.SugarIrVisitor
import team.duckie.quackquack.util.backend.kotlinc.getLogger
/**
* ### Deprecated된 메서드를 사용하는 이유
*
* Compose Compiler의 [`Default Arguments Transform`](https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:compose/compiler/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/lower/ComposableFunctionBodyTransformer.kt;l=341-365)에
* 의해 모든 컴포저블 함수에서 default argument의 값이 null로 변경됩니다. 하지만 sugar component를
* 생성하기 위해선 default value의 값을 보존해야 합니다. 이를 위해 [SugarIrVisitor]가 Compose Compiler
* 보다 먼저 적용될 수 있도록 Compiler Plugin의 적용 순서를 조정할 수 있는 deprecated된 [registerProjectComponents]
* 메서드를 사용합니다. deprecated 되지 않은 [CompilerPluginRegistrar]를 사용하면 Compiler Plugin의 적용
* 순서를 조정할 수 없습니다.
*/
@AutoService(ComponentRegistrar::class)
class SugarComponentRegistrar : ComponentRegistrar {
override val supportsK2 = false
override fun registerProjectComponents(project: MockProject, configuration: CompilerConfiguration) {
project.extensionArea
.getExtensionPoint(IrGenerationExtension.extensionPointName)
.registerExtension(configuration.getSugarIrExtension(), LoadingOrder.FIRST, project)
}
internal companion object {
/**
* [ComponentRegistrar]의 complie test는 DeprecatedError 상태로 항상 테스트에 실패합니다.
* 이를 해결하기 위해 [SugarComponentRegistrar]의 [CompilerPluginRegistrar] 버전을 제공합니다.
* 이 함수는 오직 테스트 코드에서만 사용돼야 합니다. (테스트 환경에서는 Compose Compiler가
* 적용되지 않으니 유효합니다.)
*/
@TestOnly
internal fun asPluginRegistrar() = object : CompilerPluginRegistrar() {
override val supportsK2 = false
override fun ExtensionStorage.registerExtensions(configuration: CompilerConfiguration) {
IrGenerationExtension.registerExtension(configuration.getSugarIrExtension())
}
}
private fun CompilerConfiguration.getSugarIrExtension(): SugarIrExtension {
val sugarPath = requireNotNull(this[KEY_SUGAR_PATH]) { "sugarPath was missing." }
val poet = this[KEY_POET]?.toBooleanStrict() ?: true
return SugarIrExtension(
logger = getLogger("sugar-processor"),
sugarPath = sugarPath,
poet = poet,
)
}
}
}
| 30 | Kotlin | 4 | 57 | 30d04c7342ca409a45ba449dcf6408cf4f7bc456 | 3,127 | quack-quack-android | MIT License |
app/src/main/java/com/example/woodinvoicetest/Common.kt | MaherDeeb | 270,105,871 | false | null | package com.example.woodinvoicetest
import android.content.Context
import android.util.Log
import java.io.File
object Common {
fun getAppPath(context: Context): String {
val dir = File(
android.os.Environment.getExternalStorageDirectory().toString() +
File.separator + "invoices" + File.separator
)
if (!dir.exists()) {
dir.mkdirs()
}
return dir.path + File.separator
}
} | 0 | Kotlin | 4 | 43 | 63bdf72166f5a0bcd50d90ea569880aea91d3e83 | 465 | take_orders_app | Apache License 2.0 |
src/main/kotlin/io/github/sofiapl/ast/FictiveTypeSpecification.kt | sofiapl | 202,442,654 | false | null | package io.github.sofiapl.ast
// [[("in"/"out")] <name>]
data class FictiveTypeSpecification(
val name: String?,
val restriction: FictiveTypeDeclaration.Restriction?
): Node
| 0 | Kotlin | 0 | 0 | 47a1d617de7ffd11dfa96836633994ad10eb67fb | 183 | ast | MIT License |
src/test/kotlin/com/github/rushyverse/api/item/ItemComparatorTest.kt | Rushyverse | 578,345,187 | false | null | package com.github.rushyverse.api.item
import net.kyori.adventure.text.Component
import net.minestom.server.item.ItemStack
import net.minestom.server.item.Material
import org.junit.jupiter.api.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class ItemComparatorTest {
@Test
fun `similar should check the similarity without the amount`() {
val item1 = ItemStack.of(Material.DIAMOND)
val item2 = ItemStack.of(Material.DIAMOND)
assertTrue(ItemComparator.SIMILAR.areSame(item1, item2))
val item3 = ItemStack.of(Material.DIAMOND).withDisplayName(Component.text("Test"))
assertFalse(ItemComparator.SIMILAR.areSame(item1, item3))
val item4 = ItemStack.of(Material.DIAMOND, 2).withDisplayName(Component.text("Test"))
assertTrue(ItemComparator.SIMILAR.areSame(item3, item4))
val item5 = ItemStack.of(Material.DIAMOND_SWORD)
assertFalse(ItemComparator.SIMILAR.areSame(item1, item5))
}
@Test
fun `equals should check the similarity with the amount`() {
val item1 = ItemStack.of(Material.DIAMOND)
val item2 = ItemStack.of(Material.DIAMOND)
assertTrue(ItemComparator.EQUALS.areSame(item1, item2))
val item3 = ItemStack.of(Material.DIAMOND).withDisplayName(Component.text("Test"))
assertFalse(ItemComparator.EQUALS.areSame(item1, item3))
val item4 = ItemStack.of(Material.DIAMOND, 2).withDisplayName(Component.text("Test"))
assertFalse(ItemComparator.EQUALS.areSame(item3, item4))
val item5 = ItemStack.of(Material.DIAMOND_SWORD)
assertFalse(ItemComparator.EQUALS.areSame(item1, item5))
}
@Test
fun `custom should respect the custom comparator`() {
val comparator = ItemComparator { a, b -> a.material() == b.material() }
val item1 = ItemStack.of(Material.DIAMOND)
val item2 = ItemStack.of(Material.DIAMOND)
assertTrue(comparator.areSame(item1, item2))
val item3 = ItemStack.of(Material.DIAMOND, 2)
assertTrue(comparator.areSame(item1, item3))
val item4 = ItemStack.of(Material.DIAMOND).withDisplayName(Component.text("Test"))
assertTrue(comparator.areSame(item1, item4))
val item5 = ItemStack.of(Material.DIAMOND_SWORD)
assertFalse(comparator.areSame(item1, item5))
}
} | 0 | Kotlin | 0 | 2 | 5c29c90fe5bba716063c6a083979c2335a9a5dc3 | 2,349 | api | MIT License |
sample/src/main/kotlin/com/arianegraphql/sample/resolvers.kt | arianegraphql | 354,885,191 | false | {"Kotlin": 70789, "HTML": 20} | package com.arianegraphql.sample
import com.arianegraphql.ktx.resolvers
import com.arianegraphql.sample.model.MutationWithNullableScalar
import com.arianegraphql.sample.model.MutationWithScalarArray
import com.arianegraphql.sample.model.ProductType
import com.arianegraphql.sample.model.ResultObject
import com.example.resolver.*
val myResolvers = resolvers {
Mutation {
mutationWithEnum {
println("Received ${it.input}")
ProductType.PRODUCT_A
}
mutationWithEnumArray {
println("Received ${it.input}")
ProductType.values()
}
mutationWithNullableEnum {
println("Received ${it.input}")
null
}
mutationWithInputObject {
println("Received ${it.input}")
ResultObject("a", "b", "c", ProductType.UNKNOWN)
}
mutationWithInputObjectArray {
println("Received ${it.input}")
listOf(ResultObject("a", "b", "c", ProductType.UNKNOWN))
}
mutationWithInputObjectArray { (input) ->
println("Received $input")
null
}
mutationWithValues { (string) ->
println("Received $string")
ResultObject("a", "b", "c", ProductType.UNKNOWN)
}
mutationWithNullableValues {
val string = it.string
println("Received $string")
null
}
mutationWithInputObjectArray {
println("Received ${it.input}")
listOf(ResultObject("a", "b", "c", ProductType.UNKNOWN))
}
mutationWithScalar { (input) ->
println("Received $input")
ResultObject("a", "b", "c", ProductType.UNKNOWN)
}
resolve<MutationWithScalarArray>("mutationWithScalarArray") { (input) ->
println("Received $input")
listOf(ResultObject("a", "b", "c", ProductType.UNKNOWN))
}
resolve<MutationWithNullableScalar>("mutationWithNullableScalar") { (input) ->
println("Received $input")
null
}
}
} | 6 | Kotlin | 0 | 5 | ee11124d4e28b8af3510647b1192acdce535031d | 2,130 | ariane-server | MIT License |
src/main/kotlin/br/com/zup/ot5/chave_pix/ChavePixInexistenteException.kt | DaviLevi | 383,277,033 | true | {"Kotlin": 84053, "Smarty": 2172} | package br.com.zup.ot5.chave_pix
class ChavePixInexistenteException(
chave : String
) : RuntimeException("Chave pix '$chave' inexistente") | 0 | Kotlin | 0 | 0 | f00bfecba37e7f78e18c4d89e617d90c6fb13ea3 | 143 | orange-talents-05-template-pix-keymanager-grpc | Apache License 2.0 |
app/src/main/java/com/demo/jetpack/navigation/fragment/Fragment02.kt | woniu0936 | 750,355,893 | false | {"Kotlin": 74615} | package com.demo.jetpack.navigation.fragment
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.demo.jetpack.R
import com.demo.jetpack.core.extension.viewBinding
import com.demo.jetpack.databinding.FragmentNavigation02Binding
class Fragment02 : Fragment(R.layout.fragment_navigation_02) {
private val mBinding: FragmentNavigation02Binding by viewBinding()
private val param by lazy { arguments?.getString("param") }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Toast.makeText(activity, "param: $param", Toast.LENGTH_SHORT).show()
}
} | 0 | Kotlin | 1 | 0 | 10382f0f240ae063a4a8440098876c6ef159645e | 717 | JetpackDemo | MIT License |
demo-command/src/main/kotlin/io/holixon/cqrshexagonaldemo/demoparent/command/domain/MetaData.kt | holixon | 747,608,283 | false | {"Kotlin": 26026, "TSQL": 2855, "Shell": 72} | package io.holixon.cqrshexagonaldemo.demoparent.command.domain
import com.fasterxml.jackson.annotation.JsonProperty
data class MetaData(@field:JsonProperty("total_hits") @param:JsonProperty("total_hits") val totalHits: Long)
| 7 | Kotlin | 0 | 0 | e77edf997fc816ba7ca392fec8df1a537d6611aa | 227 | cqrs-meets-hexagonal | Apache License 2.0 |
src/test/kotlin/dev/realmkit/hellper/fixture/stat/StatFixture.kt | RealmKit | 590,912,533 | false | {"Kotlin": 376600} | /*
* Copyright (c) 2023 RealmKit
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package dev.realmkit.hellper.fixture.stat
import dev.realmkit.game.core.extension.ConstantExtensions
import dev.realmkit.game.domain.stat.document.Stat
import dev.realmkit.game.domain.stat.document.StatBase
import dev.realmkit.game.domain.stat.document.StatMultiplier
import dev.realmkit.game.domain.stat.document.StatProgression
import dev.realmkit.game.domain.stat.document.StatRate
import dev.realmkit.hellper.fixture.stat.StatBaseFixture.fixture
import dev.realmkit.hellper.fixture.stat.StatBaseFixture.invalid
import dev.realmkit.hellper.fixture.stat.StatMultiplierFixture.fixture
import dev.realmkit.hellper.fixture.stat.StatMultiplierFixture.invalid
import dev.realmkit.hellper.fixture.stat.StatProgressionFixture.fixture
import dev.realmkit.hellper.fixture.stat.StatProgressionFixture.invalid
import dev.realmkit.hellper.fixture.stat.StatRateFixture.fixture
import dev.realmkit.hellper.fixture.stat.StatRateFixture.invalid
import io.kotest.property.Arb
import io.kotest.property.arbitrary.arbitrary
/**
* # [StatFixture]
* contains all the [Stat] fixtures
*/
object StatFixture {
/**
* ## [fixture]
* creates a [Stat] with random data
*/
val Stat.Companion.fixture: Arb<Stat>
get() = arbitrary {
Stat(
base = StatBase.fixture.bind(),
rate = StatRate.fixture.bind(),
multiplier = StatMultiplier.fixture.bind(),
progression = StatProgression.fixture.bind(),
)
}
/**
* ## [invalid]
* creates a [Stat] with random invalid data
*/
val Stat.Companion.invalid: Arb<Stat>
get() = arbitrary {
Stat(
base = StatBase.invalid.bind(),
rate = StatRate.invalid.bind(),
multiplier = StatMultiplier.invalid.bind(),
progression = StatProgression.invalid.bind(),
)
}
/**
* ## [prepareToWinBattle]
* sets the stats to be very high
*/
fun Stat.prepareToWinBattle() {
base.hull.max = Double.MAX_VALUE
base.hull.current = Double.MAX_VALUE
base.shield.max = Double.MAX_VALUE
base.shield.current = Double.MAX_VALUE
base.attack = Double.MAX_VALUE
base.defense = Double.MAX_VALUE
base.speed = ConstantExtensions.DOUBLE_ONE
multiplier.critical = ConstantExtensions.DOUBLE_ONE
progression.level = ConstantExtensions.LONG_ONE
progression.experience = ConstantExtensions.LONG_ZERO
}
}
| 28 | Kotlin | 0 | 0 | 75824606b7edf018adf82af1cc588fe25c5f9de5 | 3,638 | game | MIT License |
src/main/kotlin/com/github/jozott00/wokwiintellij/runner/profileStates/WokwiSimulatorStartState.kt | Jozott00 | 737,328,628 | false | {"Kotlin": 113010, "HTML": 2436} | package com.github.jozott00.wokwiintellij.runner.profileStates
import com.github.jozott00.wokwiintellij.runner.WokwiProcessHandler
import com.github.jozott00.wokwiintellij.services.WokwiProjectService
import com.github.jozott00.wokwiintellij.simulator.args.WokwiArgs
import com.intellij.execution.ExecutionResult
import com.intellij.execution.Executor
import com.intellij.execution.configurations.RunProfileState
import com.intellij.execution.runners.ProgramRunner
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
class WokwiSimulatorStartState(private val project: Project, private val waitForDebugger: Boolean) : RunProfileState {
override fun execute(executor: Executor?, runner: ProgramRunner<*>) = object : ExecutionResult {
override fun getExecutionConsole() = null
override fun getActions(): Array<AnAction> {
return emptyArray()
}
override fun getProcessHandler() = WokwiStartProcessHandler(project, waitForDebugger)
// override fun getProcessHandler() = WokwiRunnerProcessHandler(project)
}
}
class WokwiStartProcessHandler(project: Project, waitForDebugger: Boolean) :
WokwiProcessHandler() {
private val wokwiService = project.service<WokwiProjectService>()
init {
wokwiService.startSimulator(this, waitForDebugger)
}
override fun destroyProcessImpl() {
notifyProcessTerminated(0)
}
override fun detachProcessImpl() {
notifyProcessDetached()
}
override fun detachIsDefault() = false
override fun getProcessInput() = null
override fun onStarted(runArgs: WokwiArgs) {
this.destroyProcess()
}
} | 0 | Kotlin | 0 | 3 | 89bc09e4a0a95c17d039f873f8466f1984bc52d9 | 1,746 | wokwi-intellij | MIT License |
src/main/kotlin/MathUtils.kt | evilthreads669966 | 721,369,481 | false | {"Kotlin": 16467} | /*
Copyright 2023 <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.
*/
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.Executors
import java.util.concurrent.Future
import java.util.concurrent.ThreadPoolExecutor
object MathUtils{
@JvmStatic
@Throws(NumberZeroException::class, NegativeNumberException::class)
fun gcf(numbers: SortedSet<Long>): FactorResult<Long> {
numbers.forEach {
if(it == 0L) throw NumberZeroException()
if(it < 0L) throw NegativeNumberException()
}
val factors = ConcurrentHashMap<Long, MutableList<Long>>()
numbers.forEach { num ->
factors[num] = mutableListOf()
}
var pool = Executors.newFixedThreadPool(numbers.size) as ThreadPoolExecutor
val tasks = mutableListOf<Future<*>>()
numbers.forEach { num ->
val task = pool.submit {
for (i in 1..num) {
if (num % i == 0L) {
synchronized(factors){
factors[num]!!.add(i)
}
}
}
}
tasks.add(task)
}
tasks.forEach { it.get() }
if (numbers.size == 1) {
factors[numbers.first()]!!
return FactorResult(factors[numbers.first()]!!.last(), factors[numbers.first()]!!, factors)
}
val commonFactors = Collections.synchronizedList(mutableListOf<Long>())
numbers.drop(1)
tasks.clear()
if(pool.maximumPoolSize < factors[factors.keys.first()]!!.size)
pool.maximumPoolSize = factors[factors.keys.first()]!!.size
factors[factors.keys.first()]!!.forEach { factor ->
val task = pool.submit {
var count = 0
numbers.forEach { num ->
if (factors[num]!!.contains(factor))
count++
}
if (count == numbers.size)
synchronized(commonFactors){
commonFactors.add(factor)
}
}
tasks.add(task)
}
tasks.forEach { it.get() }
val result = FactorResult<Long>(commonFactors.max(), commonFactors, factors)
return result
}
/*this is wierd and hacked together. It needs to be rewritten*/
@JvmStatic
fun lcm(numbers: List<Int>): Int{
var lcm: Int = numbers.max()
loop@while(true){
for(number in numbers) {
if(lcm % number != 0) {
lcm++
continue@loop
}
}
return lcm
}
}
} | 0 | Kotlin | 0 | 1 | 53f1cf3a3b1a31649d93e2c07ca2d057258ab866 | 3,222 | fraction_calculator | Apache License 2.0 |
src/main/kotlin/com/github/durun/nitron/inout/database/FileDatabaseBase.kt | Durun | 212,494,212 | false | null | package com.github.durun.nitron.inout.database
import org.jetbrains.exposed.sql.Database
import java.nio.file.Path
import java.sql.Driver
import kotlin.reflect.KClass
import kotlin.reflect.jvm.jvmName
internal class FileDatabaseBase(
private val driver: KClass<out Driver>,
private val urlMap: (Path) -> String,
private val patch: () -> Unit = {}
) : FileDatabase {
override fun connect(path: Path): Database {
val db = Database.connect(urlMap(path), driver.jvmName)
patch()
return db
}
} | 9 | Kotlin | 0 | 0 | d61f5c0f3884413fc42ce24aaa12921676c1b1b8 | 546 | nitron | MIT License |
wearApp/src/main/java/dev/johnoreilly/starwars/wearApp/people/PeopleList.kt | joreilly | 357,294,402 | false | null | package dev.johnoreilly.starwars.wearApp.people
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.Card
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.ScalingLazyColumn
import androidx.wear.compose.material.ScalingLazyListState
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.rememberScalingLazyListState
import dev.johnoreilly.starwars.fragment.PersonFragment
import dev.johnoreilly.starwars.wearApp.compose.rotaryEventHandler
@Composable
fun PeopleList(
people: List<PersonFragment>,
scrollState: ScalingLazyListState = rememberScalingLazyListState(),
) {
val configuration = LocalConfiguration.current
val verticalPadding = remember {
if (configuration.isScreenRound) 20.dp else 0.dp
}
ScalingLazyColumn(
modifier = Modifier
.rotaryEventHandler(scrollState)
.padding(horizontal = 4.dp),
contentPadding = PaddingValues(
horizontal = 8.dp,
vertical = 8.dp + verticalPadding
),
state = scrollState,
) {
items(people.size) {
PersonView(people[it])
}
}
}
@Composable
fun PersonView(person: PersonFragment) {
Card(onClick = { }) {
Column(modifier = Modifier.fillMaxWidth()) {
Text(person.name, style = MaterialTheme.typography.title3)
Text(
person.homeworld.name,
style = MaterialTheme.typography.body1,
color = Color.DarkGray
)
}
}
}
| 0 | Kotlin | 10 | 141 | 41fc40dd50ce18a0034bc1cd270b74e040fba2e1 | 2,017 | StarWars | Apache License 2.0 |
BlurBenchmark/src/main/java/at/favre/app/blurbenchmark/adapter/BenchmarkResultAdapter.kt | Parseus | 181,662,644 | true | {"Kotlin": 208376, "C": 53487, "RenderScript": 8951, "C++": 3637, "Makefile": 641} | package at.favre.app.blurbenchmark.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.RecyclerView
import at.favre.app.blurbenchmark.R
import at.favre.app.blurbenchmark.models.BenchmarkWrapper
/**
* Created by PatrickF on 25.05.2015.
*/
class BenchmarkResultAdapter(private val results: List<BenchmarkWrapper>, private val fragmentManager: FragmentManager) : RecyclerView.Adapter<BenchmarkResultHolder>() {
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): BenchmarkResultHolder {
val inflater = viewGroup.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val convertView = inflater.inflate(R.layout.list_benchmark_result, viewGroup, false)
return BenchmarkResultHolder(convertView, fragmentManager)
}
override fun onBindViewHolder(benchmarkResultHolder: BenchmarkResultHolder, i: Int) {
benchmarkResultHolder.onBind(results[i])
}
override fun getItemCount(): Int {
return results.size
}
}
| 0 | Kotlin | 1 | 0 | f99cf1cb6c3843a95c53758fa2210980a205ad52 | 1,134 | BlurTestAndroid | Apache License 2.0 |
src/main/kotlin/com/timoh/aoc2018/first/part1/solution.kt | TimoHanisch | 159,952,280 | false | null | package com.timoh.aoc2018.first.part1
import java.io.File
fun main(args: Array<String>) {
val resource = ClassLoader.getSystemClassLoader().getResource("input/input1")
val value = File(resource.toURI())
.useLines { it.toList() }
.fold(0L) { acc, line -> acc + line.toLong() }
println(value)
} | 0 | Kotlin | 0 | 0 | 6487bb44daeb13763a90ac33c0a706d7641cfbb4 | 323 | aoc2018 | MIT License |
data/RF03521/rnartist.kts | fjossinet | 449,239,232 | false | {"Kotlin": 8214424} | import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF03521"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
2 to 3
98 to 99
}
value = "#3e5e01"
}
color {
location {
5 to 11
90 to 96
}
value = "#ce2c60"
}
color {
location {
13 to 16
83 to 86
}
value = "#ce0862"
}
color {
location {
17 to 20
78 to 81
}
value = "#5b5c97"
}
color {
location {
22 to 23
73 to 74
}
value = "#4cb21a"
}
color {
location {
24 to 27
67 to 70
}
value = "#5ce2d4"
}
color {
location {
28 to 29
64 to 65
}
value = "#f0cabf"
}
color {
location {
30 to 34
56 to 60
}
value = "#cd8aae"
}
color {
location {
37 to 41
48 to 52
}
value = "#d5a051"
}
color {
location {
4 to 4
97 to 97
}
value = "#d5d408"
}
color {
location {
12 to 12
87 to 89
}
value = "#884a85"
}
color {
location {
17 to 16
82 to 82
}
value = "#6e3aed"
}
color {
location {
21 to 21
75 to 77
}
value = "#47d7e0"
}
color {
location {
24 to 23
71 to 72
}
value = "#a4dfbf"
}
color {
location {
28 to 27
66 to 66
}
value = "#1f27a7"
}
color {
location {
30 to 29
61 to 63
}
value = "#221f74"
}
color {
location {
35 to 36
53 to 55
}
value = "#ed057a"
}
color {
location {
42 to 47
}
value = "#563fef"
}
color {
location {
1 to 1
}
value = "#4d1249"
}
color {
location {
100 to 100
}
value = "#181c3d"
}
}
} | 0 | Kotlin | 0 | 0 | 3016050675602d506a0e308f07d071abf1524b67 | 3,099 | Rfam-for-RNArtist | MIT License |
app/src/main/java/com/example/soundmonoapp/AudioMonitorService.kt | gcapuccia | 871,057,302 | false | {"Kotlin": 14939} | import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.media.AudioFormat
import android.media.AudioRecord
import android.media.AudioTrack
import android.media.MediaRecorder
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
class AudioMonitorService : Service() {
private val sampleRate = 44100
private val bufferSize = AudioRecord.getMinBufferSize(sampleRate,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT)
@SuppressLint("MissingPermission")
private val audioRecorder = AudioRecord(MediaRecorder.AudioSource.MIC,
sampleRate, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, bufferSize)
private val audioPlayer = AudioTrack(
AudioTrack.MODE_STREAM, sampleRate,
AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, bufferSize,
AudioTrack.MODE_STREAM)
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel()
}
val notification: Notification = NotificationCompat.Builder(this, "CHANNEL_ID")
.setContentTitle("SOUNDMONOAPP")
.setContentText("Audio monitoring in progress")
.setSmallIcon(android.R.drawable.ic_dialog_info)
.build()
startForeground(1, notification)
audioRecorder.startRecording()
audioPlayer.play()
Thread {
val audioBuffer = ShortArray(bufferSize)
while (true) {
val readBytes = audioRecorder.read(audioBuffer, 0, bufferSize)
if (readBytes > 0) {
audioPlayer.write(audioBuffer, 0, readBytes)
}
}
}.start()
return START_STICKY
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onDestroy() {
super.onDestroy()
audioRecorder.stop()
audioPlayer.stop()
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
"CHANNEL_ID",
"Audio Monitor Channel",
NotificationManager.IMPORTANCE_DEFAULT
)
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(channel)
}
}
} | 0 | Kotlin | 0 | 0 | 50e483f1d2b795f195fabcf7e2f232d57ad8d715 | 2,668 | SoundMonoApp | MIT License |
client/src/commonMain/kotlin/com/algolia/search/dsl/strategy/DSLAlternativesAsExact.kt | algolia | 153,273,215 | false | {"Kotlin": 1346247, "Dockerfile": 163} | package com.algolia.search.dsl.strategy
import com.algolia.search.dsl.DSL
import com.algolia.search.dsl.DSLParameters
import com.algolia.search.model.search.AlternativesAsExact
/**
* DSL for building a [List] of [AlternativesAsExact].
*/
@Suppress("PropertyName")
@DSLParameters
public class DSLAlternativesAsExact(
private val alternativesAsExacts: MutableList<AlternativesAsExact> = mutableListOf()
) {
public val IgnorePlurals: AlternativesAsExact.IgnorePlurals = AlternativesAsExact.IgnorePlurals
public val SingleWordSynonym: AlternativesAsExact.SingleWordSynonym = AlternativesAsExact.SingleWordSynonym
public val MultiWordsSynonym: AlternativesAsExact.MultiWordsSynonym = AlternativesAsExact.MultiWordsSynonym
/**
* Add [this] to [alternativesAsExacts].
*/
public operator fun AlternativesAsExact.unaryPlus() {
alternativesAsExacts += this
}
public companion object : DSL<DSLAlternativesAsExact, List<AlternativesAsExact>> {
override operator fun invoke(block: DSLAlternativesAsExact.() -> Unit): List<AlternativesAsExact> {
return DSLAlternativesAsExact().apply(block).alternativesAsExacts
}
}
}
| 14 | Kotlin | 23 | 59 | 21f0c6bd3c6c69387d1dd4ea09f69a220c5eaff4 | 1,194 | algoliasearch-client-kotlin | MIT License |
app/src/main/java/com/iutcalendar/task/TaskAdapter.kt | wwwazz333 | 486,323,544 | false | {"Kotlin": 204168} | package com.iutcalendar.task
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.iutcalendar.calendrier.EventCalendrier
import com.iutcalendar.tools.vibrator.VibratorSimpleUse
import com.univlyon1.tools.agenda.R
class TaskAdapter(
var context: Context,
private var relatedEvent: EventCalendrier
) : RecyclerView.Adapter<TaskViewHolder>() {
private val personalCalendrier
get() = PersonalCalendrier.getInstance(context)
private val list
get() = personalCalendrier.getLinkedTask(relatedEvent)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskViewHolder {
val inflater = LayoutInflater.from(parent.context)
val eventView = inflater.inflate(R.layout.task_card, parent, false)
return TaskViewHolder(eventView)
}
override fun onBindViewHolder(holder: TaskViewHolder, position: Int) {
val task = list[position]
holder.apply {
text.text = task.txt
view.setOnLongClickListener {
VibratorSimpleUse.pushVibration(context)
removeTask(task, position)
return@setOnLongClickListener true
}
}
}
override fun getItemCount(): Int {
return list.size
}
private fun removeTask(taskClicked: Task, position: Int) {
val alertDialog = AlertDialog.Builder(context)
alertDialog.setTitle("Suppression")
alertDialog.setMessage(
"""
Voulez-vous supprimer cette tâche ?
"${taskClicked.txt}"
""".trimIndent()
)
alertDialog.setPositiveButton(context.getString(R.string.yes)) { dialogInterface: DialogInterface, _: Int ->
personalCalendrier.apply {
remove(context, taskClicked)
save(context)
}
Toast.makeText(context, "Tâche supprimer", Toast.LENGTH_SHORT).show()
notifyItemRemoved(position)
notifyItemRangeChanged(position, itemCount - position)
dialogInterface.dismiss()
}
alertDialog.setNegativeButton(context.getString(R.string.no)) { dialogInterface: DialogInterface, _: Int -> dialogInterface.cancel() }
alertDialog.show()
}
} | 2 | Kotlin | 0 | 0 | 95d2a6a5bb3a2d843d647563a4124847ed4b1d62 | 2,429 | AgendaLyon1 | MIT License |
src/main/kotlin/Test.kt | gblmedeiros | 133,167,034 | false | null | class Test(val layerId: Long) {
fun test() {
println(layerId)
}
} | 0 | Kotlin | 0 | 0 | f9bdf1ab379277393df2826b14ae5f78aea89f02 | 82 | spring-boot-kotlin-starter-kit | Apache License 2.0 |
backend/test/annotationdefinition/generator/FinalizeConditionTest.kt | MaxMello | 211,313,972 | false | {"JavaScript": 710246, "Kotlin": 539611, "Python": 19119, "Dockerfile": 1460, "HTML": 793, "Shell": 554, "CSS": 39} | package annotationdefinition.generator
import document.annotation.*
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
internal class FinalizeConditionTest {
private val annotationMap: AnnotationMap = mutableMapOf(
"A1" to DocumentTargetAnnotation(listOf(ValueToProbability("x", 0.8))),
"A2" to DocumentTargetAnnotation(listOf(
ValueToProbability("a", 0.7),
ValueToProbability("b", 0.8),
ValueToProbability("c", 0.9))),
"A3" to DocumentTargetAnnotation(listOf(ValueToProbability("z"))),
"A4" to SpanTargetAnnotation(setOf(
SpanTargetSingleAnnotation(setOf(Span(1, 10)), listOf(ValueToProbability(1, 0.7),
ValueToProbability(5, 1.0))),
SpanTargetSingleAnnotation(setOf(Span(2, 10)), listOf(ValueToProbability(2, 0.6))),
SpanTargetSingleAnnotation(setOf(Span(3, 10)), listOf(ValueToProbability(3, 0.9)))
)
),
"A5" to SpanTargetAnnotation(setOf(SpanTargetSingleAnnotation(setOf(Span(2, 10)), listOf(ValueToProbability(true))))),
"A6" to SpanTargetAnnotation(setOf(SpanTargetSingleAnnotation(setOf(Span(3, 10)), listOf(ValueToProbability("Hello")))))
)
@Test
fun `FinalizeCondition Always returns true`() {
assertTrue(FinalizeCondition.Always.execute(annotationMap["A1"]!!))
}
@Test
fun `FinalizeCondition ProbabilityGreaterThanEquals DocumentTarget success`() {
assertTrue(FinalizeCondition.ProbabilityGreaterThanEquals(0.6).execute(annotationMap["A1"]!!))
}
@Test
fun `FinalizeCondition ProbabilityGreaterThanEquals DocumentTarget failure`() {
assertFalse(FinalizeCondition.ProbabilityGreaterThanEquals(0.91).execute(annotationMap["A2"]!!))
}
@Test
fun `FinalizeCondition ProbabilityGreaterThanEquals SpanTarget success`() {
assertTrue(FinalizeCondition.ProbabilityGreaterThanEquals(0.6).execute(annotationMap["A4"]!!))
}
@Test
fun `FinalizeCondition ProbabilityGreaterThanEquals SpanTarget failure`() {
assertFalse(FinalizeCondition.ProbabilityGreaterThanEquals(0.75).execute(annotationMap["A4"]!!))
}
@Test
fun `FinalizeCondition ValueIn DocumentTarget success`() {
assertTrue(FinalizeCondition.ValueIn("b").execute(annotationMap["A2"]!!))
}
@Test
fun `FinalizeCondition ValueIn DocumentTarget failure`() {
assertFalse(FinalizeCondition.ValueIn("failure").execute(annotationMap["A2"]!!))
}
@Test
fun `FinalizeCondition ValueIn SpanTarget success`() {
assertTrue(FinalizeCondition.ValueIn(true).execute(annotationMap["A5"]!!))
}
@Test
fun `FinalizeCondition ValueIn SpanTarget failure`() {
assertFalse(FinalizeCondition.ValueIn(false).execute(annotationMap["A5"]!!))
}
@Test
fun `FinalizeCondition SetEquals DocumentTarget success`() {
assertTrue(FinalizeCondition.SetEquals(setOf("a", "c", "b")).execute(annotationMap["A2"]!!))
}
@Test
fun `FinalizeCondition SetEquals DocumentTarget failure`() {
assertFalse(FinalizeCondition.SetEquals(setOf("a", "b")).execute(annotationMap["A2"]!!))
}
@Test
fun `FinalizeCondition SetEquals SpanTarget success`() {
assertTrue(FinalizeCondition.SetEquals(setOf(1, 5)).execute(annotationMap["A4"]!!))
}
@Test
fun `FinalizeCondition SetEquals SpanTarget failure`() {
assertFalse(FinalizeCondition.SetEquals(setOf("Ola")).execute(annotationMap["A6"]!!))
}
@Test
fun `Not of successful And is failure`() {
assertFalse(FinalizeCondition.Not(
FinalizeCondition.And(setOf(
FinalizeCondition.ValueIn("b"),
FinalizeCondition.ProbabilityGreaterThanEquals(0.7)
))
).execute(annotationMap["A2"]!!))
}
@Test
fun `Not of successful Or is failure`() {
assertFalse(FinalizeCondition.Not(
FinalizeCondition.Or(setOf(
FinalizeCondition.ValueIn("b"),
FinalizeCondition.ProbabilityGreaterThanEquals(0.9)
))
).execute(annotationMap["A2"]!!))
}
} | 2 | JavaScript | 0 | 6 | 831e1be853a63b7059ad8aa942049eeb6f07a74e | 4,251 | ActiveAnno | MIT License |
defitrack-rest/defitrack-protocol-services/defitrack-kyberswap/src/main/java/io/defitrack/protocol/kyberswap/pooling/KyberswapEthereumPoolingMarketProvider.kt | decentri-fi | 426,174,152 | false | null | package io.defitrack.protocol.kyberswap.pooling
import io.defitrack.common.network.Network
import io.defitrack.market.pooling.PoolingMarketProvider
import io.defitrack.market.pooling.domain.PoolingMarket
import io.defitrack.protocol.Protocol
import io.defitrack.protocol.kyberswap.apr.KyberswapAPRService
import io.defitrack.protocol.kyberswap.graph.KyberswapEthereumGraphProvider
import io.defitrack.token.TokenType
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import org.springframework.stereotype.Service
@Service
class KyberswapEthereumPoolingMarketProvider(
private val kyberswapPolygonService: KyberswapEthereumGraphProvider,
private val kyberswapAPRService: KyberswapAPRService,
) : PoolingMarketProvider() {
override suspend fun fetchMarkets(): List<PoolingMarket> = coroutineScope {
val semaphore = Semaphore(10)
kyberswapPolygonService.getPoolingMarkets().map {
async {
semaphore.withPermit {
try {
val token = getToken(it.id)
val token0 = getToken(it.token0.id)
val token1 = getToken(it.token1.id)
PoolingMarket(
id = "kyberswap-ethereum-${it.id}",
network = getNetwork(),
protocol = getProtocol(),
address = it.id,
name = token.name,
symbol = token.symbol,
tokens = listOf(
token0.toFungibleToken(),
token1.toFungibleToken()
),
apr = kyberswapAPRService.getAPR(it.pair.id, getNetwork()),
marketSize = it.reserveUSD,
tokenType = TokenType.KYBER,
positionFetcher = defaultPositionFetcher(token.address)
)
} catch (ex: Exception) {
ex.printStackTrace()
null
}
}
}
}.awaitAll().filterNotNull()
}
override fun getProtocol(): Protocol {
return Protocol.KYBER_SWAP
}
override fun getNetwork(): Network {
return Network.ETHEREUM
}
} | 16 | Kotlin | 6 | 5 | e4640223e69c30f986b8b4238e026202b08a5548 | 2,544 | defi-hub | MIT License |
app/src/main/java/com/stats/nhlcompose/teams/TeamsViewModel.kt | NoNews | 345,416,215 | false | null | package com.stats.nhlcompose.teams
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.data.features.TeamsRepository
import com.stats.nhlcompose.R
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
class TeamsViewModel(private val repository: TeamsRepository) : ViewModel() {
private val state: MutableState<TeamsScreenContract.State> =
mutableStateOf(TeamsScreenContract.State.Idle)
init {
viewModelScope.launch {
observeTeams()
}
}
private suspend fun observeTeams() {
repository.observeTeams(forceReload = false)
.map { data ->
val state = when {
data.content != null -> {
val teams = requireNotNull(data.content)
TeamsScreenContract.State.Content(
teams = teams.map { team ->
TeamCardUiModel(
name = team.name,
drawableRes = team.toImageRes(),
subtitle = team.fistYearOfPlay
)
}
)
}
data.loading && data.content == null -> {
TeamsScreenContract.State.Loading
}
else -> TeamsScreenContract.State.Loading
}
state
}.collect { model ->
state.value = model
}
}
fun observeState() = state
override fun onCleared() {
super.onCleared()
}
} | 0 | Kotlin | 0 | 0 | 7548b7aeaf5cb3862397c0340f5d2150ebf578c6 | 1,845 | JetNhl | Apache License 2.0 |
src/main/kotlin/com/rootsid/wal/agent/api/model/outofband/AttachDecorator.kt | roots-id | 481,774,698 | false | {"Kotlin": 105977, "JavaScript": 16655} | package com.rootsid.wal.agent.api.model.outofband
import com.fasterxml.jackson.annotation.JsonProperty
import io.swagger.v3.oas.annotations.media.Schema
@Schema
data class AttachDecorator(
@Schema(description = "Attachment identifier", example = "3fa85f64-5717-4562-b3fc-2c963f66afa6")
var id: String,
@Schema(description = "MIME type", example = "application/json")
@JsonProperty("mime_type")
val mimeType: String = "application/json",
@Schema(description = "Attachment data", example = "3fa85f64-5717-4562-b3fc-2c963f66afa6")
val `data`: AttachDecoratorData
)
| 1 | Kotlin | 0 | 3 | f92eddedf2e476420fbb72a1f7651f0cb8498809 | 594 | wal-agent | Apache License 2.0 |
smash-ranks-android/app/src/main/java/com/garpr/android/misc/DeviceUtilsImpl.kt | charlesmadere | 41,832,700 | true | null | package com.garpr.android.misc
import android.content.Context
import androidx.core.app.ActivityManagerCompat
import com.garpr.android.extensions.activityManager
class DeviceUtilsImpl(
context: Context
) : DeviceUtils {
override val hasLowRam: Boolean = ActivityManagerCompat.isLowRamDevice(context.activityManager)
}
| 0 | Kotlin | 0 | 9 | 151b2a0f9b4d38be60c3f73344ca444f17810bfd | 333 | smash-ranks-android | The Unlicense |
oapp/src/main/java/com/example/oapp/adapter/HomeAdapter.kt | Asmewill | 415,843,980 | false | {"Kotlin": 1283675, "Java": 382535} | package com.example.oapp.adapter
import android.text.Html
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.example.oapp.R
import com.example.oapp.bean.HomeData
import com.example.oapp.utils.ImageLoader
import com.example.oapp.utils.SettingUtil
import com.example.oapp.viewmodel.CollectViewModel
/**
* Created by jsxiaoshui on 2021/6/28
*/
class HomeAdapter(private val mViewModel:CollectViewModel):BaseQuickAdapter<HomeData.DatasBean,BaseViewHolder>(R.layout.item_home_list) {
override fun convert(helper: BaseViewHolder?, item: HomeData.DatasBean?) {
helper?:return
item?:return
var tv_article_top=helper.getView<TextView>(R.id.tv_article_top)
var tv_article_fresh=helper.getView<TextView>(R.id.tv_article_fresh)
var tv_article_tag=helper.getView<TextView>(R.id.tv_article_tag)
var tv_article_author=helper.getView<TextView>(R.id.tv_article_author)
var tv_article_date=helper.getView<TextView>(R.id.tv_article_date)
var iv_article_thumbnail=helper.getView<ImageView>(R.id.iv_article_thumbnail)
var tv_article_title=helper.getView<TextView>(R.id.tv_article_title)
var tv_article_chapterName=helper.getView<TextView>(R.id.tv_article_chapterName)
var iv_like=helper.getView<ImageView>(R.id.iv_like)
if(item.isTop){
tv_article_top.visibility= View.VISIBLE
}else{
tv_article_top.visibility= View.GONE
}
if(SettingUtil.getIsNoPhotoMode()){
iv_article_thumbnail.visibility=View.GONE
}else{
iv_article_thumbnail.visibility=View.VISIBLE
if(!TextUtils.isEmpty(item.envelopePic)){
iv_article_thumbnail.visibility=View.VISIBLE
ImageLoader.loadIv(mContext, item.envelopePic!!,iv_article_thumbnail)
}else{
iv_article_thumbnail.visibility=View.GONE
}
}
if(item.fresh){
tv_article_fresh.visibility=View.VISIBLE
}else{
tv_article_fresh.visibility=View.GONE
}
if(item.tags?.size!!>0){
tv_article_tag?.setText(item.tags!!.get(0).name)
tv_article_tag.visibility=View.VISIBLE
}else{
tv_article_tag.visibility=View.GONE
}
if(!TextUtils.isEmpty(item.author)){
tv_article_author.setText(item.author)
}else{
tv_article_author.setText(item.shareUser)
}
tv_article_date.setText(item.niceDate)
tv_article_title.setText(Html.fromHtml(item.title).toString())
tv_article_chapterName.setText(item.superChapterName+"/"+item.chapterName)
if(item.collect){
iv_like.setImageResource(R.drawable.ic_like)
}else{
iv_like.setImageResource(R.drawable.ic_like_not)
}
iv_like.setOnClickListener {
if(!item.collect){
mViewModel.addCollect(item.id,helper.layoutPosition-1)
}else{
mViewModel.cancelCollect(item.id,helper.layoutPosition-1)
}
}
}
} | 0 | Kotlin | 0 | 0 | 641dc8c22f4b537b12ab93c1c52d4f8701a0b945 | 3,281 | JetpackMvvm | Apache License 2.0 |
breathOfTheWild/src/main/kotlin/breathOfTheWild/roastedFood/RoastedFoodsRouter.kt | adamWeesner | 239,233,558 | false | null | package breathOfTheWild.roastedFood
import BaseRouter
import shared.zelda.RoastedFood
import shared.zelda.responses.RoastedFoodsResponse
import kotlin.reflect.full.createType
data class RoastedFoodsRouter(
override val basePath: String,
override val service: RoastedFoodsService
) : BaseRouter<RoastedFood, RoastedFoodsService>(
RoastedFoodsResponse(),
service,
RoastedFood::class.createType()
)
| 1 | Kotlin | 1 | 1 | a04ad390fe844a7d89db2fa726599c23d3f796f6 | 418 | weesnerDevelopment | MIT License |
Chapter 07/18_weight.kt | bpbpublications | 649,604,575 | false | {"Kotlin": 93212, "Java": 3484} | package com.example.chapter7
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
fun WeightExample2() {
Row {
ExtractedText("Item A")
ExtractedText("Item B")
ExtractedText("Item C")
}
}
@Composable
private fun RowScope.ExtractedText(text: String) {
Text(
modifier = Modifier.weight(0.3f),
text = text
)
} | 0 | Kotlin | 0 | 1 | d3a62fb563db2ecd138981b709abd3c3641509ee | 538 | A-Solutions-Guide-for-Android-Developers-in-Kotlin | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.