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/main/kotlin/no/skatteetaten/aurora/gradle/plugins/mutators/MiscellaneousTools.kt
Skatteetaten
87,403,632
false
null
package no.skatteetaten.aurora.gradle.plugins.mutators import com.github.benmanes.gradle.versions.updates.DependencyUpdatesTask import no.skatteetaten.aurora.gradle.plugins.model.AuroraReport import org.gradle.api.Project import org.gradle.kotlin.dsl.named class MiscellaneousTools(private val project: Project) { fun applyVersions(): AuroraReport { project.logger.lifecycle("Apply versions support") with(project) { with(tasks.named("dependencyUpdates", DependencyUpdatesTask::class).get()) { revision = "release" checkForGradleUpdate = true outputFormatter = "json" outputDir = "build/dependencyUpdates" reportfileName = "report" resolutionStrategy { strategy -> strategy.componentSelection { selection -> selection.all { all -> val rejectionPatterns = listOf("alpha", "beta", "pr", "rc", "cr", "m", "preview") val regex: (String) -> Regex = { Regex("(?i).*[.-]$it[.\\d-]*") } if (rejectionPatterns.any { all.candidate.version.matches(regex(it)) }) { all.reject("Release candidate") } } } } } } return AuroraReport( name = "plugin com.github.ben-manes.versions", description = "only allow stable versions in upgrade" ) } }
1
Kotlin
2
2
ec414d87869b825c10f16157549b560fcc92e26c
1,570
aurora-gradle-plugin
Apache License 2.0
v2-model/src/commonMain/kotlin/com/bselzer/gw2/v2/model/guild/member/GuildMember.kt
Woody230
388,820,096
false
{"Kotlin": 750899}
package com.bselzer.gw2.v2.model.guild.member import com.bselzer.gw2.v2.model.account.AccountName import com.bselzer.gw2.v2.model.guild.rank.GuildRankId import kotlinx.datetime.Instant import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class GuildMember( /** * The account name of the player. */ @SerialName("name") val name: AccountName = AccountName(), /** * The name of the rank. * @see <a href="https://wiki.guildwars2.com/wiki/API:2/guild/:id/ranks">the wiki</a> */ @SerialName("rank") val rank: GuildRankId = GuildRankId(), /** * The date and time the player joined the guild. */ @SerialName("joined") val joinedAt: Instant = Instant.DISTANT_PAST )
2
Kotlin
0
2
7bd43646f94d1e8de9c20dffcc2753707f6e455b
779
GW2Wrapper
Apache License 2.0
plugin-bsp/src/main/kotlin/org/jetbrains/plugins/bsp/android/run/BspAndroidConfigurationExecutor.kt
JetBrains
826,262,028
false
null
package org.jetbrains.plugins.bsp.android.run import com.android.ddmlib.IDevice import com.android.tools.idea.execution.common.AndroidConfigurationExecutor import com.android.tools.idea.execution.common.debug.DebugSessionStarter import com.android.tools.idea.execution.common.debug.impl.java.AndroidJavaDebugger import com.android.tools.idea.execution.common.processhandler.AndroidProcessHandler import com.android.tools.idea.projectsystem.ApplicationProjectContext import com.android.tools.idea.run.ShowLogcatListener import com.android.tools.idea.run.configuration.execution.createRunContentDescriptor import com.intellij.execution.ExecutionException import com.intellij.execution.configurations.RunConfiguration import com.intellij.execution.filters.TextConsoleBuilderFactory import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.ui.ConsoleView import com.intellij.execution.ui.RunContentDescriptor import com.intellij.openapi.components.service import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.runBlockingCancellable import com.intellij.xdebugger.impl.XDebugSessionImpl import org.jetbrains.plugins.bsp.magicmetamodel.impl.workspacemodel.getModule import org.jetbrains.plugins.bsp.run.config.BspRunConfiguration import org.jetbrains.plugins.bsp.target.TemporaryTargetUtils import com.android.tools.idea.project.getPackageName as getApplicationIdFromManifest public class BspAndroidConfigurationExecutor(private val environment: ExecutionEnvironment) : AndroidConfigurationExecutor { override val configuration: RunConfiguration get() = environment.runProfile as RunConfiguration override fun run(indicator: ProgressIndicator): RunContentDescriptor = runBlockingCancellable { val applicationId = getApplicationIdOrThrow() val processHandler = AndroidProcessHandler(applicationId, { it.forceStop(applicationId) }) val console = createConsole().apply { attachToProcess(processHandler) } val device = getDevice() processHandler.addTargetDevice(device) showLogcat(device, applicationId) createRunContentDescriptor(processHandler, console, environment) } override fun debug(indicator: ProgressIndicator): RunContentDescriptor = runBlockingCancellable { val device = getDevice() val applicationId = getApplicationIdOrThrow() val debugSession = startDebugSession(device, applicationId, environment, indicator) showLogcat(device, applicationId) debugSession.runContentDescriptor } private suspend fun startDebugSession( device: IDevice, applicationId: String, environment: ExecutionEnvironment, indicator: ProgressIndicator, ): XDebugSessionImpl { val debugger = AndroidJavaDebugger() val debuggerState = debugger.createState() return DebugSessionStarter.attachDebuggerToStartedProcess( device, object : ApplicationProjectContext { override val applicationId: String = applicationId }, environment, debugger, debuggerState, destroyRunningProcess = { d -> d.forceStop(applicationId) }, indicator, ) } private fun getDevice(): IDevice { val deviceFuture = environment.getCopyableUserData(DEVICE_FUTURE_KEY) ?: throw ExecutionException("No target device") return deviceFuture.get() } private fun getApplicationIdOrThrow(): String = getApplicationId() ?: throw ExecutionException("Couldn't get application ID") private fun getApplicationId(): String? { val bspRunConfiguration = environment.runProfile as? BspRunConfiguration ?: return null val target = bspRunConfiguration.targets.singleOrNull() ?: return null val targetInfo = environment.project.service<TemporaryTargetUtils>().getBuildTargetInfoForId(target) val module = targetInfo?.getModule(environment.project) ?: return null return getApplicationIdFromManifest(module) } private fun createConsole(): ConsoleView = TextConsoleBuilderFactory.getInstance().createBuilder(environment.project).console private fun showLogcat(device: IDevice, applicationId: String) { environment.project.messageBus .syncPublisher(ShowLogcatListener.TOPIC) .showLogcat(device, applicationId) } // The "Apply changes" button isn't available for BspRunConfiguration, so this is an unexpected code path override fun applyChanges(indicator: ProgressIndicator): RunContentDescriptor = throw ExecutionException("Apply changes not supported") override fun applyCodeChanges(indicator: ProgressIndicator): RunContentDescriptor = throw ExecutionException("Apply code changes not supported") }
2
null
18
45
1d79484cfdf8fc31d3a4b214655e857214071723
4,712
hirschgarten
Apache License 2.0
composeApp/src/commonMain/kotlin/com/jetbrains/dependoapp/presentation/screens/components/HomeBottomContent.kt
loke101
763,358,687
false
{"Kotlin": 234797, "Swift": 661}
package com.jetbrains.dependoapp.presentation.screens.components import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Card import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.KeyboardArrowRight import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.icerockdev.library.MR import dev.icerock.moko.resources.compose.colorResource @Composable fun HomeBottomContent( cashTobeCollectedAmount:String?, todayCashDueAmount:String?, oldCashDueAmount:String?, oldCashDepositCount:String?, totalCashDueAmount:String? ) { Column( verticalArrangement = Arrangement.spacedBy(5.dp), horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxWidth() .padding(horizontal = 10.dp) ) { Row( horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .horizontalScroll( rememberScrollState() ) ) { DashCashScreen( amount = "₹ ${cashTobeCollectedAmount?:"0.0"}", heading = "Cash to be collected", amountColor = Color.White ) DashCashScreen( amount = "₹ ${todayCashDueAmount?:"0.0"}", heading = "Today's cash due for deposit", amountColor = Color.White ) DashCashScreen( amount = "₹ ${oldCashDueAmount?:"0.0"}", heading = "Old cash due for deposit(${oldCashDepositCount?:"0.0"})", amountColor = Color.White ) } AmountContent( amountText = "Total cash due for deposit", amountColor = Color.White, onClick = {}, amountHeading = "₹ ${totalCashDueAmount?:"0.0"}", ) } } @Composable fun AmountContent( amountHeading: String? = "", amountText: String? = "", amountColor: Color?, onClick: (() -> Unit)? = null, ) { Card( shape = RoundedCornerShape(10.dp), elevation = 3.dp, backgroundColor = colorResource(MR.colors.backColor), contentColor = Color.White, modifier = Modifier .padding(start = 1.dp, end = 1.dp) .fillMaxWidth() .clickable { onClick?.invoke() }, ) { Row( Modifier .padding(15.dp) .fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text( text = amountText.toString(), modifier = Modifier.padding(start = 3.dp), color = colorResource(MR.colors.cardViewBack), textDecoration = TextDecoration.Underline, fontSize = 13.sp, fontWeight = FontWeight.W400, overflow = TextOverflow.Ellipsis, fontFamily = FontFamily.SansSerif ) Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp) ) { if (amountColor != null) { Text( text = amountHeading.toString(), fontSize = 13.sp, fontWeight = FontWeight.W400, color = amountColor, fontFamily = FontFamily.SansSerif ) } Icon( imageVector = Icons.Default.KeyboardArrowRight, contentDescription = "Arrow Icon", tint = Color.White, modifier = Modifier.size(13.dp) ) } } } } @Composable fun DashCashScreen( amount: String, heading: String, amountColor: Color, ) { Card(modifier = Modifier.size(width = 105.dp, height = 70.dp), elevation = 10.dp, contentColor = Color.White, shape = RoundedCornerShape(10.dp), backgroundColor = MaterialTheme.colors.primary) { Column(verticalArrangement = Arrangement.spacedBy(3.dp), horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(vertical = 4.dp, horizontal = 4.dp)) { Text(text = "Rs $amount", modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, fontFamily = FontFamily.SansSerif, style = MaterialTheme.typography.caption) Text(text = heading,Modifier.fillMaxWidth(), textAlign = TextAlign.Center, fontFamily = FontFamily.SansSerif, style = MaterialTheme.typography.caption ) } } } fun addLineBreaks(text: String, wordsPerLine: Int): String { val words = text.split(Regex("\\s+")) val modifiedWords = words.chunked(wordsPerLine) { it.joinToString(" ") } return modifiedWords.joinToString("\n") }
0
Kotlin
0
0
edcd07d4846375a79173b3aff090e7a7828029fe
6,454
KMPDEPENDO_01
Apache License 2.0
webrtc-kmp/src/iosMain/kotlin/com/shepeliev/webrtckmp/internal/IceServer.kt
shepeliev
329,550,581
false
{"Kotlin": 233515}
@file:OptIn(ExperimentalForeignApi::class) package com.shepeliev.webrtckmp.internal import WebRTC.RTCIceServer import WebRTC.RTCTlsCertPolicy import com.shepeliev.webrtckmp.IceServer import com.shepeliev.webrtckmp.TlsCertPolicy import kotlinx.cinterop.ExperimentalForeignApi internal fun IceServer.toPlatform(): RTCIceServer { return RTCIceServer( uRLStrings = urls, username = username, credential = password, tlsCertPolicy = tlsCertPolicy.toPlatform(), hostname = hostname, tlsAlpnProtocols = tlsAlpnProtocols, tlsEllipticCurves = tlsEllipticCurves ) } private fun TlsCertPolicy.toPlatform(): RTCTlsCertPolicy { return when (this) { TlsCertPolicy.TlsCertPolicySecure -> RTCTlsCertPolicy.RTCTlsCertPolicySecure TlsCertPolicy.TlsCertPolicyInsecureNoCheck -> { RTCTlsCertPolicy.RTCTlsCertPolicyInsecureNoCheck } } }
13
Kotlin
38
181
73e482e70dc7192601acd3482a6774c017c072de
928
webrtc-kmp
Apache License 2.0
kusb/src/commonMain/kotlin/dev/lucianosantos/kusb/api/Kusb.kt
lucianosantosdev
758,214,057
false
{"Kotlin": 830}
package dev.lucianosantos.kusb.api class Kusb { private val platform: Platform = getPlatform() fun greet(): String { return "Hello, ${platform.name}!" } }
0
Kotlin
0
0
cc1e0e9a4926b1d6542095a9d4180422fc659190
176
kusb
MIT License
src/main/java/calebxzhou/craftcone/net/protocol/BufferReadable.kt
calebxzhou
655,742,846
false
null
package calebxzhou.craftcone.net.protocol import net.minecraft.network.FriendlyByteBuf /** * Created on 2023-07-13,17:27. */ //通用数据包 interface BufferReadable<T : Packet> { // 读取 数据 fun read(buf: FriendlyByteBuf): T }
0
Kotlin
0
0
24164295c2a96cf81614537d258b8f4b052cba89
231
craftcone-client
Creative Commons Zero v1.0 Universal
app/src/main/java/uk/co/victoriajanedavis/chatapp/presentation/ui/friendrequests/sent/SentFriendRequestsViewModel.kt
sbearben
158,967,910
false
null
package uk.co.victoriajanedavis.chatapp.presentation.ui.friendrequests.sent import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import uk.co.victoriajanedavis.chatapp.domain.entities.FriendshipEntity import uk.co.victoriajanedavis.chatapp.domain.interactors.CancelSentFriendRequest import uk.co.victoriajanedavis.chatapp.domain.interactors.GetSentFriendRequestsList import uk.co.victoriajanedavis.chatapp.domain.interactors.RefreshSentFriendRequests import uk.co.victoriajanedavis.chatapp.presentation.common.ListState import uk.co.victoriajanedavis.chatapp.presentation.common.ListState.* import uk.co.victoriajanedavis.chatapp.domain.common.StreamState.* import java.util.UUID import javax.inject.Inject class SentFriendRequestsViewModel @Inject constructor( private val getSentFriendRequests: GetSentFriendRequestsList, private val refreshSentFriendRequests: RefreshSentFriendRequests, private val cancelFriendRequest: CancelSentFriendRequest ) : ViewModel() { private val friendLiveData = MutableLiveData<ListState<List<FriendshipEntity>>>() private val compositeDisposable = CompositeDisposable() private var refreshDisposable: Disposable? = null init { friendLiveData.value = ShowLoading compositeDisposable.add(bindToUseCase()) } override fun onCleared() { compositeDisposable.dispose() } fun getSentFriendRequestsLiveData(): LiveData<ListState<List<FriendshipEntity>>> = friendLiveData fun refreshItems() { refreshDisposable?.dispose() refreshDisposable = refreshSentFriendRequests.getRefreshSingle(null) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({friendLiveData.value = StopLoading}, { e -> onError(e) }) compositeDisposable.add(refreshDisposable!!) } fun cancelFriendRequest(receiverUserUuid: UUID) { compositeDisposable.add(bindToCancelFriendRequest(receiverUserUuid)) } private fun bindToUseCase() : Disposable { return getSentFriendRequests.getBehaviorStream(null) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe{ streamState -> when (streamState) { is OnNext -> onNext(streamState.content) is OnError -> onError(streamState.throwable) } } } private fun onNext(friendEntities: List<FriendshipEntity>) { if (!friendEntities.isEmpty()) friendLiveData.value = ShowContent(friendEntities) else friendLiveData.value = ShowEmpty } private fun onError(e: Throwable) { friendLiveData.value = ShowError(e.message ?: e.toString()) } private fun bindToCancelFriendRequest(receiverUserUuid: UUID) : Disposable { return cancelFriendRequest.getActionCompletable(receiverUserUuid) .subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({}, { e -> onError(e) }) } }
0
Kotlin
10
16
e6d7890effc84b1b5c47870c33a0b3d11edffe4b
3,360
ChatApp
Apache License 2.0
libraries/remote/src/main/java/com/example/eziketobenna/bakingapp/remote/ApiServiceFactory.kt
Ezike
270,478,922
false
null
package com.example.eziketobenna.bakingapp.remote import com.squareup.moshi.Moshi import java.util.concurrent.TimeUnit import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory object ApiServiceFactory { private const val BASE_URL: String = "https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/" fun makeAPiService(isDebug: Boolean, moshi: Moshi): ApiService { val okHttpClient: OkHttpClient = makeOkHttpClient( makeLoggingInterceptor((isDebug)) ) return makeAPiService(okHttpClient, moshi) } private fun makeAPiService(okHttpClient: OkHttpClient, moshi: Moshi): ApiService { val retrofit: Retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .client(okHttpClient) .addConverterFactory(MoshiConverterFactory.create(moshi)) .build() return retrofit.create(ApiService::class.java) } private fun makeOkHttpClient(httpLoggingInterceptor: HttpLoggingInterceptor): OkHttpClient { return OkHttpClient.Builder() .addInterceptor(httpLoggingInterceptor) .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build() } private fun makeLoggingInterceptor(isDebug: Boolean): HttpLoggingInterceptor { val logging = HttpLoggingInterceptor() logging.level = if (isDebug) { HttpLoggingInterceptor.Level.BODY } else { HttpLoggingInterceptor.Level.NONE } return logging } }
4
Kotlin
79
432
ba1ee513d08f9d02141f914e3e58abde1abe4c14
1,685
Baking-App-Kotlin
Apache License 2.0
api/src/main/kotlin/com/seedcompany/cordtables/components/tables/sil/table_of_languages/Read.kt
CordField
409,237,733
false
null
package com.seedcompany.cordtables.components.tables.sil.table_of_languages import com.seedcompany.cordtables.common.ErrorType import com.seedcompany.cordtables.common.Utility import com.seedcompany.cordtables.components.admin.GetSecureListQuery import com.seedcompany.cordtables.components.admin.GetSecureListQueryRequest import org.springframework.beans.factory.annotation.Autowired import org.springframework.jdbc.core.namedparam.MapSqlParameterSource import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.CrossOrigin import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.ResponseBody import java.sql.SQLException import javax.sql.DataSource data class SilTableOfLanguagesReadRequest( val token: String?, val id: String? = null, ) data class SilTableOfLanguagesReadResponse( val error: ErrorType, val tableOfLanguage: tableOfLanguage? = null, ) @CrossOrigin(origins = ["http://localhost:3333", "https://dev.cordtables.com", "https://cordtables.com"]) @Controller("SilTableOfLanguagesRead") class Read( @Autowired val util: Utility, @Autowired val ds: DataSource, @Autowired val secureList: GetSecureListQuery, ) { var jdbcTemplate: NamedParameterJdbcTemplate = NamedParameterJdbcTemplate(ds) @PostMapping("sil/table-of-languages/read") @ResponseBody fun readHandler(@RequestBody req: SilTableOfLanguagesReadRequest): SilTableOfLanguagesReadResponse { if (req.token == null) return SilTableOfLanguagesReadResponse(ErrorType.TokenNotFound) if (req.id == null) return SilTableOfLanguagesReadResponse(ErrorType.MissingId) val paramSource = MapSqlParameterSource() paramSource.addValue("token", req.token) paramSource.addValue("id", req.id) val query = secureList.getSecureListQueryHandler( GetSecureListQueryRequest( tableName = "sil.table_of_languages", getList = false, columns = arrayOf( "id", "iso_639", "language_name", "uninverted_name", "country_code", "country_name", "region_code", "region_name", "area", "l1_users", "digits", "all_users", "countries", "family", "classification", "latitude", "longitude", "egids", "is_written", "created_at", "created_by", "modified_at", "modified_by", "owning_person", "owning_group", ), ) ).query try { val jdbcResult = jdbcTemplate.queryForRowSet(query, paramSource) while (jdbcResult.next()) { var id: String? = jdbcResult.getString("id") if (jdbcResult.wasNull()) id = null var iso_639: String? = jdbcResult.getString("iso_639") if (jdbcResult.wasNull()) iso_639 = null var language_name: String? = jdbcResult.getString("language_name") if (jdbcResult.wasNull()) language_name = null var uninverted_name: String? = jdbcResult.getString("uninverted_name") if (jdbcResult.wasNull()) uninverted_name = null var country_code: String? = jdbcResult.getString("country_code") if (jdbcResult.wasNull()) country_code = null var country_name: String? = jdbcResult.getString("country_name") if (jdbcResult.wasNull()) country_name = null var region_code: String? = jdbcResult.getString("region_code") if (jdbcResult.wasNull()) region_code = null var region_name: String? = jdbcResult.getString("region_name") if (jdbcResult.wasNull()) region_name = null var area: String? = jdbcResult.getString("area") if (jdbcResult.wasNull()) area = null var l1_users: Int? = jdbcResult.getInt("l1_users") if (jdbcResult.wasNull()) l1_users = null var digits: Int? = jdbcResult.getInt("digits") if (jdbcResult.wasNull()) digits = null var all_users: Int? = jdbcResult.getInt("all_users") if (jdbcResult.wasNull()) all_users = null var countries: Int? = jdbcResult.getInt("countries") if (jdbcResult.wasNull()) countries = null var family: String? = jdbcResult.getString("family") if (jdbcResult.wasNull()) family = null var classification: String? = jdbcResult.getString("classification") if (jdbcResult.wasNull()) classification = null var latitude: Double? = jdbcResult.getDouble("latitude") if (jdbcResult.wasNull()) latitude = null var longitude: Double? = jdbcResult.getDouble("longitude") if (jdbcResult.wasNull()) longitude = null var egids: String? = jdbcResult.getString("egids") if (jdbcResult.wasNull()) egids = null var is_written: String? = jdbcResult.getString("is_written") if (jdbcResult.wasNull()) is_written = null var created_at: String? = jdbcResult.getString("created_at") if (jdbcResult.wasNull()) created_at = null var created_by: String? = jdbcResult.getString("created_by") if (jdbcResult.wasNull()) created_by = null var modified_at: String? = jdbcResult.getString("modified_at") if (jdbcResult.wasNull()) modified_at = null var modified_by: String? = jdbcResult.getString("modified_by") if (jdbcResult.wasNull()) modified_by = null var owning_person: String? = jdbcResult.getString("owning_person") if (jdbcResult.wasNull()) owning_person = null var owning_group: String? = jdbcResult.getString("owning_group") if (jdbcResult.wasNull()) owning_group = null val tableOfLanguage = tableOfLanguage( id = id, iso_639 = iso_639, language_name = language_name, uninverted_name = uninverted_name, country_code = country_code, country_name = country_name, region_code = region_code, region_name = region_name, area = area, l1_users = l1_users, digits = digits, all_users = all_users, countries = countries, family = family, classification = classification, latitude = latitude, longitude = longitude, egids = egids, is_written = is_written, created_at = created_at, created_by = created_by, modified_at = modified_at, modified_by = modified_by, owning_person = owning_person, owning_group = owning_group, ) return SilTableOfLanguagesReadResponse(ErrorType.NoError, tableOfLanguage = tableOfLanguage) } } catch (e: SQLException) { println("error while listing ${e.message}") return SilTableOfLanguagesReadResponse(ErrorType.SQLReadError) } return SilTableOfLanguagesReadResponse(error = ErrorType.UnknownError) } }
93
Kotlin
1
3
7e5588a8b3274917f9a5df2ffa12d27db23fb909
8,290
cordtables
MIT License
src/main/kotlin/com/xinaiz/wds/core/element/modules/ByteToBufferedImageHelper.kt
domazey
155,060,100
false
null
package com.xinaiz.wds.core.element.modules import java.awt.image.BufferedImage import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import javax.imageio.ImageIO object BytesHelper { fun toBytes(bufferedImage: BufferedImage): ByteArray { val baos = ByteArrayOutputStream() ImageIO.write(bufferedImage, "jpg", baos) return baos.toByteArray() } fun toBufferedImage(bytes: ByteArray): BufferedImage { val bis = ByteArrayInputStream(bytes) ImageIO.setUseCache(false) val bufferedImage = ImageIO.read(bis) bis.close() return bufferedImage } }
0
Kotlin
0
0
55012e722cb4e56785ca25e5477e0d7c2a5260cc
642
web-driver-support
Apache License 2.0
tests/src/base enum.kt
mmarlewski
611,681,057
false
{"Kotlin": 1093910, "Shell": 814}
import com.efm.room.Base import org.junit.Assert.* import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(HeadlessTestRunner::class) class `base enum` { @Before fun `set up`() { } @Test fun `test companion functions`() { println(Base.grass.ordinal) println(Base.getOrdinal(Base.grass)) println(Base.getBase(3)) } }
1
Kotlin
0
3
b05515da1aecfae7b9f47036ed089dafe1fc95d2
406
escape-from-morasko
MIT License
tests/src/base enum.kt
mmarlewski
611,681,057
false
{"Kotlin": 1093910, "Shell": 814}
import com.efm.room.Base import org.junit.Assert.* import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(HeadlessTestRunner::class) class `base enum` { @Before fun `set up`() { } @Test fun `test companion functions`() { println(Base.grass.ordinal) println(Base.getOrdinal(Base.grass)) println(Base.getBase(3)) } }
1
Kotlin
0
3
b05515da1aecfae7b9f47036ed089dafe1fc95d2
406
escape-from-morasko
MIT License
src/main/kotlin/com/dwolla/shared/USState.kt
Dwolla
189,449,029
false
null
package com.dwolla.shared import com.google.gson.annotations.SerializedName enum class USState( @JvmField val value: String, @JvmField val displayName: String ) { @SerializedName("AL") AL("AL", "Alabama"), @SerializedName("AK") AK("AK", "Alaska"), @SerializedName("AS") AS("AS", "American Samoa"), @SerializedName("AZ") AZ("AZ", "Arizona"), @SerializedName("AR") AR("AR", "Arkansas"), @SerializedName("CA") CA("CA", "California"), @SerializedName("CO") CO("CO", "Colorado"), @SerializedName("CT") CT("CT", "Connecticut"), @SerializedName("DC") DC("DC", "District of Columbia"), @SerializedName("DE") DE("DE", "Delaware"), @SerializedName("FL") FL("FL", "Florida"), @SerializedName("GA") GA("GA", "Georgia"), @SerializedName("GU") GU("GU", "Guam"), @SerializedName("HI") HI("HI", "Hawaii"), @SerializedName("ID") ID("ID", "Idaho"), @SerializedName("IL") IL("IL", "Illinois"), @SerializedName("IN") IN("IN", "Indiana"), @SerializedName("IA") IA("IA", "Iowa"), @SerializedName("KS") KS("KS", "Kansas"), @SerializedName("KY") KY("KY", "Kentucky"), @SerializedName("LA") LA("LA", "Louisiana"), @SerializedName("ME") ME("ME", "Maine"), @SerializedName("MD") MD("MD", "Maryland"), @SerializedName("MA") MA("MA", "Massachusetts"), @SerializedName("MI") MI("MI", "Michigan"), @SerializedName("MN") MN("MN", "Minnesota"), @SerializedName("MS") MS("MS", "Mississippi"), @SerializedName("MO") MO("MO", "Missouri"), @SerializedName("MT") MT("MT", "Montana"), @SerializedName("NE") NE("NE", "Nebraska"), @SerializedName("NV") NV("NV", "Nevada"), @SerializedName("NH") NH("NH", "New Hampshire"), @SerializedName("NJ") NJ("NJ", "New Jersey"), @SerializedName("NM") NM("NM", "New Mexico"), @SerializedName("NY") NY("NY", "New York"), @SerializedName("NC") NC("NC", "North Carolina"), @SerializedName("ND") ND("ND", "North Dakota"), @SerializedName("MP") MP("MP", "Northern Mariana Islands"), @SerializedName("OH") OH("OH", "Ohio"), @SerializedName("OK") OK("OK", "Oklahoma"), @SerializedName("OR") OR("OR", "Oregon"), @SerializedName("PA") PA("PA", "Pennsylvania"), @SerializedName("PR") PR("PR", "Puerto Rico"), @SerializedName("RI") RI("RI", "Rhode Island"), @SerializedName("SC") SC("SC", "South Carolina"), @SerializedName("SD") SD("SD", "South Dakota"), @SerializedName("TN") TN("TN", "Tennessee"), @SerializedName("TX") TX("TX", "Texas"), @SerializedName("UM") UM("UM", "U.S. Minor Outlying Islands"), @SerializedName("UT") UT("UT", "Utah"), @SerializedName("VT") VT("VT", "Vermont"), @SerializedName("VI") VI("VI", "Virgin Islands"), @SerializedName("VA") VA("VA", "Virginia"), @SerializedName("WA") WA("WA", "Washington"), @SerializedName("WV") WV("WV", "West Virginia"), @SerializedName("WI") WI("WI", "Wisconsin"), @SerializedName("WY") WY("WY", "Wyoming") }
7
Kotlin
5
9
013d9d5cbf963c85224c0fd9c68f84044046ed17
3,275
dwolla-v2-kotlin
MIT License
misk-hibernate/src/main/kotlin/misk/hibernate/Transacter.kt
cashapp
113,107,217
false
{"Kotlin": 3843790, "TypeScript": 232251, "Java": 83564, "JavaScript": 5073, "Shell": 3462, "HTML": 1536, "CSS": 58}
package misk.hibernate import com.google.common.annotations.VisibleForTesting import misk.jdbc.DataSourceConfig import misk.vitess.Keyspace import misk.vitess.Shard import misk.vitess.tabletDoesNotExists import javax.persistence.PersistenceException import kotlin.reflect.KClass /** * Provides explicit block-based transaction demarcation. */ interface Transacter { /** * Returns true if the calling thread is currently within a transaction block. */ val inTransaction: Boolean /** * Is the scalability check currently enabled. Use [Session.withoutChecks] to disable checks. */ fun isCheckEnabled(check: Check): Boolean /** * Starts a transaction on the current thread, executes [block], and commits the transaction. * If the block raises an exception the transaction will be rolled back instead of committed. * * If retries are permitted (the default), a failed but recoverable transaction will be * reattempted after rolling back. * * It is an error to start a transaction if another transaction is already in progress. */ fun <T> transaction(block: (session: Session) -> T): T /** * Runs a non-transactional session against a read replica. * * A few things that are different with replica reads: * * Replica reads are (obviously?) read only. * * Consistency is eventual. If your application thread just wrote something in a transaction * you may not see that write with a replica read as the write may not have replicated * to the replica yet. * * There may be time jumping. As each query may end up at a separate replica that will likely * be at a separate point in the replica stream. That means each query can jump back or forward * in "time". (There is some support for internally consistent replica reads that peg a single * replica in Vitess but we're not using that. If you need that functionality reach out to * #vitess) * * Full scatters are allowed since you can increase the availability of these by adding more * replicas. * * If no reader is configured for replica reads when installing the [HibernateModule], this * method will throw an [IllegalStateException]. * * Note: You can do it another way, where you annotate the [Transacter] with the readerQualifer * defined by [HibernateModule], which will use the read only replica as the datasource. * */ fun <T> replicaRead(block: (session: Session) -> T): T fun retries(maxAttempts: Int = 2): Transacter fun noRetries(): Transacter /** * Creates a new transacter that produces read only sessions. This does not mean the underlying * datasource is read only, only that the session produced won't modify the database. */ fun readOnly(): Transacter /** * Disable cowrite checks for the duration of the session. Useful for quickly setting up test * data in testing. */ // TODO(jontirsen): Figure out a way to make this only available for test code @VisibleForTesting fun allowCowrites(): Transacter fun config(): DataSourceConfig /** Returns KClasses for the bound DbEntities for the transacter */ fun entities(): Set<KClass<out DbEntity<*>>> } fun Transacter.shards() = transaction { it.shards() } fun Transacter.shards(keyspace: Keyspace) = transaction { it.shards(keyspace) } /** * Commits a transaction with operations of [block]. * * New objects must be persisted with an explicit call to [Session.save]. * Updates are performed implicitly by modifying objects returned from a query. * * For example if we were to save a new movie to a movie database, and update the revenue of an * existing movie: * ``` * transacter.transaction { session -> * // Saving a new entity to the database needs an explicit call. * val starWars = DbMovie(name = "Star Wars", year = "1977", revenue = 775_400_000) * session.save(starWars) * * // Updating a movie from the database is done by modifying the object. * // Changes are saved implicitly. * val movie: DbMovie = queryFactory.newQuery<MovieQuery>().id(id).uniqueResult(session)!! * movie.revenue = 100_000_000 * } * */ fun <T> Transacter.transaction(shard: Shard, block: (session: Session) -> T): T = transaction { it.target(shard) { block(it) } } /** * Runs a read on master first then tries it on replicas on failure. This method is here only for * health check purpose for standby regions. */ fun <T> Transacter.failSafeRead(block: (session: Session) -> T): T = try { transaction { block(it) } } catch (e: PersistenceException) { if (tabletDoesNotExists(e)) { replicaRead { block(it) } } else { throw e } } fun <T> Transacter.failSafeRead(shard: Shard, block: (session: Session) -> T): T = failSafeRead { it.target(shard) { block(it) } } /** * Thrown to explicitly trigger a retry, subject to retry limits and config such as noRetries(). */ class RetryTransactionException @JvmOverloads constructor( message: String? = null, cause: Throwable? = null ) : Exception(message, cause)
169
Kotlin
169
400
13dcba0c4e69cc2856021270c99857e7e91af27d
5,080
misk
Apache License 2.0
src/main/kotlin/com/example/realworld/dto/PingResponse.kt
brunohenriquepj
367,784,702
false
null
package com.example.realworld.dto data class PingResponse(val ping: PingResponseData) { companion object { fun of(message: String): PingResponse { val responseData = PingResponseData(message) return PingResponse(responseData) } } } data class PingResponseData(val message: String)
7
Kotlin
0
2
a3da13258606924f185b249545955e142f783b92
331
spring-boot-kotlin-realworld
MIT License
app/src/main/java/com/example/take_my_money/presentation/view/SplashActivity.kt
ozielguimaraes
494,566,896
false
{"Kotlin": 47595}
package com.example.take_my_money.presentation.view import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.os.Handler import android.os.Looper import androidx.appcompat.app.AppCompatActivity import androidx.core.os.postDelayed import com.example.take_my_money.databinding.ActivitySplashBinding @SuppressLint("CustomSplashScreen") class SplashActivity : AppCompatActivity() { private lateinit var binding: ActivitySplashBinding @SuppressLint override fun onCreate(savedInstanceState: Bundle?) { binding = ActivitySplashBinding.inflate(layoutInflater) super.onCreate(savedInstanceState) setContentView(binding.root) splashScreen() } private fun splashScreen() { Handler(Looper.getMainLooper()).postDelayed(3000, 3000) { val intent = Intent(this, CoinListActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK startActivity(intent) } } }
2
Kotlin
2
1
a09df3749ac565e30721a3c80b8000c90afd701c
1,050
take-my-money
MIT License
app/src/main/java/com/alexsci/android/lambdarunner/ui/run_lambda/RunLambdaActivity.kt
ralexander-phi
218,896,059
false
null
package com.alexsci.android.lambdarunner.ui.run_lambda import android.app.Activity import android.content.Intent import android.os.AsyncTask import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import arrow.core.Either import com.alexsci.android.lambdarunner.* import com.alexsci.android.lambdarunner.aws.lambda.InvokeFunctionRequest import com.alexsci.android.lambdarunner.aws.lambda.InvokeFunctionResult import com.alexsci.android.lambdarunner.aws.lambda.LambdaClient import com.alexsci.android.lambdarunner.aws.lambda.LambdaClientBuilder import com.alexsci.android.lambdarunner.ui.common.ToolbarHelper import com.alexsci.android.lambdarunner.ui.edit_json.EditJsonActivity import com.alexsci.android.lambdarunner.ui.list_functions.ListFunctionsActivity import com.alexsci.android.lambdarunner.ui.list_keys.ListKeysActivity import com.alexsci.android.lambdarunner.ui.scan_qr.ScanQRActivity import com.alexsci.android.lambdarunner.ui.view_results.ViewResultsActivity import com.alexsci.android.lambdarunner.util.preferences.PreferencesUtil import com.amazonaws.AmazonClientException import com.google.gson.GsonBuilder import com.google.gson.JsonElement import com.google.gson.JsonParser import com.google.gson.JsonSyntaxException class RunLambdaActivity: AppCompatActivity() { companion object { const val SAVED_STATE_JSON = "json" } private lateinit var preferencesUtil: PreferencesUtil private lateinit var jsonEditText: EditText private lateinit var editButton: Button private lateinit var qrButton: Button private lateinit var errorMessage: TextView private var lastKnownText: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_run_lambda) setSupportActionBar(findViewById(R.id.toolbar)) supportActionBar?.setDisplayHomeAsUpEnabled(true) preferencesUtil = PreferencesUtil(this) val accessKeyId = preferencesUtil.get(SHARED_PREFERENCE_ACCESS_KEY_ID) val region = preferencesUtil.get(SHARED_PREFERENCE_REGION) val functionName = preferencesUtil.get(SHARED_PREFERENCE_FUNCTION_NAME) errorMessage = findViewById<TextView>(R.id.error_message).also { // Start hidden it.visibility = View.GONE } jsonEditText = findViewById<EditText>(R.id.json_edittext).also { it.addTextChangedListener(object: TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} override fun afterTextChanged(s: Editable?) { if (s != null) { try { val text = s.toString() lastKnownText = text val root = JsonParser().parse(text) onJsonValidationResult(Either.right(root)) } catch (e: JsonSyntaxException) { onJsonValidationResult(Either.left(e)) } } } }) } if (accessKeyId == null) { startActivity(Intent(this, ListKeysActivity::class.java)) } else if (region == null || functionName == null) { startActivity(Intent(this, ListFunctionsActivity::class.java)) } else { supportActionBar?.title = functionName editButton = findViewById<Button>(R.id.edit_json).also { it.setOnClickListener { val intent = Intent(this, EditJsonActivity::class.java) intent.putExtra(EditJsonActivity.JSON_EXTRA, jsonEditText.text.toString()) startActivityForResult(intent, RequestCodes.REQUEST_CODE_EDIT_JSON.code) } } qrButton = findViewById<Button>(R.id.scan_qr).also { it.setOnClickListener { val intent = Intent(this, ScanQRActivity::class.java) intent.putExtra( ScanQRActivity.SCAN_REQUIREMENTS_EXTRA, ScanQRActivity.ScanRequirements.IS_JSON.name ) startActivityForResult(intent, RequestCodes.REQUEST_CODE_SCAN_QR.code) } } findViewById<Button>(R.id.invoke)?.setOnClickListener { val jsonText = jsonEditText.text.toString() preferencesUtil.set(SHARED_PREFERENCE_LAST_USED_JSON, jsonText) val request = InvokeFunctionRequest(functionName, jsonText) val client = LambdaClientBuilder(accessKeyId, region).getClient(this@RunLambdaActivity) InvokeTask(client, request).execute() } } } private fun onJsonValidationResult(e: Either<JsonSyntaxException, JsonElement>) { when (e) { is Either.Left -> { // JSON is not valid editButton.isEnabled = false errorMessage.text = e.a.toString() errorMessage.visibility = View.VISIBLE } is Either.Right -> { if (e.b.isJsonObject || e.b.isJsonArray) { editButton.isEnabled = true errorMessage.visibility = View.GONE } else { editButton.isEnabled = false errorMessage.text = "Edit disabled, only able to edit arrays and objects" errorMessage.visibility = View.VISIBLE } } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == RequestCodes.REQUEST_CODE_EDIT_JSON.code && resultCode == Activity.RESULT_OK) { if (data != null && data.hasExtra(EditJsonActivity.JSON_EXTRA)) { val jsonText = data.getStringExtra(EditJsonActivity.JSON_EXTRA)!! setJsonText(jsonText) } } if (requestCode == RequestCodes.REQUEST_CODE_SCAN_QR.code && resultCode == Activity.RESULT_OK) { if (data != null && data.hasExtra(ScanQRActivity.DETECTED_JSON_EXTRA)) { val jsonText = data.getStringExtra(ScanQRActivity.DETECTED_JSON_EXTRA)!! setJsonText(jsonText) } } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(SAVED_STATE_JSON, lastKnownText) } override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) lastKnownText = savedInstanceState.getString(SAVED_STATE_JSON) } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) if (lastKnownText == null) { lastKnownText = preferencesUtil.get(SHARED_PREFERENCE_LAST_USED_JSON, EMPTY_JSON_OBJECT_TEXT) } setJsonText(lastKnownText!!) } override fun onOptionsItemSelected(item: MenuItem): Boolean { val toolbarResult = ToolbarHelper().onOptionsItemSelected(this, item) if (toolbarResult != null) { return toolbarResult } else { when (item.itemId) { android.R.id.home -> { startActivity(Intent(this, ListFunctionsActivity::class.java)) return true } else -> return super.onOptionsItemSelected(item) } } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.main_menu, menu) return true } private fun setJsonText(uglyJson: String) { var text: String try { val gson = GsonBuilder().setPrettyPrinting().serializeNulls().create() val root = JsonParser().parse(uglyJson) val prettyJson = gson.toJson(root) text = prettyJson } catch (e: JsonSyntaxException) { // It's not JSON, just show it as-is text = uglyJson } jsonEditText.setText(text) } private inner class InvokeTask( val client: LambdaClient, val request: InvokeFunctionRequest ): AsyncTask<Void, Void, Either<AmazonClientException, InvokeFunctionResult>>() { override fun doInBackground(vararg params: Void?): Either<AmazonClientException, InvokeFunctionResult> { return client.invoke(request) } override fun onPostExecute(result: Either<AmazonClientException, InvokeFunctionResult>?) { super.onPostExecute(result) when (result) { is Either.Left -> Toast.makeText(this@RunLambdaActivity, result.a.toString(), Toast.LENGTH_LONG).show() is Either.Right -> { val intent = Intent(this@RunLambdaActivity, ViewResultsActivity::class.java) intent.putExtra(ViewResultsActivity.RESULT_JSON, result.b.payload) startActivity(intent) } } } } }
4
Kotlin
0
3
d74c85c7873668dda49305985c24ed7de926ed7a
9,672
android-aws-lambda-runner
MIT License
src/main/kotlin/nl/joerihofman/gettingtowikipedia/Main.kt
joerihofman
354,338,522
false
null
package nl.joerihofman.gettingtowikipedia import io.ktor.client.* import io.ktor.client.engine.apache.* import io.ktor.client.features.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import kotlinx.coroutines.runBlocking import kotlin.system.exitProcess const val wikipediaUrl = "https://en.wikipedia.org" val client = HttpClient(Apache) val wikiPageUrlRegex: Regex = Regex("href=\"/wiki/[^Help:][^File:](?!#)[^\"]*") // Should not contain italic text or in-page references fun main() { search("/wiki/Wikipedia:Getting_to_Philosophy") client.close() } private fun search(endpoint: String) { val requestBody = doRequest(endpoint) val title = findTitle(requestBody) if (title != "Philosophy") { val firstFoundLink = findFirstLink(requestBody) search(firstFoundLink) } } private fun doRequest(endpoint: String): String { val completeUrl = wikipediaUrl + endpoint println("Request to $completeUrl") return runBlocking { val response: HttpResponse try { response = client.request(completeUrl) } catch (e: ClientRequestException) { println("Something went wrong! Request to [$completeUrl] failed.") throw e } return@runBlocking response.readText() } } private fun findTitle(body: String): String { var title = body.substringAfter("<title>") title = title.substringBefore("</title>") title = title.substringBefore(" - Wikipedia") // This is always in the title return title.also { println("Title: [$it]") } } private fun findFirstLink(body: String) : String { val possibleLinks = mutableListOf<String>() if (body.contains("id=\"bodyContent\"")) { wikiPageUrlRegex.findAll(body).forEach { val possibleLink = it.value.substringAfter("href=\"") possibleLinks.add(possibleLink) } } println("Found possible first link [${possibleLinks[0]}]") return possibleLinks[0] }
0
Kotlin
0
0
0763d358851baee609a0008b2d6705b430334224
2,027
getting-to-wikipedia-kotlin
The Unlicense
src/main/kotlin/dev/shtanko/algorithms/leetcode/TwoCitySchedCost.kt
ashtanko
203,993,092
false
null
/* * Copyright 2020 Oleksii Shtanko * * 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 dev.shtanko.algorithms.leetcode /** * Two City Scheduling */ fun Array<IntArray>.twoCitySchedCost(): Int { var cost = 0 sortWith { a: IntArray, b: IntArray -> val first = a[1] - a[0] val second = b[1] - b[0] first - second } for (i in 0 until size / 2) { cost += this[i][1] + this[size - i - 1][0] } return cost }
6
null
0
19
23b1f7f7d6e6647f64fb637a3f4e76938cbbdf8c
985
Kotlin-Lab
Apache License 2.0
src/main/kotlin/VideoConverter.kt
AndreyBychkov
213,034,244
false
null
import ws.schild.jave.* import java.io.File internal class VideoConverter { fun convert(source: File, target: File) { val audio = AudioAttributes().apply { setCodec(AudioAttributes.DIRECT_STREAM_COPY) } val video = VideoAttributes().apply { setCodec("mpeg4") } val encodingAttributes = EncodingAttributes().apply { format = target.extension audioAttributes = audio videoAttributes = video } val encoder = Encoder() encoder.encode(MultimediaObject(source), target, encodingAttributes) } }
0
Kotlin
0
2
99d77efe0688a47a007c30fb7dccb2930e69857e
623
VideoConverter
MIT License
src/main/kotlin/Day03.kt
gijs-pennings
573,023,936
false
{"Kotlin": 20319}
fun main() { val lines = readInput(3) println(part1(lines.map { it.chunked(it.length / 2) })) println(part1(lines.chunked(3).map { listOf(it[0].intersect(it[1]), it[2]) })) } private fun part1(rucksacks: List<List<String>>) = rucksacks .map { it[0].intersect(it[1]).first() } .sumOf { if (it.isLowerCase()) it - 'a' + 1 else it - 'A' + 27 } private fun String.intersect(s: String) = toList().intersect(s.toSet()).joinToString("")
0
Kotlin
0
0
8ffbcae744b62e36150af7ea9115e351f10e71c1
452
aoc-2022
ISC License
orchestration_api/src/main/java/ru/flowernetes/orchestration/api/domain/usecase/SaveLogFromLogReaderUseCase.kt
b1nd
252,335,785
false
null
package ru.flowernetes.orchestration.api.domain.usecase import ru.flowernetes.entity.workload.Workload import java.io.Reader interface SaveLogFromLogReaderUseCase { fun exec(workload: Workload, reader: Reader) }
0
Kotlin
1
2
8eef7e3324642fa4b26a69be69525d79a4873ea4
217
flowernetes
MIT License
src/jvmMain/kotlin/com/sprinttracker/models/Models.kt
rafaelnferreira
672,568,405
false
null
package com.sprinttracker.models import com.sprinttracker.services.TimeTrackingServiceFacade.Companion.EXPECTED_NUMBER_OF_TRACKED_HOURS_PER_DAY import java.math.BigDecimal import java.math.RoundingMode import java.time.LocalDate import kotlin.math.max // marker to allow persistence interface Persistable<T> data class Configuration( val servicesUrl: String = "", val project: String = "", val team: String = "", val pat: String = "" ) : Persistable<Configuration> { fun isValid(): Boolean = servicesUrl.isNotEmpty() && project.isNotEmpty() && team.isNotEmpty() && pat.isNotEmpty() } enum class WorkItemType { EPIC, FEATURE, USER_STORY, TASK, BUG } data class WorkItem( val id: Long, val type: WorkItemType, val title: String, val state: String, val completedWork: Double, val remainingWork: Double, val parent: WorkItem?, val children: List<WorkItem>? ) { infix fun withParent(parent: WorkItem) = WorkItem( this.id, this.type, this.title, this.state, this.completedWork, this.remainingWork, parent, this.children ) infix fun withChild(child: WorkItem) = WorkItem( this.id, this.type, this.title, this.state, this.completedWork, this.remainingWork, this.parent, (this.children ?: emptyList()) + child ) infix fun withChildren(children: List<WorkItem>) = WorkItem( this.id, this.type, this.title, this.state, this.remainingWork, this.completedWork, this.parent, children ) infix fun isSame(other: WorkItem) = this.id == other.id val isPlaceholderOnly: Boolean get() = this.id < 1 } data class TimeEntry( val hours: Double, val workItem: WorkItem, val burn: Boolean = true, val closeWorkItem: Boolean = false, val date: LocalDate = LocalDate.now(), val expectedNumOfHoursTrackedPerDay: Int = EXPECTED_NUMBER_OF_TRACKED_HOURS_PER_DAY, ) { fun toPersistable() = PersistableTimeEntry(hours, workItem.id, burn, date) fun computeRemainingWork(): Double = if (burn) max(workItem.remainingWork - hours, 0.0) else workItem.remainingWork fun computeCompletedWork(): Double = if (workItem.type == WorkItemType.TASK) workItem.completedWork + hours else workItem.completedWork + BigDecimal(hours / expectedNumOfHoursTrackedPerDay).setScale(2, RoundingMode.UP) .toDouble() } data class PersistableTimeEntry(val hours: Double, val workItemId: Long, val burn: Boolean, val date: LocalDate) : Persistable<PersistableTimeEntry>
2
Kotlin
0
0
e3a3c94bd733a00bf51f62ec8760a5fa9d9c1bdb
2,677
sprint-tracker
Apache License 2.0
app/src/main/java/com/example/khabarapp/mvvm/NewsViewModel.kt
rajatkumarsingh01
751,651,200
false
{"Kotlin": 43722}
package com.example.khabarapp.mvvm import android.app.Application import android.content.Context import android.net.ConnectivityManager import android.net.NetworkCapabilities import android.os.Build import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.example.khabarapp.db.News import com.example.khabarapp.db.SavedArticle import com.example.khabarapp.wrapper.Resource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import retrofit2.Response import java.io.IOException class NewsViewModel(private val newsRepo: NewsRepo, private val application: Application):AndroidViewModel(application){ //Adding news data val breakingNews: MutableLiveData<Resource<News>?> = MutableLiveData() val pageNumber=1 val categoryNews: MutableLiveData<Resource<News>?> = MutableLiveData() //to get saved news val getSavedNews=newsRepo.getAllSavedNews() init { getBreakingNews("us") } fun getBreakingNews(code: String) = viewModelScope.launch { checkInternetandBreakingNews(code) } private suspend fun checkInternetandBreakingNews(code: String) { breakingNews.postValue(Resource.Loading()) try { if (hasInternetConnection()){ val response=newsRepo.getBreakingNews(code,pageNumber) breakingNews.postValue(handleNewsResponse(response)) }else{ breakingNews.postValue(Resource.Error("No INTERNET CONNECTION")) } }catch (t:Throwable){ when(t){ is IOException->breakingNews.postValue(Resource.Error("NETWORK FAILURE")) else -> breakingNews.postValue(Resource.Error("Conversion Error")) } } } private fun handleNewsResponse(response: Response<News>): Resource<News>? { if (response.isSuccessful){ response.body()?.let { resultresponse-> return Resource.Success(resultresponse) } } return Resource.Error(response.message()) } fun getCategory(cat:String)=viewModelScope.launch { categoryNews.postValue(Resource.Loading()) val response=newsRepo.getCategoryNews(cat) categoryNews.postValue(handleNewsResponse(response)) } //checking connectivity private fun hasInternetConnection(): Boolean { val connectivityManager = application.getSystemService( Context.CONNECTIVITY_SERVICE ) as ConnectivityManager if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val activeNetwork = connectivityManager.activeNetwork ?: return false val capabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false return when { capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true else -> false } } else { connectivityManager.activeNetworkInfo?.run { return when(type) { ConnectivityManager.TYPE_WIFI -> true ConnectivityManager.TYPE_MOBILE -> true ConnectivityManager.TYPE_ETHERNET -> true else -> false } } } return false } fun insertArticle(savedArticle: SavedArticle){ insertNews(savedArticle) } fun insertNews(savedArticle: SavedArticle)= viewModelScope.launch(Dispatchers.IO) { newsRepo.insertNews(savedArticle) } fun deleteAllArticles(){ deleteAll() } fun deleteAll()= viewModelScope.launch(Dispatchers.IO) { newsRepo.deleteAll() } }
0
Kotlin
0
0
f8d1009cd41f55aef1a286b1437e26d177cfecd3
3,961
KhabarApp
Open Market License
src/commonMain/kotlin/org/tix/integrations/jira/issue/Parent.kt
ncipollo
336,920,234
false
{"Kotlin": 601503}
package org.tix.integrations.jira.issue import kotlinx.serialization.Serializable @Serializable data class Parent( val id: String = "", val key: String = "" )
8
Kotlin
0
3
02f87c827c1159af055f5afc5481afd45c013703
169
tix-core
MIT License
tilbakekreving/infrastructure/src/main/kotlin/tilbakekreving/infrastructure/repo/vurdering/MånedsvurderingTilbakekrevingsbehandlingDbJson.kt
navikt
227,366,088
false
{"Kotlin": 8916291, "Shell": 3838, "TSQL": 1233, "Dockerfile": 800}
package tilbakekreving.infrastructure.repo.vurdering import arrow.core.Nel import no.nav.su.se.bakover.common.deserialize import no.nav.su.se.bakover.common.extensions.toNonEmptyList import no.nav.su.se.bakover.common.ident.NavIdentBruker import no.nav.su.se.bakover.common.serialize import no.nav.su.se.bakover.common.tid.Tidspunkt import no.nav.su.se.bakover.common.tid.periode.Måned import no.nav.su.se.bakover.hendelse.domain.DefaultHendelseMetadata import no.nav.su.se.bakover.hendelse.domain.HendelseId import no.nav.su.se.bakover.hendelse.domain.Hendelsesversjon import tilbakekreving.domain.MånedsvurderingerTilbakekrevingsbehandlingHendelse import tilbakekreving.domain.TilbakekrevingsbehandlingId import tilbakekreving.domain.vurdert.Månedsvurdering import tilbakekreving.domain.vurdert.Vurdering import tilbakekreving.domain.vurdert.Vurderinger import tilbakekreving.infrastructure.repo.vurdering.MånedsvurderingerDbJson.Companion.toDomain import java.lang.IllegalArgumentException import java.time.YearMonth import java.util.UUID internal fun mapToMånedsvurderingerTilbakekrevingsbehandlingHendelse( data: String, hendelseId: HendelseId, tidligereHendelsesId: HendelseId, sakId: UUID, hendelsestidspunkt: Tidspunkt, versjon: Hendelsesversjon, meta: DefaultHendelseMetadata, ): MånedsvurderingerTilbakekrevingsbehandlingHendelse { val deserialized = deserialize<MånedsvurderingTilbakekrevingsbehandlingDbJson>(data) return MånedsvurderingerTilbakekrevingsbehandlingHendelse( hendelseId = hendelseId, sakId = sakId, hendelsestidspunkt = hendelsestidspunkt, versjon = versjon, meta = meta, id = TilbakekrevingsbehandlingId(deserialized.behandlingsId), tidligereHendelseId = tidligereHendelsesId, utførtAv = NavIdentBruker.Saksbehandler(navIdent = deserialized.utførtAv), vurderinger = deserialized.vurderinger.toDomain(), ) } private data class MånedsvurderingTilbakekrevingsbehandlingDbJson( val behandlingsId: UUID, val utførtAv: String, val vurderinger: List<MånedsvurderingerDbJson>, ) internal fun MånedsvurderingerTilbakekrevingsbehandlingHendelse.toJson(): String { return MånedsvurderingTilbakekrevingsbehandlingDbJson( behandlingsId = this.id.value, utførtAv = this.utførtAv.navIdent, vurderinger = this.vurderinger.toJson(), ).let { serialize(it) } } private data class MånedsvurderingerDbJson( val måned: String, val vurdering: String, ) { fun toDomain(): Månedsvurdering = Månedsvurdering( måned = Måned.fra(YearMonth.parse(måned)), vurdering = when (vurdering) { "SkalIkkeTilbakekreve" -> Vurdering.SkalIkkeTilbakekreve "SkalTilbakekreve" -> Vurdering.SkalTilbakekreve else -> throw IllegalArgumentException("Ukjent vurderingstype") }, ) companion object { fun List<MånedsvurderingerDbJson>.toDomain(): Vurderinger = Vurderinger(this.map { it.toDomain() }.toNonEmptyList()) } } private fun Vurderinger.toJson(): Nel<MånedsvurderingerDbJson> = this.vurderinger.map { MånedsvurderingerDbJson( måned = it.måned.toString(), vurdering = when (it.vurdering) { Vurdering.SkalIkkeTilbakekreve -> "SkalIkkeTilbakekreve" Vurdering.SkalTilbakekreve -> "SkalTilbakekreve" }, ) }
0
Kotlin
1
1
f187a366e1b4ec73bf18f4ebc6a68109494f1c1b
3,413
su-se-bakover
MIT License
src/main/kotlin/io/art/gradle/common/configurator/SourceDependenciesConfigurator.kt
art-community
200,132,555
false
null
/* * ART * * Copyright 2019-2022 ART * * 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 io.art.gradle.common.configurator import CmakeSourceDependency import SourceDependenciesConfiguration import SourceDependency import UnixSourceDependency import io.art.gradle.common.constants.* import io.art.gradle.common.logger.logger import org.eclipse.jgit.api.Git import org.gradle.api.Project import java.io.File fun Project.configureSourceDependencies(configuration: SourceDependenciesConfiguration) { configuration.unixDependencies.forEach { dependency -> configureUnix(dependency, configuration) } configuration.cmakeDependencies.forEach { dependency -> configureCmake(dependency, configuration) } } private fun Project.configureUnix(dependency: UnixSourceDependency, sources: SourceDependenciesConfiguration) { val task = tasks.register("$BUILD-${dependency.name}") { group = SOURCES doLast { val dependencyDirectory = sources.directory.resolve(dependency.name).toFile() if (!dependencyDirectory.exists()) { dependencyDirectory.mkdirs() Git.cloneRepository() .setDirectory(dependencyDirectory) .setURI(dependency.url!!) .setCloneSubmodules(true) .apply { dependency.version?.let(::setBranch) } .call() } if (dependencyDirectory.resolve(MAKE_FILE).exists()) { executeDependencyCommand(dependency.makeCommand(), dependencyDirectory) copyDependencyBuiltFiles(dependency, dependencyDirectory) return@doLast } if (dependencyDirectory.resolve(CONFIGURE_SCRIPT).exists()) { dos2Unix(dependencyDirectory) executeDependencyCommand(dependency.configureCommand(), dependencyDirectory) executeDependencyCommand(dependency.makeCommand(), dependencyDirectory) copyDependencyBuiltFiles(dependency, dependencyDirectory) return@doLast } dos2Unix(dependencyDirectory) executeDependencyCommand(dependency.autogenCommand(), dependencyDirectory) executeDependencyCommand(dependency.configureCommand(), dependencyDirectory) executeDependencyCommand(dependency.makeCommand(), dependencyDirectory) copyDependencyBuiltFiles(dependency, dependencyDirectory) } } if (dependency.beforeBuild) { tasks.getByPath(BUILD).dependsOn(task) } if (dependency.beforeNativeBuild) { tasks.findByPath(BUILD_NATIVE_EXECUTABLE_TASK)?.dependsOn(task) } } private fun Project.configureCmake(dependency: CmakeSourceDependency, sources: SourceDependenciesConfiguration) { val task = tasks.register("$BUILD-${dependency.name}") { group = SOURCES doLast { val dependencyDirectory = sources.directory.resolve(dependency.name).toFile() if (!dependencyDirectory.exists()) { dependencyDirectory.mkdirs() Git.cloneRepository() .setDirectory(dependencyDirectory) .setURI(dependency.url ?: throw DEPENDENCY_URL_EXCEPTION) .apply { dependency.version?.let(::setBranch) } .setCloneSubmodules(true) .call() } if (dependency.wsl) dos2Unix(dependencyDirectory) if (!dependencyDirectory.resolve(CMAKE_CACHE).exists()) { executeDependencyCommand(dependency.cmakeConfigureCommand(), dependencyDirectory) } executeDependencyCommand(dependency.cmakeBuildCommand(), dependencyDirectory) copyDependencyBuiltFiles(dependency, dependencyDirectory) } } if (dependency.beforeBuild) { tasks.getByPath(BUILD).dependsOn(task) } if (dependency.beforeNativeBuild) { tasks.findByPath(BUILD_NATIVE_EXECUTABLE_TASK)?.dependsOn(task) } } private fun Project.copyDependencyBuiltFiles(dependency: SourceDependency, dependencyDirectory: File) { dependency.builtFiles().forEach { (from, to) -> copy { val source = dependencyDirectory.resolve(from) from(source.absolutePath) val destination = projectDir.resolve(to) if (destination.isDirectory) { into(destination.absolutePath) return@copy } into(destination.parentFile.absolutePath) rename(source.name, destination.name) } } } private fun Project.dos2Unix(dependencyDirectory: File) { val logger = logger(project.name) dependencyDirectory.listFiles()!!.asSequence().filter { file -> file.isFile }.forEach { file -> exec { commandLine(*bashCommand(DOS_TO_UNIX_FILE, file.absolutePath.wsl())) workingDir(dependencyDirectory) errorOutput = logger.error() } } } private fun Project.executeDependencyCommand(command: Array<String>, dependencyDirectory: File) { val logger = logger(project.name) exec { commandLine(*command) workingDir(dependencyDirectory) errorOutput = logger.error() } }
0
Kotlin
1
3
2c6fa18ff4e7b8857a540d042448b2bb425dea2c
5,844
art-gradle
Apache License 2.0
app/src/main/kotlin/com/rcaetano/marvelheroes/feature/favourite/FavouriteAdapter.kt
rodrigo-mnz
219,619,523
false
null
package com.rcaetano.marvelheroes.feature.favourite import android.view.View import android.view.ViewGroup import android.widget.ImageView import androidx.core.view.ViewCompat import androidx.recyclerview.widget.RecyclerView import com.rcaetano.marvelheroes.R import com.rcaetano.marvelheroes.data.model.Character import com.rcaetano.marvelheroes.inflate import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.item_character.view.* class FavouriteAdapter( private val onItemClick: (character: Character, imageView: ImageView) -> Unit, private val refreshList: () -> Unit ) : RecyclerView.Adapter<CharacterItem>() { var list: List<Character> = emptyList() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = CharacterItem( parent.inflate(R.layout.item_character), onItemClick, refreshList ) override fun getItemCount() = list.size override fun onBindViewHolder(holder: CharacterItem, position: Int) { holder.bind(list[position]) } } class CharacterItem( private val view: View, private val onItemClick: (character: Character, imageView: ImageView) -> Unit, private val refreshList: () -> Unit ) : RecyclerView.ViewHolder(view) { fun bind(character: Character) { view.setOnClickListener { ViewCompat.setTransitionName(view.img_character, "image$adapterPosition") onItemClick(character, view.img_character) } Picasso.get().load(buildThumbnailUri(character)) .placeholder(R.drawable.portrait_thumb_placeholder) .into(view.img_character) view.txt_name.text = character.name view.img_favourite.setImageResource(R.drawable.ic_favorite_full) view.img_favourite.setOnClickListener { FavouriteHelper.removeFavouriteCharacter(character, view.context) refreshList() } } private fun buildThumbnailUri(character: Character) = "${character.thumbnail.path}/portrait_xlarge.${character.thumbnail.extension}" }
0
Kotlin
0
0
1b9b947f8b08ae8fbe5097fb5c09d0c503abb023
2,092
marvel
MIT License
data/src/main/java/com.alorma.data/net/config/NetworkConfigDataSource.kt
Alhima
160,325,370
false
null
package com.alorma.data.net.config import com.alorma.domain.exception.DataOriginException import com.alorma.domain.model.Configuration class NetworkConfigDataSource(private val configApi: ConfigApi, private val mapper: ConfigurationMapper) { suspend fun get(): Configuration = try { mapper.map( configApi.getConfig().await(), configApi.getGenre().await() ) } catch (e: Exception) { throw DataOriginException() } }
0
Kotlin
0
0
aad70ea89f3ba47402538c1ee3d8c4cbb90f019e
582
TrendingMovies
Apache License 2.0
src/main/kotlin/no/nav/familie/ef/iverksett/tilbakekreving/TilbakekrevingListener.kt
navikt
357,821,728
false
null
package no.nav.familie.ef.iverksett.tilbakekreving import com.fasterxml.jackson.module.kotlin.readValue import no.nav.familie.ef.iverksett.felles.FamilieIntegrasjonerClient import no.nav.familie.ef.iverksett.iverksetting.IverksettingRepository import no.nav.familie.kontrakter.felles.objectMapper import no.nav.familie.kontrakter.felles.tilbakekreving.HentFagsystemsbehandlingRequest import no.nav.familie.kontrakter.felles.tilbakekreving.HentFagsystemsbehandlingRespons import no.nav.familie.kontrakter.felles.tilbakekreving.Ytelsestype import no.nav.familie.log.mdc.MDCConstants import org.apache.kafka.clients.consumer.ConsumerRecord import org.slf4j.LoggerFactory import org.slf4j.MDC import org.springframework.kafka.annotation.KafkaListener import org.springframework.kafka.listener.ConsumerSeekAware import org.springframework.stereotype.Component import java.util.UUID @Component class TilbakekrevingListener( private val iverksettingRepository: IverksettingRepository, private val familieIntegrasjonerClient: FamilieIntegrasjonerClient, private val tilbakekrevingProducer: TilbakekrevingProducer ) : ConsumerSeekAware { private val logger = LoggerFactory.getLogger(javaClass) private val secureLogger = LoggerFactory.getLogger("secureLogger") @KafkaListener( id = "familie-ef-iverksett", topics = ["teamfamilie.privat-tbk-hentfagsystemsbehandling-request-topic"], containerFactory = "concurrentTilbakekrevingListenerContainerFactory" ) fun listen(consumerRecord: ConsumerRecord<String, String>) { val key: String = consumerRecord.key() val data: String = consumerRecord.value() try { MDC.put(MDCConstants.MDC_CALL_ID, UUID.randomUUID().toString()) transformerOgSend(data, key) } catch (ex: Exception) { logger.error("Feil ved håndtering av HentFagsystemsbehandlingRequest med eksternId=$key") secureLogger.error("Feil ved håndtering av HentFagsystemsbehandlingRequest med consumerRecord=$consumerRecord", ex) throw ex } finally { MDC.remove(MDCConstants.MDC_CALL_ID) } } private fun transformerOgSend(data: String, key: String) { try { val request: HentFagsystemsbehandlingRequest = objectMapper.readValue(data) if (!request.erEfYtelse()) { return } logger.info("HentFagsystemsbehandlingRequest er mottatt i kafka med key=$key og data=$data") val iverksett = iverksettingRepository.hentAvEksternId(request.eksternId.toLong()) familieIntegrasjonerClient.hentBehandlendeEnhetForBehandling(iverksett.søker.personIdent)?.let { val fagsystemsbehandling = iverksett.tilFagsystembehandling(it) tilbakekrevingProducer.send(fagsystemsbehandling, key) } ?: error("Kan ikke finne behandlende enhet for søker på behandling ${iverksett.behandling.behandlingId}") } catch (ex: Exception) { secureLogger.error( "Feil ved sending av melding med key=$key. Forsøker å sende HentFagsystemsbehandlingRespons med feilmelding.", ex ) tilbakekrevingProducer.send(HentFagsystemsbehandlingRespons(feilMelding = ex.message), key) } } private fun HentFagsystemsbehandlingRequest.erEfYtelse(): Boolean { return listOf(Ytelsestype.OVERGANGSSTØNAD, Ytelsestype.SKOLEPENGER, Ytelsestype.BARNETILSYN).contains(this.ytelsestype) } }
3
Kotlin
0
0
9785e50dc2f1dbc65ef4ab60e23282504f7a85b0
3,559
familie-ef-iverksett
MIT License
android/src/test/java/com/amplitude/android/ConfigurationTest.kt
amplitude
448,411,338
false
{"Kotlin": 549264, "Java": 7655, "JavaScript": 1408}
package com.amplitude.android import android.app.Application import android.content.Context import com.amplitude.android.plugins.AndroidLifecyclePlugin import io.mockk.mockk import io.mockk.mockkStatic import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test class ConfigurationTest { private var context: Context? = null @BeforeEach fun setUp() { context = mockk<Application>(relaxed = true) mockkStatic(AndroidLifecyclePlugin::class) } @Test fun configuration_init_isValid() { val configuration = Configuration("test-apikey", context!!) Assertions.assertTrue(configuration.isValid()) } @Suppress("DEPRECATION") @Test fun configuration_allows_propertyUpdate() { val configuration = Configuration("test-apikey", context!!) Assertions.assertTrue(configuration.trackingSessionEvents) Assertions.assertTrue(configuration.defaultTracking.sessions) Assertions.assertFalse(configuration.defaultTracking.appLifecycles) Assertions.assertFalse(configuration.defaultTracking.deepLinks) Assertions.assertFalse(configuration.defaultTracking.screenViews) configuration.trackingSessionEvents = false configuration.defaultTracking.sessions = false configuration.defaultTracking.appLifecycles = true configuration.defaultTracking.deepLinks = true configuration.defaultTracking.screenViews = true Assertions.assertFalse(configuration.trackingSessionEvents) Assertions.assertFalse(configuration.defaultTracking.sessions) Assertions.assertTrue(configuration.defaultTracking.appLifecycles) Assertions.assertTrue(configuration.defaultTracking.deepLinks) Assertions.assertTrue(configuration.defaultTracking.screenViews) } @Test fun configuration_defaultTracking_quick_update() { val configuration = Configuration( "test-apikey", context!!, defaultTracking = DefaultTrackingOptions.ALL ) Assertions.assertTrue(configuration.defaultTracking.sessions) Assertions.assertTrue(configuration.defaultTracking.appLifecycles) Assertions.assertTrue(configuration.defaultTracking.deepLinks) Assertions.assertTrue(configuration.defaultTracking.screenViews) configuration.defaultTracking = DefaultTrackingOptions.NONE Assertions.assertFalse(configuration.defaultTracking.sessions) Assertions.assertFalse(configuration.defaultTracking.appLifecycles) Assertions.assertFalse(configuration.defaultTracking.deepLinks) Assertions.assertFalse(configuration.defaultTracking.screenViews) } }
26
Kotlin
10
27
4b834bd366b6cef05d362973cc03075a48e7b1aa
2,751
Amplitude-Kotlin
MIT License
app/src/main/java/com/ml/shubham0204/simpledocumentscanner/api/BoundingBox.kt
shubham0204
515,969,984
false
{"Kotlin": 41826}
package com.ml.shubham0204.simpledocumentscanner.api import android.graphics.PointF import android.graphics.RectF // BoundingBox class that holds the RectF for the predicted document class BoundingBox( private var p1 : PointF , p2 : PointF , private var p3 : PointF , p4 : PointF ) { var vertices = arrayOf( p1 , p2 , p3 , p4 ) companion object { // Creates a new BoundingBox instance from given x, y, width and height. fun createFromXYWH( x : Int , y : Int , w : Int , h : Int ) : BoundingBox { return BoundingBox( PointF( x.toFloat() , y.toFloat() ) , PointF( x.toFloat() , (y+h).toFloat() ) , PointF( (x+w).toFloat() , (y+h).toFloat() ) , PointF( (x+w).toFloat() , y.toFloat() ) ) } fun createFromRect( rect : RectF ) : BoundingBox { return BoundingBox( PointF(rect.left, rect.top ) , PointF( rect.left , rect.top + rect.height() ) , PointF( rect.left + rect.width() , rect.top + rect.height() ) , PointF( rect.left + rect.width() , rect.top ) ) } } // With the current `vertices`, return a new RectF fun toRectF() : RectF { return RectF( vertices[0].x , vertices[0].y , vertices[2].x , vertices[2].y ) } override fun toString(): String { return "${p1.x} ${p1.y} ${p3.x} ${p3.y}" } }
0
Kotlin
1
4
0a14ce0bc7a03f99d70ad544d3d30251f57c6f27
1,478
Simple_Document_Scanner_Android
Apache License 2.0
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/DrinkMargarita.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.regular import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Regular.DrinkMargarita: ImageVector get() { if (_drinkMargarita != null) { return _drinkMargarita!! } _drinkMargarita = fluentIcon(name = "Regular.DrinkMargarita") { fluentPath { moveTo(19.87f, 3.49f) arcToRelative(0.75f, 0.75f, 0.0f, true, false, -0.24f, -1.48f) lineToRelative(-6.0f, 1.0f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, -0.62f, 0.6f) lineTo(12.73f, 5.0f) lineTo(5.75f, 5.0f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, -0.75f, 0.75f) verticalLineToRelative(4.0f) arcToRelative(3.25f, 3.25f, 0.0f, false, false, 3.0f, 3.24f) verticalLineToRelative(0.51f) arcToRelative(4.0f, 4.0f, 0.0f, false, false, 3.25f, 3.93f) verticalLineToRelative(3.07f) horizontalLineToRelative(-2.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.0f, 1.5f) horizontalLineToRelative(6.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.0f, -1.5f) horizontalLineToRelative(-2.5f) verticalLineToRelative(-3.07f) arcTo(4.0f, 4.0f, 0.0f, false, false, 16.0f, 13.5f) lineTo(16.0f, 13.0f) curveToRelative(1.68f, -0.14f, 3.0f, -1.54f, 3.0f, -3.25f) verticalLineToRelative(-4.0f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, -0.75f, -0.75f) horizontalLineToRelative(-3.99f) lineToRelative(0.12f, -0.6f) lineToRelative(5.5f, -0.91f) close() moveTo(17.5f, 8.0f) horizontalLineToRelative(-3.84f) lineToRelative(0.3f, -1.5f) horizontalLineToRelative(3.54f) lineTo(17.5f, 8.0f) close() moveTo(13.36f, 9.5f) horizontalLineToRelative(4.14f) verticalLineToRelative(0.25f) curveToRelative(0.0f, 0.97f, -0.78f, 1.75f, -1.75f, 1.75f) horizontalLineToRelative(-0.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, -0.75f, 0.75f) verticalLineToRelative(1.25f) arcToRelative(2.5f, 2.5f, 0.0f, false, true, -5.0f, 0.0f) verticalLineToRelative(-1.25f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, -0.75f, -0.75f) horizontalLineToRelative(-0.5f) curveToRelative(-0.97f, 0.0f, -1.75f, -0.78f, -1.75f, -1.75f) lineTo(6.5f, 9.5f) horizontalLineToRelative(5.34f) lineTo(11.0f, 13.6f) arcToRelative(0.75f, 0.75f, 0.0f, true, false, 1.48f, 0.3f) lineToRelative(0.87f, -4.4f) close() moveTo(12.14f, 8.0f) lineTo(6.5f, 8.0f) lineTo(6.5f, 6.5f) horizontalLineToRelative(5.94f) lineToRelative(-0.3f, 1.5f) close() } } return _drinkMargarita!! } private var _drinkMargarita: ImageVector? = null
1
Kotlin
3
83
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
3,509
compose-fluent-ui
Apache License 2.0
common/network/android-library/src/main/java/me/s097t0r1/common/network/factory/NetworkServiceFactory.kt
s097t0r1
532,375,742
false
{"Kotlin": 254344, "FreeMarker": 2844, "Fluent": 172}
package me.s097t0r1.common.network.factory import retrofit2.Retrofit interface NetworkService interface NetworkServiceFactory { fun <T : NetworkService> create(serviceClass: Class<T>): T class Base(private val retrofit: Retrofit) : NetworkServiceFactory { override fun <T : NetworkService> create(serviceClass: Class<T>): T = retrofit.create(serviceClass) } } inline fun <reified T : NetworkService> NetworkServiceFactory.create() = this.create(T::class.java)
4
Kotlin
1
8
b77ad8bc65268eb4f5fe280bc6e2e9d02d4a7499
498
ktcast
MIT License
app/src/test/java/com/straucorp/mviflow/FlowUnitTest.kt
astraube
343,548,974
false
null
package com.straucorp.mviflow import com.straucorp.mviflow.commom.extensions.flatMapFirst import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay import kotlinx.coroutines.flow.* import kotlinx.coroutines.runBlocking import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class FlowUnitTest { @Test @ExperimentalCoroutinesApi fun flow_flatMapFirst() { runBlocking { flowFlatMapFirst() } } @ExperimentalCoroutinesApi suspend fun flowFlatMapFirst() { (1..2000).asFlow() .onEach { delay(50) } .flatMapFirst { v -> flow { delay(500) emit(v) } } .onEach { println("[*] $it") } .catch { println("Error $it") } .collect() } }
0
Kotlin
0
2
ca4ec9e80c8668aff94cd3256a13490f6788cf2a
1,013
MVI-Coroutines-Flow-Dagger-Hilt
MIT License
src/test/kotlin/parser/AtomicExpressionTests.kt
reutermj
623,244,412
false
{"Kotlin": 223132}
package parser import kotlin.test.* class AtomicExpressionTests { private inline fun <reified T: AtomicExpressionToken>tryParsing(text: String, whitespaceCombos: List<String>) { for (i in whitespaceCombos) { val s = "$text$i" testParse(s, ::parseExpression) { assertIs<AtomicExpression>(it) assertIs<T>(it.atom()) val builder = StringBuilder() it.atom().stringify(builder) assertEquals(text, builder.toString()) builder.clear() } } } @Test fun testParse() { tryParsing<NameToken>("a", whitespaceCombos) tryParsing<StringToken>("\"hello world\"", whitespaceCombos) tryParsing<BadStringToken>("\"hello world", whitespaceCombosStartingWithNewLine) tryParsing<CharToken>("'a'", whitespaceCombos) tryParsing<BadCharToken>("'a", whitespaceCombosStartingWithNewLine) tryParsing<IntToken>("1", whitespaceCombos) tryParsing<FloatToken>("1.1", whitespaceCombos) } @Test fun testReparse() { for (i in whitespaceCombos) { val inString = "a$i" val text = "bc" val start = Span(0, 1) val end = Span(0, 1) val change = Change(text, start, end) testReparse(inString, change) { parseExpression(it)!! } } for (i in whitespaceCombos) { val inString = "c$i" val text = "ab" val start = Span(0, 0) val end = Span(0, 0) val change = Change(text, start, end) testReparse(inString, change) { parseExpression(it)!! } } } fun testNullParse(inString: String) { val iterator = ParserIterator() iterator.add(inString) val expression = parseExpression(iterator) assertNull(expression) } @Test fun testBadToken() { testNullParse("") testNullParse("Abc") testNullParse("let") testNullParse("if") testNullParse("function") testNullParse("return") testNullParse(" ") testNullParse("\n") testNullParse(")") testNullParse("{") testNullParse("}") testNullParse(",") testNullParse(".") testNullParse(":") testNullParse("=") } }
7
Kotlin
0
0
740f60309da3e612e2e505424db98f554ea65e3b
2,383
cortecs
MIT License
components/src/test/java/uk/gov/android/ui/components/HelpTextTest.kt
govuk-one-login
687,488,193
false
null
package uk.gov.ui.components import androidx.compose.runtime.Composable import com.android.resources.NightMode import org.junit.runner.RunWith import org.junit.runners.Parameterized @RunWith(Parameterized::class) class HelpTextTest( private val parameters: Pair<HelpTextParameters, NightMode> ) : BaseScreenshotTest(parameters.second) { override val generateComposeLayout: @Composable () -> Unit = { GdsHelpText(parameters.first) } companion object { @JvmStatic @Parameterized.Parameters(name = "{index}: GdsHelpText") fun values(): List<Pair<HelpTextParameters, NightMode>> { val result: MutableList<Pair<HelpTextParameters, NightMode>> = mutableListOf() HelpTextProvider().values.forEach(applyNightMode(result)) return result } } }
8
null
1
5
87a64f831bf69fa4b56a8b7ba365ecbf2cc67d58
835
mobile-android-ui
MIT License
SetColumns/src/main/kotlin/example/App.kt
aterai
158,348,575
false
null
package example import java.awt.* // ktlint-disable no-wildcard-imports import javax.swing.* // ktlint-disable no-wildcard-imports import javax.swing.JSpinner.DefaultEditor fun makeUI(): Component { val field = JTextField(20) field.toolTipText = "JTextField#setColumns(20)" val password = JPasswordField(20) password.toolTipText = "JPasswordField#setColumns(20)" val spinner = JSpinner() spinner.toolTipText = "JSpinner#setColumns(20)" (spinner.editor as? DefaultEditor)?.textField?.columns = 20 val combo1 = JComboBox<String>() combo1.isEditable = true combo1.toolTipText = "JComboBox setEditable(true), setColumns(20)" (combo1.editor.editorComponent as? JTextField)?.columns = 20 val combo2 = JComboBox<String>() combo2.toolTipText = "JComboBox setEditable(true), default" combo2.isEditable = true val combo3 = JComboBox<String>() combo3.toolTipText = "JComboBox setEditable(false), default" val layout = SpringLayout() val p = JPanel(layout) layout.putConstraint(SpringLayout.WEST, field, 10, SpringLayout.WEST, p) layout.putConstraint(SpringLayout.WEST, password, 10, SpringLayout.WEST, p) layout.putConstraint(SpringLayout.WEST, spinner, 10, SpringLayout.WEST, p) layout.putConstraint(SpringLayout.WEST, combo1, 10, SpringLayout.WEST, p) layout.putConstraint(SpringLayout.WEST, combo2, 10, SpringLayout.WEST, p) layout.putConstraint(SpringLayout.WEST, combo3, 10, SpringLayout.WEST, p) layout.putConstraint(SpringLayout.NORTH, field, 10, SpringLayout.NORTH, p) layout.putConstraint(SpringLayout.NORTH, password, 10, SpringLayout.SOUTH, field) layout.putConstraint(SpringLayout.NORTH, spinner, 10, SpringLayout.SOUTH, password) layout.putConstraint(SpringLayout.NORTH, combo1, 10, SpringLayout.SOUTH, spinner) layout.putConstraint(SpringLayout.NORTH, combo2, 10, SpringLayout.SOUTH, combo1) layout.putConstraint(SpringLayout.NORTH, combo3, 10, SpringLayout.SOUTH, combo2) listOf(field, password, spinner, combo1, combo2, combo3).forEach { p.add(it) } return JPanel(BorderLayout()).also { it.add(p) it.preferredSize = Dimension(320, 240) } } fun main() { EventQueue.invokeLater { runCatching { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()) }.onFailure { it.printStackTrace() Toolkit.getDefaultToolkit().beep() } JFrame().apply { defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE contentPane.add(makeUI()) pack() setLocationRelativeTo(null) isVisible = true } } }
0
null
6
9
47a0c684f64c3db2c8b631b2c20c6c7f9205bcab
2,548
kotlin-swing-tips
MIT License
app/src/main/java/com/cagataymuhammet/contactlist/data/db/ContactDatabase.kt
cagataymuhammet
467,321,973
false
{"Kotlin": 70478}
package com.cagataymuhammet.contactlist.data.db import androidx.room.Database import androidx.room.RoomDatabase @Database(entities = [ContactEntity::class], version = 1) abstract class ContactDatabase : RoomDatabase() { abstract fun contactDao(): ContactDao }
0
Kotlin
0
3
e4b212f9f37391c838358412ca466251e954c47a
267
Contacts
Apache License 2.0
app/src/main/java/com/khanappsnj/characterviewer/ui/CharacterDetailFragment.kt
SKGitKit
632,900,190
false
null
package com.khanappsnj.characterviewer.ui import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.navigation.fragment.navArgs import com.bumptech.glide.Glide import com.khanappsnj.characterviewer.databinding.CharacterDetailBinding class CharacterDetailFragment : Fragment() { private val args: CharacterDetailFragmentArgs by navArgs() private var _binding: CharacterDetailBinding? = null private val binding get() = checkNotNull(_binding) { "Is the view visible?" } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = CharacterDetailBinding.inflate(inflater, container, false) return (binding.root) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val bundle = arguments if (!bundle!!.containsKey("charName")) { binding.apply { if (args.charImage.isNotEmpty()) { Glide.with(requireActivity()) .load("https://duckduckgo.com/${args.charImage}") .into(characterImageView) } titleTextView.text = args.charName descriptionTextView.text = args.charDescription } } else { binding.apply { Glide.with(requireActivity()) .load("https://duckduckgo.com/${bundle?.getString("charImage")}") .into(characterImageView) titleTextView.text = bundle.getString("charName") descriptionTextView.text = bundle.getString("charDescription") } } } override fun onDestroyView() { _binding = null super.onDestroyView() } }
0
Kotlin
0
0
d2778319e523a172bcbe2688cdd278c58adb209d
2,014
CharacterViewer
MIT License
androidutils/src/main/java/peru/android/dev/androidutils/FragmentExtensions.kt
Bruno125
158,170,168
true
{"Kotlin": 82012, "Java": 1123}
package peru.android.dev.androidutils import android.os.Handler import android.widget.Toast import androidx.fragment.app.Fragment import androidx.core.os.HandlerCompat.postDelayed fun Fragment.toast(message: Int, duration: Int = Toast.LENGTH_SHORT) = Toast.makeText(context, message, duration).show() fun Fragment.runWithDelay(delay: Long, predicate: ()->Unit) { val handler = Handler() handler.postDelayed({ predicate() }, delay) }
0
Kotlin
0
1
5b996ad482f9077c8abcf1071b38bc4fe518cd87
465
android-dev-peru-app
Apache License 2.0
src/jvmTest/kotlin/org/slf4j/LoggerUnitTest.kt
KodePadLaunch
322,977,922
false
null
package org.slf4j import kotlin.test.Test class LoggerUnitTest { private val logger: Logger = LoggerFactory.getLogger(LoggerUnitTest::class.java) @Test fun traceLog() { logger.trace("this is a trace log!") } @Test fun debugLog() { logger.debug("this is a debug log") } @Test fun infoLog() { logger.info("this is an info log") } @Test fun warnLog() { logger.warn("this is a warn log") } @Test fun errorLog() { logger.error("this is an error log") } }
0
Kotlin
0
0
2afdf0ed30ef8d11811424caa594e5ab9a6c2613
560
IrcClient
Apache License 2.0
Quiz/app/src/main/java/com/example/quiz/view_model/vm/QuestionViewModel.kt
KamilDonda
321,666,752
false
null
package com.example.quiz.view_model.vm import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.example.quiz.model.entities.Quiz import com.example.quiz.model.repository.QuizRepository import kotlinx.coroutines.launch class QuestionViewModel(application: Application) : AndroidViewModel(application) { private val _timeIsUp = MutableLiveData<Boolean>() val timeIsUp: LiveData<Boolean> get() = _timeIsUp fun setTimeIsUp(bool: Boolean) { _timeIsUp.value = bool } private var _currentQuizNumber = 0 val currentQuizNumber: Int get() = _currentQuizNumber fun incrementQuizNumber(): Boolean { val bool = _currentQuizNumber < _quizList.value!!.size - 1 if (bool) _currentQuizNumber++ resetProgressStatus() return bool } fun resetQuizNumber(): Int { _currentQuizNumber = 0 resetQuizList() resetProgressStatus() return _currentQuizNumber } private var _progressStatus: Int = 0 val progressStatus: Int get() = _progressStatus fun incrementProgressStatus(time: Int) { _progressStatus = time } private fun resetProgressStatus() { _progressStatus = 0 } private val _quizList: MutableLiveData<List<Quiz>> = MutableLiveData() val quizList: LiveData<List<Quiz>> get() = _quizList private fun resetQuizList() { _quizList.value = null } init { setTimeIsUp(false) } fun setCategoryAndDifficulty(category: Int? = null, difficulty: String = "all") { if (category != null) { if (difficulty == "all") { setQuizList(category) } else { setQuizList(category, difficulty) } } else { setQuizList() } } private fun setQuizList() { viewModelScope.launch { _quizList.value = QuizRepository .getQuiz() .results } } private fun setQuizList(category: Int) { viewModelScope.launch { _quizList.value = QuizRepository .getQuizFromCategory(category) .results } } private fun setQuizList(category: Int, difficulty: String) { viewModelScope.launch { _quizList.value = QuizRepository .getQuizFromCategoryWithDifficultyLevel(category, difficulty) .results } } fun getCurrentQuestion() = _quizList.value!![_currentQuizNumber].question fun getCurrentCorrectAnswer() = _quizList.value!![_currentQuizNumber].correct_answer fun getCurrentAnswers(): List<String> { val list: MutableList<String> = _quizList.value!![_currentQuizNumber].incorrect_answers as MutableList<String> val correct = getCurrentCorrectAnswer() if (!list.contains(correct)) list.add(correct) list.shuffle() return list } fun getCurrentCategory() = _quizList.value!![_currentQuizNumber].category }
0
Kotlin
0
1
755580ba0eefe3e44ed12096a60b15bcd0a3b826
3,211
QuizzzyMobile
MIT License
feature/logbook/src/main/java/com/loryblu/feature/logbook/navigation/LogbookNavigation.kt
loryblu
665,795,911
false
{"Kotlin": 248260}
package com.loryblu.feature.logbook.navigation import androidx.compose.runtime.collectAsState import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable import androidx.navigation.compose.navigation import com.loryblu.core.util.Screen import com.loryblu.feature.logbook.ui.task.LogbookTaskViewModel import com.loryblu.feature.logbook.ui.task.CategoryScreen import com.loryblu.feature.logbook.ui.home.LogbookScreen import com.loryblu.feature.logbook.ui.task.ShiftScreen import com.loryblu.feature.logbook.ui.task.TaskScreen import com.loryblu.feature.logbook.ui.home.LogbookHomeViewModel import com.loryblu.feature.logbook.ui.task.SummaryScreen import org.koin.androidx.compose.koinViewModel fun NavGraphBuilder.logbookNavigation( navController: NavController, onBackButtonClicked: () -> Unit ) { navigation( startDestination = Screen.Logbook.route, route = "logbook" ) { composable(route = Screen.Logbook.route) { val viewModel: LogbookHomeViewModel = koinViewModel() val userTasks = viewModel.userTasks.collectAsState() LogbookScreen( onBackButtonClicked = onBackButtonClicked, onNextScreenClicked = { navController.navigate(Screen.CategoryScreen.route) }, userTasks = userTasks.value, selectADayOfWeek = { viewModel.selectADayOfWeek(it) } ) } navigation( startDestination = Screen.CategoryScreen.route, route = "register_logbook_task" ) { composable(route = Screen.CategoryScreen.route) { val viewModel: LogbookTaskViewModel = koinViewModel() CategoryScreen( onBackButtonClicked = { navController.navigateUp() }, onNextScreenClicked = { viewModel.setSelectedCategory(it) navController.navigate(Screen.TaskScreen.route) }, onCloseButtonClicked = { navController.navigate(Screen.Dashboard.route) { popUpTo(Screen.Logbook.route) { inclusive = true } } }, ) } composable(route = Screen.TaskScreen.route) { val viewModel: LogbookTaskViewModel = koinViewModel() TaskScreen( onBackButtonClicked = { navController.navigateUp() }, onNextScreenClicked = { viewModel.setSelectedTask(it) navController.navigate(Screen.ShiftScreen.route) }, onCloseButtonClicked = { navController.navigate(Screen.Dashboard.route) { popUpTo(Screen.Logbook.route) { inclusive = true } } }, ) } composable(route = Screen.ShiftScreen.route) { val viewModel: LogbookTaskViewModel = koinViewModel() ShiftScreen( onBackButtonClicked = { navController.navigateUp() }, onNextScreenClicked = { shift, frequency -> viewModel.setShift(shift) viewModel.setFrequency(frequency) navController.navigate(Screen.SummaryScreen.route) }, onCloseButtonClicked = { navController.navigate(Screen.Dashboard.route) { popUpTo(Screen.Logbook.route) { inclusive = true } } }, ) } composable(route = Screen.SummaryScreen.route) { val viewModel: LogbookTaskViewModel = koinViewModel() SummaryScreen( onBackButtonClicked = { navController.navigate(Screen.Logbook.route) { popUpTo(Screen.Logbook.route) { inclusive = true } } }, onCloseButtonClicked = { navController.navigate(Screen.Dashboard.route) { popUpTo(Screen.Logbook.route) { inclusive = true } } }, logbookTaskModel = viewModel.getLogbookTaskModel() ) { } } } } }
0
Kotlin
4
4
fdfd8338a4cee024bb69678dc3dc1375223b0f93
4,610
loryblu-android
MIT License
appcues/src/main/java/com/appcues/statemachine/State.kt
appcues
413,524,565
false
{"Kotlin": 1101664, "Shell": 17991, "Ruby": 1503}
package com.appcues.statemachine import com.appcues.data.model.Experience internal sealed class State { object Idling : State() data class BeginningExperience(val experience: Experience) : State() data class BeginningStep( val experience: Experience, val flatStepIndex: Int, val isFirst: Boolean, var metadata: Map<String, Any?> = hashMapOf(), ) : State() data class RenderingStep(val experience: Experience, val flatStepIndex: Int, val isFirst: Boolean) : State() data class EndingStep( val experience: Experience, val flatStepIndex: Int, val markComplete: Boolean, // this works as a ContinuationSideEffect that AppcuesViewModel will // send to the state machine once it's done dismissing the current container // the presence of a non-null value is what tells the UI to dismiss the current container, // and it should be set to null if a dismiss is not requested (i.e. moving to next step in same container) val onUiDismissed: (() -> Unit)?, ) : State() data class EndingExperience( val experience: Experience, val flatStepIndex: Int, val markComplete: Boolean, val trackAnalytics: Boolean, // to disable analytics on force stop ) : State() val currentExperience: Experience? get() = when (this) { is Idling -> null is BeginningExperience -> this.experience is BeginningStep -> this.experience is EndingExperience -> this.experience is EndingStep -> this.experience is RenderingStep -> this.experience } val currentStepIndex: Int? get() = when (this) { is Idling -> null is BeginningExperience -> null is BeginningStep -> this.flatStepIndex is EndingExperience -> this.flatStepIndex is EndingStep -> this.flatStepIndex is RenderingStep -> this.flatStepIndex } }
4
Kotlin
1
9
f89fdadba3e08d161e5d674efa9eb6a46759608b
2,020
appcues-android-sdk
MIT License
testapp/src/main/java/com/rakuten/tech/mobile/testapp/ui/display/preload/PreloadMiniAppViewModel.kt
minh-rakuten
239,911,943
true
{"Kotlin": 532008}
package com.rakuten.tech.mobile.testapp.ui.display.preload import androidx.lifecycle.* import com.rakuten.tech.mobile.miniapp.MiniApp import com.rakuten.tech.mobile.miniapp.MiniAppManifest import com.rakuten.tech.mobile.miniapp.MiniAppSdkException import com.rakuten.tech.mobile.miniapp.permission.MiniAppCustomPermission import com.rakuten.tech.mobile.miniapp.permission.MiniAppCustomPermissionResult import com.rakuten.tech.mobile.miniapp.permission.MiniAppCustomPermissionType import com.rakuten.tech.mobile.testapp.ui.settings.AppSettings import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class PreloadMiniAppViewModel constructor(private val miniApp: MiniApp) : ViewModel() { constructor() : this(MiniApp.instance(AppSettings.instance.miniAppSettings)) private val _miniAppManifest = MutableLiveData<MiniAppManifest>() private val _manifestErrorData = MutableLiveData<String>() val miniAppManifest: LiveData<MiniAppManifest> get() = _miniAppManifest val manifestErrorData: LiveData<String> get() = _manifestErrorData fun checkMiniAppManifest(miniAppId: String, versionId: String) = viewModelScope.launch(Dispatchers.IO) { try { val miniAppManifest = miniApp.getMiniAppManifest(miniAppId, versionId) val downloadedManifest = miniApp.getDownloadedManifest(miniAppId) if (downloadedManifest != null && isManifestEqual(miniAppManifest, downloadedManifest) && isAcceptedRequiredPermissions(miniAppId, miniAppManifest)) _miniAppManifest.postValue(null) else _miniAppManifest.postValue(miniAppManifest) } catch (error: MiniAppSdkException) { _manifestErrorData.postValue(error.message) } } private fun isManifestEqual(apiManifest: MiniAppManifest, downloadedManifest: MiniAppManifest): Boolean { val changedRequiredPermissions = (apiManifest.requiredPermissions + downloadedManifest.requiredPermissions).groupBy { it.first.type } .filter { it.value.size == 1 } .flatMap { it.value } val changedOptionalPermissions = (apiManifest.optionalPermissions + downloadedManifest.optionalPermissions).groupBy { it.first.type } .filter { it.value.size == 1 } .flatMap { it.value } return changedRequiredPermissions.isEmpty() && changedOptionalPermissions.isEmpty() && apiManifest.customMetaData == downloadedManifest.customMetaData } fun storeManifestPermission( miniAppId: String, permissions: List<Pair<MiniAppCustomPermissionType, MiniAppCustomPermissionResult>> ) { // store values in SDK cache val permissionsWhenAccept = MiniAppCustomPermission( miniAppId = miniAppId, pairValues = permissions ) miniApp.setCustomPermissions(permissionsWhenAccept) } private fun isAcceptedRequiredPermissions(miniAppId: String, manifest: MiniAppManifest): Boolean { // verify if user has been denied any required permission val cachedPermissions = miniApp.getCustomPermissions(miniAppId).pairValues val notGrantedPairs = mutableListOf<Pair<MiniAppCustomPermissionType, MiniAppCustomPermissionResult>>() manifest.requiredPermissions.forEach { (first) -> cachedPermissions.find { it.first == first && it.second == MiniAppCustomPermissionResult.DENIED }?.let { notGrantedPairs.add(it) } } return notGrantedPairs.isEmpty() } }
0
Kotlin
0
0
3615a82e9e4b76f477381c4bd0c2d2b64e2a5330
3,635
android-miniapp
MIT License
app/src/main/java/com/example/codepathwordle/StartUp.kt
AKolari
766,016,539
false
{"Kotlin": 14453}
package com.example.codepathwordle import android.content.Intent import android.os.Bundle import android.os.Vibrator import android.view.View import android.widget.Button import android.widget.EditText import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.core.view.isInvisible import androidx.core.view.isVisible class StartUp : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home) val startButton = findViewById<Button>(R.id.buttonStart) val rulesButton = findViewById<Button>(R.id.buttonRules) val allTextViews= arrayOf(findViewById<TextView>(R.id.h1), findViewById<TextView>(R.id.h2), findViewById<TextView>(R.id.textView), findViewById<TextView>(R.id.textView2), findViewById<TextView>(R.id.textView3)) var showRules=false startButton.setOnClickListener{ val startIntent= Intent(this, MainActivity::class.java ) startActivity(startIntent) finish() } rulesButton.setOnClickListener{ if(showRules){ showRules=false allTextViews[1].isVisible=true; allTextViews[0].text= "Wordle, But Worse " allTextViews[2].isInvisible=true allTextViews[3].isInvisible=true allTextViews[4].isInvisible=true startButton.isVisible=true rulesButton.setText("Rules") } else{ showRules=true allTextViews[1].isInvisible=true; allTextViews[0].text= "Guess a Four Letter Word" allTextViews[2].isVisible=true allTextViews[3].isVisible=true allTextViews[4].isVisible=true startButton.isInvisible=true rulesButton.setText("Go Back") } } } }
0
Kotlin
0
0
ca5e471a8b37b5bcf1f741f661f9e8098d4753db
2,021
Codepath-Wordle
Apache License 2.0
subscription-service/src/main/kotlin/com/egm/stellio/subscription/job/TimeIntervalNotificationJob.kt
stellio-hub
257,818,724
false
null
package com.egm.stellio.subscription.job import arrow.core.flatten import com.egm.stellio.shared.model.CompactedJsonLdEntity import com.egm.stellio.shared.util.* import com.egm.stellio.subscription.model.EntityInfo import com.egm.stellio.subscription.model.Notification import com.egm.stellio.subscription.model.Subscription import com.egm.stellio.subscription.service.NotificationService import com.egm.stellio.subscription.service.SubscriptionService import kotlinx.coroutines.reactive.awaitFirst import kotlinx.coroutines.runBlocking import org.springframework.http.HttpHeaders import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Component import org.springframework.web.reactive.function.client.WebClient @Component class TimeIntervalNotificationJob( private val subscriptionService: SubscriptionService, private val notificationService: NotificationService, private val webClient: WebClient ) { @Scheduled(fixedRate = 1000) fun sendTimeIntervalNotification() { runBlocking { subscriptionService.getRecurringSubscriptionsToNotify().forEach { subscription -> val contextLink = subscriptionService.getContextsLink(subscription) // TODO send one notification per subscription getEntitiesToNotify(subscription, contextLink).forEach { compactedEntity -> sendNotification(compactedEntity, subscription) } } } } fun prepareQueryParams(entityInfo: EntityInfo, q: String?, attributes: List<String>?): String { val param = java.lang.StringBuilder() param.append("?$QUERY_PARAM_TYPE=${entityInfo.type.encode()}") if (entityInfo.id != null) param.append("&$QUERY_PARAM_ID=${entityInfo.id}") if (entityInfo.idPattern != null) param.append("&$QUERY_PARAM_ID_PATTERN=${entityInfo.idPattern}") if (q != null) param.append("&$QUERY_PARAM_FILTER=${q.encode()}") if (!attributes.isNullOrEmpty()) param.append("&$QUERY_PARAM_ATTRS=${attributes.joinToString(",")}") return param.toString() } suspend fun sendNotification( compactedEntity: CompactedJsonLdEntity, subscription: Subscription ): Triple<Subscription, Notification, Boolean> = notificationService.callSubscriber( subscription, compactedEntity ) suspend fun getEntitiesToNotify( subscription: Subscription, contextLink: String ): Set<CompactedJsonLdEntity> = subscription.entities .map { getEntities(prepareQueryParams(it, subscription.q, subscription.notification.attributes), contextLink) } .flatten() .toSet() suspend fun getEntities(paramRequest: String, contextLink: String): List<CompactedJsonLdEntity> = webClient.get() .uri("/ngsi-ld/v1/entities$paramRequest") .header(HttpHeaders.LINK, contextLink) .retrieve() .bodyToMono(String::class.java) .map { JsonUtils.deserializeListOfObjects(it) } .awaitFirst() }
43
Kotlin
9
21
1e504ca31e75e9a921cd3324839e4b97fcfa36ad
3,179
stellio-context-broker
Apache License 2.0
src/jvmMain/kotlin/CommonDefsImplJvm.kt
JetBrains
27,873,341
false
{"Kotlin": 1305157, "Lex": 29252, "Ruby": 691, "Shell": 104}
package org.intellij.markdown.html import org.intellij.markdown.lexer.Stack import java.net.URLEncoder actual class BitSet actual constructor(size: Int): java.util.BitSet(size){ actual val size = size() } private const val PUNCTUATION_MASK: Int = (1 shl Character.DASH_PUNCTUATION.toInt()) or (1 shl Character.START_PUNCTUATION.toInt()) or (1 shl Character.END_PUNCTUATION.toInt()) or (1 shl Character.CONNECTOR_PUNCTUATION.toInt()) or (1 shl Character.OTHER_PUNCTUATION.toInt()) or (1 shl Character.INITIAL_QUOTE_PUNCTUATION.toInt()) or (1 shl Character.FINAL_QUOTE_PUNCTUATION.toInt()) or (1 shl Character.MATH_SYMBOL.toInt()) actual typealias URI = java.net.URI actual fun isWhitespace(char: Char): Boolean { return char == 0.toChar() || Character.isSpaceChar(char) || char.isWhitespace() } actual fun isPunctuation(char: Char): Boolean { return isAsciiPunctuationFix(char) || (PUNCTUATION_MASK shr Character.getType(char)) and 1 != 0 } private fun isAsciiPunctuationFix(char: Char): Boolean { // the ones which are not covered by a more general check return "$^`".contains(char) } actual fun urlEncode(str: String): String { return URLEncoder.encode(str, "UTF-8") }
56
Kotlin
75
661
43c06cb6a9d66caab8b431f738aba3c57aee559f
1,272
markdown
Apache License 2.0
app/src/main/java/in/junkielabs/parking/components/api/models/auth/ParamAuthVerify.kt
JunkieLabs
361,432,908
false
null
package `in`.junkielabs.parking.components.api.models.auth import `in`.junkielabs.parking.components.api.models.guard.ParamGuard import com.squareup.moshi.JsonClass import java.io.Serializable /** * Created by niraj on 02-01-2020. */ @JsonClass(generateAdapter = true) data class ParamAuthVerify( var user: ParamAuthUser, var guard: ParamGuard ): Serializable
0
Kotlin
4
7
e5e8c3f09560b0d27efe08c9744d43ddb1db41fe
364
junkie-parking-android-app
MIT License
src/commonMain/kotlin/data/items/ThickFelsteelNecklace.kt
marisa-ashkandi
332,658,265
false
null
package `data`.items import `data`.Constants import `data`.buffs.Buffs import `data`.model.Item import `data`.model.ItemSet import `data`.model.Socket import `data`.model.SocketBonus import character.Buff import character.Stats import kotlin.Array import kotlin.Boolean import kotlin.Double import kotlin.Int import kotlin.String import kotlin.collections.List import kotlin.js.JsExport @JsExport public class ThickFelsteelNecklace : Item() { public override var isAutoGenerated: Boolean = true public override var id: Int = 24106 public override var name: String = "Thick Felsteel Necklace" public override var itemLevel: Int = 113 public override var quality: Int = 3 public override var icon: String = "inv_jewelry_necklace_17.jpg" public override var inventorySlot: Int = 2 public override var itemSet: ItemSet? = null public override var itemClass: Constants.ItemClass? = Constants.ItemClass.ARMOR public override var itemSubclass: Constants.ItemSubclass? = Constants.ItemSubclass.MISC public override var allowableClasses: Array<Constants.AllowableClass>? = null public override var minDmg: Double = 0.0 public override var maxDmg: Double = 0.0 public override var speed: Double = 0.0 public override var stats: Stats = Stats( stamina = 36, resilienceRating = 23.0 ) public override var sockets: Array<Socket> = arrayOf() public override var socketBonus: SocketBonus? = null public override val buffs: List<Buff> by lazy { listOfNotNull( Buffs.byIdOrName(31023, "Thick Felsteel Necklace", this) )} }
21
Kotlin
11
25
9cb6a0e51a650b5d04c63883cb9bf3f64057ce73
1,604
tbcsim
MIT License
onnx/src/jvmMain/kotlin/org/jetbrains/kotlinx/dl/onnx/inference/facealignment/Fan2D106FaceAlignmentModel.kt
juliabeliaeva
393,365,928
true
{"Kotlin": 1591347, "Jupyter Notebook": 50439}
/* * Copyright 2020-2022 JetBrains s.r.o. and Kotlin Deep Learning project contributors. All Rights Reserved. * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file. */ package org.jetbrains.kotlinx.dl.onnx.inference.facealignment import org.jetbrains.kotlinx.dl.api.core.shape.TensorShape import org.jetbrains.kotlinx.dl.api.inference.InferenceModel import org.jetbrains.kotlinx.dl.api.inference.facealignment.Landmark import org.jetbrains.kotlinx.dl.api.preprocessing.Operation import org.jetbrains.kotlinx.dl.api.preprocessing.pipeline import org.jetbrains.kotlinx.dl.impl.preprocessing.call import org.jetbrains.kotlinx.dl.impl.preprocessing.image.* import org.jetbrains.kotlinx.dl.onnx.inference.ONNXModels import org.jetbrains.kotlinx.dl.onnx.inference.OnnxInferenceModel import java.awt.image.BufferedImage import java.io.File import java.io.IOException private const val OUTPUT_NAME = "fc1" /** * The light-weight API for solving Face Alignment task via Fan2D106 model. * * @param [internalModel] model used to make predictions */ public class Fan2D106FaceAlignmentModel( override val internalModel: OnnxInferenceModel, modelKindDescription: String? = null ) : FaceAlignmentModelBase<BufferedImage>(modelKindDescription), InferenceModel by internalModel { override val preprocessing: Operation<BufferedImage, Pair<FloatArray, TensorShape>> get() = pipeline<BufferedImage>() .resize { outputWidth = internalModel.inputDimensions[2].toInt() outputHeight = internalModel.inputDimensions[1].toInt() } .convert { colorMode = ColorMode.BGR } .toFloatArray {} .call(ONNXModels.FaceAlignment.Fan2d106.preprocessor) override val outputName: String = OUTPUT_NAME /** * Constructs the face alignment model from a given path. * @param [pathToModel] path to model */ public constructor(pathToModel: String) : this(OnnxInferenceModel(pathToModel)) /** * Detects 106 [Landmark] objects for the given [imageFile]. * @param [imageFile] file containing an input image */ @Throws(IOException::class) public fun detectLandmarks(imageFile: File): List<Landmark> { return detectLandmarks(ImageConverter.toBufferedImage(imageFile)) } override fun copy( copiedModelName: String?, saveOptimizerState: Boolean, copyWeights: Boolean ): Fan2D106FaceAlignmentModel { return Fan2D106FaceAlignmentModel( internalModel.copy(copiedModelName, saveOptimizerState, copyWeights), modelKindDescription ) } }
0
Kotlin
0
1
752afe86c486e75ffe1473b75401ae0da8469794
2,700
KotlinDL
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/dynamodb/OperationsMetricOptionsDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.dynamodb import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.dynamodb.OperationsMetricOptions @Generated public fun buildOperationsMetricOptions(initializer: @AwsCdkDsl OperationsMetricOptions.Builder.() -> Unit): OperationsMetricOptions = OperationsMetricOptions.Builder().apply(initializer).build()
1
Kotlin
0
0
b22e397ff37c5fce365a5430790e5d83f0dd5a64
439
aws-cdk-kt
Apache License 2.0
src/commonMain/kotlin/com/cozmicgames/graphics/gpu/layout/Vec2VertexComponent.kt
CozmicGames
477,147,957
false
{"Kotlin": 690755}
package com.cozmicgames.graphics.gpu.layout import com.cozmicgames.Kore import com.cozmicgames.log import com.cozmicgames.memory.Memory import com.cozmicgames.utils.maths.Vector2 import com.cozmicgames.graphics.gpu.VertexLayout class Vec2VertexComponent(name: String, normalized: Boolean, type: VertexLayout.AttributeType) : VertexComponent.Normal<Vector2>(name, type, 2, normalized) { override fun writeToMemory(value: Vector2, memory: Memory, offset: Int) { if (!isNormalized) { memory.setFloat(offset, value.x) memory.setFloat(offset + Memory.SIZEOF_FLOAT, value.y) } else when (type) { VertexLayout.AttributeType.BYTE -> { memory.setByte(offset, (value.x * 0xFF).toInt().toByte()) memory.setByte(offset + Memory.SIZEOF_BYTE, (value.y * 0xFF).toInt().toByte()) } VertexLayout.AttributeType.SHORT -> { memory.setShort(offset, (value.x * 0xFFFF).toInt().toShort()) memory.setShort(offset + Memory.SIZEOF_SHORT, (value.y * 0xFFFF).toInt().toShort()) } VertexLayout.AttributeType.INT -> { memory.setInt(offset, (value.x * 0xFFFFFFFF).toInt()) memory.setInt(offset + Memory.SIZEOF_INT, (value.y * 0xFFFFFFFF).toInt()) } else -> Kore.log.error(Vec2VertexComponent::class, "Unsupported vertex component configuration (Type: $type, Normalized: $isNormalized)") } } override fun readFromMemory(memory: Memory, offset: Int): Vector2 { val result = Vector2() if (!isNormalized) { result.x = memory.getFloat(offset) result.y = memory.getFloat(offset + Memory.SIZEOF_FLOAT) } else when (type) { VertexLayout.AttributeType.BYTE -> { result.x = memory.getByte(offset) / 0xFF.toFloat() result.y = memory.getByte(offset + Memory.SIZEOF_BYTE) / 0xFF.toFloat() } VertexLayout.AttributeType.SHORT -> { result.x = memory.getShort(offset) / 0xFFFF.toFloat() result.y = memory.getShort(offset + Memory.SIZEOF_SHORT) / 0xFFFF.toFloat() } VertexLayout.AttributeType.INT -> { result.x = memory.getInt(offset) / 0xFFFFFFFF.toFloat() result.y = memory.getInt(offset + Memory.SIZEOF_INT) / 0xFFFFFFFF.toFloat() } else -> Kore.log.error(Vec2VertexComponent::class, "Unsupported vertex component configuration (Type: $type, Normalized: $isNormalized)") } return result } override fun createVertexComponentObject() = Vector2() }
0
Kotlin
0
0
08290e122f639e87c823f8220c80738c1c7fb631
2,697
Kore
MIT License
src/org/aoc2021/Day14.kt
jsgroth
439,763,933
false
{"Kotlin": 86732}
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path object Day14 { private const val iterationsPart1 = 10 private const val iterationsPart2 = 40 private fun solve(lines: List<String>, iterations: Int): Long { val start = lines[0] val rules = lines.drop(2).map { it.split(" -> ") }.associate { it[0] to it[1] } val startMap = start.windowed(2).groupBy { it }.mapValues { (_, values) -> values.size.toLong() } val processed = (1..iterations).fold(startMap) { polymer, _ -> doIteration(polymer, rules) } val countsByChar = processed.entries.flatMap { (pair, count) -> listOf( pair[0] to count, pair[1] to count ) } .groupBy(Pair<Char, Long>::first, Pair<Char, Long>::second) .mapValues { (_, counts) -> counts.sum() } .mapValues { (c, count) -> if (c == start.first() || c == start.last()) { if (start.first() == start.last()) { (count + 2) / 2 } else { (count + 1) / 2 } } else { count / 2 } } return countsByChar.values.maxOrNull()!! - countsByChar.values.minOrNull()!! } private fun doIteration(polymer: Map<String, Long>, rules: Map<String, String>): Map<String, Long> { val newMap = mutableMapOf<String, Long>() polymer.forEach { (pair, count) -> val rule = rules[pair] if (rule != null) { newMap.merge(pair[0] + rule, count) { a, b -> a + b } newMap.merge(rule + pair[1], count) { a, b -> a + b } } else { newMap.merge(pair, count) { a, b -> a + b } } } return newMap.toMap() } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input14.txt"), Charsets.UTF_8) val solution1 = solve(lines, iterationsPart1) println(solution1) val solution2 = solve(lines, iterationsPart2) println(solution2) } }
0
Kotlin
0
0
ba81fadf2a8106fae3e16ed825cc25bbb7a95409
2,155
advent-of-code-2021
The Unlicense
dsl/src/main/kotlin/com/github/weisj/swingdsl/dsl/components/HideableTreeExtensions.kt
weisJ
349,581,043
false
null
/* * MIT License * * Copyright (c) 2021 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.github.weisj.swingdsl.dsl.components import com.github.weisj.swingdsl.components.HideableTree import com.github.weisj.swingdsl.components.HideableTreeNode import com.github.weisj.swingdsl.core.condition.ObservableCondition import com.github.weisj.swingdsl.dsl.onSwingThread @Suppress("unused") private fun <T> HideableTreeNode<T>.bindVisible( node: HideableTreeNode<*>, tree: HideableTree, visibleBinding: ObservableCondition?, ) { visibleBinding ?: return node.isVisibleBase = visibleBinding.get() visibleBinding.onChange { onSwingThread { tree.setNodeVisible(node, it) } } } @Suppress("unused") private fun <T> HideableTreeNode<T>.bindEnabled( node: HideableTreeNode<*>, tree: HideableTree, enabledBinding: ObservableCondition?, ) { enabledBinding ?: return node.isEnabledBase = enabledBinding.get() enabledBinding.onChange { onSwingThread { tree.setNodeEnabled(node, it) } } } fun <T> HideableTreeNode<T>.addWithBinding( node: HideableTreeNode<*>, tree: HideableTree, visibleBinding: ObservableCondition? = null, enabledBinding: ObservableCondition? = null ) { add(node) bindVisible(node, tree, visibleBinding) bindEnabled(node, tree, enabledBinding) }
4
Kotlin
0
6
7291a86a000007d74027cc7ec1b332664ea60cb7
2,444
swing-dsl
MIT License
app/src/main/java/uk/co/dekoorb/android/cryptowatch/net/CoinMarketCapService.kt
edbrook
118,527,767
false
null
package uk.co.dekoorb.android.cryptowatch.net import com.google.gson.GsonBuilder import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Query import uk.co.dekoorb.android.cryptowatch.db.entity.Currency /** * Created by edbrook on 23/01/2018. */ interface CoinMarketCapService { @GET("v1/ticker/") fun getConvertedCurrencies(@Query("convert") toCurrency: String): Call<List<Currency>> } class CoinMarketCapServiceBuilder { companion object { const val API_BASE_URL = "https://api.coinmarketcap.com/" } private fun getRetrofit(): Retrofit { val gson = GsonBuilder() .registerTypeAdapter(Currency::class.java, CurrencyGsonDeserializer()) .create() return Retrofit.Builder() .baseUrl(API_BASE_URL) .addConverterFactory(GsonConverterFactory.create(gson)) .build() } fun getCoinMarketCapService(): CoinMarketCapService { val retrofit = getRetrofit() return retrofit.create(CoinMarketCapService::class.java) } }
0
Kotlin
0
0
d83bba7ec1db3f87dfd29f10b4907a55e78e28c5
1,158
android-CryptoWatch
MIT License
app/src/main/java/com/harrypotter/features/characters/detail/vm/CharacterDetailViewModel.kt
mnlmato
625,648,336
false
{"Kotlin": 115492}
package com.harrypotter.features.characters.detail.vm import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.harrypotter.coreui.resourceprovider.ResourceProvider import com.harrypotter.coreui.vm.SingleLiveData import com.harrypotter.features.characters.detail.domain.usecase.GetCharacterUseCase import com.harrypotter.features.characters.main.vm.mapper.toCharacterUI import com.harrypotter.features.characters.main.vm.model.CharacterUI import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel class CharacterDetailViewModel @Inject constructor( private val getCharacterUseCase: GetCharacterUseCase, private val resourceProvider: ResourceProvider, ) : ViewModel() { val closeScreenEvent = SingleLiveData<Unit>() private val characterMutableEvent = MutableLiveData<CharacterUI>() val characterEvent: LiveData<CharacterUI> get() = characterMutableEvent fun loadCharacter(id: String) { characterMutableEvent.value = getCharacterUseCase(id).toCharacterUI(resourceProvider) } fun onBackClicked() { closeScreenEvent.value = Unit } }
0
Kotlin
0
3
b8397ef6212b78d9afc86519a68f8b4bfc3a43fb
1,196
harrypotter
The Unlicense
SecureCamera/src/main/java/io/github/toyota32k/secureCamera/data/ChapterEditor.kt
toyota-m2k
594,937,009
false
null
package io.github.toyota32k.secureCamera.data class ChapterEditor { }
2
Kotlin
0
0
c4da942036eb6e746718e38789ccc53e9aa03bb2
70
android-camera
Apache License 2.0
src_old/main/kotlin/glm/swizzle.kt
FauxKiwi
315,724,386
false
null
package glm /////////////////////////////////////////////////////////////////////////// // Vec2 /////////////////////////////////////////////////////////////////////////// var <T> Vec2T<T>.xy get() = Vec2T(x, y); set(v) { x = v.x; y = v.y } var <T> Vec2T<T>.yx get() = Vec2T(y, x); set(v) { x = v.y; y = v.x } var <T> Vec2T<T>.xx get() = Vec2T(x, y); set(v) { x = v.x; y = v.y } var <T> Vec2T<T>.yy get() = Vec2T(y, x); set(v) { x = v.y; y = v.x } /////////////////////////////////////////////////////////////////////////// // Vec3 /////////////////////////////////////////////////////////////////////////// var <T> Vec3T<T>.xy get() = Vec2T(x, y); set(v) { x = v.x; y = v.y } var <T> Vec3T<T>.yx get() = Vec2T(y, x); set(v) { x = v.y; y = v.x } var <T> Vec3T<T>.xx get() = Vec2T(x, y); set(v) { x = v.x; y = v.y } var <T> Vec3T<T>.yy get() = Vec2T(y, x); set(v) { x = v.y; y = v.x } var <T> Vec3T<T>.xyz get() = Vec3T(x, y, z); set(v) { x = v.x; y = v.y; z = v.z } var <T> Vec3T<T>.xzy get() = Vec3T(x, z, y); set(v) { x = v.x; y = v.z; z = v.y } var <T> Vec3T<T>.yxz get() = Vec3T(y, x, z); set(v) { x = v.y; y = v.x; z = v.z } var <T> Vec3T<T>.yzx get() = Vec3T(y, z, x); set(v) { x = v.y; y = v.z; z = v.x } var <T> Vec3T<T>.zxy get() = Vec3T(z, x, y); set(v) { x = v.z; y = v.x; z = v.y } var <T> Vec3T<T>.zyx get() = Vec3T(z, y, x); set(v) { x = v.z; y = v.y; z = v.x } var <T> Vec3T<T>.xxy get() = Vec3T(x, x, y); set(v) { x = v.x; y = v.x; z = v.y } var <T> Vec3T<T>.xxz get() = Vec3T(x, x, z); set(v) { x = v.x; y = v.x; z = v.z } var <T> Vec3T<T>.yyx get() = Vec3T(y, y, x); set(v) { x = v.y; y = v.y; z = v.x } var <T> Vec3T<T>.yyz get() = Vec3T(y, y, z); set(v) { x = v.y; y = v.y; z = v.z } var <T> Vec3T<T>.zzx get() = Vec3T(z, z, x); set(v) { x = v.z; y = v.z; z = v.x } var <T> Vec3T<T>.zzy get() = Vec3T(z, z, y); set(v) { x = v.z; y = v.z; z = v.y } var <T> Vec3T<T>.xxx get() = Vec3T(x, x, x); set(v) { x = v.x; y = v.x; z = v.x } var <T> Vec3T<T>.yyy get() = Vec3T(y, y, y); set(v) { x = v.y; y = v.y; z = v.y } var <T> Vec3T<T>.zzz get() = Vec3T(z, z, z); set(v) { x = v.z; y = v.z; z = v.z } /////////////////////////////////////////////////////////////////////////// // Vec4 /////////////////////////////////////////////////////////////////////////// var <T> Vec4T<T>.xy get() = Vec2T(x, y); set(v) { x = v.x; y = v.y } var <T> Vec4T<T>.yx get() = Vec2T(y, x); set(v) { x = v.y; y = v.x } var <T> Vec4T<T>.xx get() = Vec2T(x, y); set(v) { x = v.x; y = v.y } var <T> Vec4T<T>.yy get() = Vec2T(y, x); set(v) { x = v.y; y = v.x } var <T> Vec4T<T>.xyz get() = Vec3T(x, y, z); set(v) { x = v.x; y = v.y; z = v.z } var <T> Vec4T<T>.xzy get() = Vec3T(x, z, y); set(v) { x = v.x; y = v.z; z = v.y } var <T> Vec4T<T>.yxz get() = Vec3T(y, x, z); set(v) { x = v.y; y = v.x; z = v.z } var <T> Vec4T<T>.yzx get() = Vec3T(y, z, x); set(v) { x = v.y; y = v.z; z = v.x } var <T> Vec4T<T>.zxy get() = Vec3T(z, x, y); set(v) { x = v.z; y = v.x; z = v.y } var <T> Vec4T<T>.zyx get() = Vec3T(z, y, x); set(v) { x = v.z; y = v.y; z = v.x } var <T> Vec4T<T>.xxy get() = Vec3T(x, x, y); set(v) { x = v.x; y = v.x; z = v.y } var <T> Vec4T<T>.xxz get() = Vec3T(x, x, z); set(v) { x = v.x; y = v.x; z = v.z } var <T> Vec4T<T>.yyx get() = Vec3T(y, y, x); set(v) { x = v.y; y = v.y; z = v.x } var <T> Vec4T<T>.yyz get() = Vec3T(y, y, z); set(v) { x = v.y; y = v.y; z = v.z } var <T> Vec4T<T>.zzx get() = Vec3T(z, z, x); set(v) { x = v.z; y = v.z; z = v.x } var <T> Vec4T<T>.zzy get() = Vec3T(z, z, y); set(v) { x = v.z; y = v.z; z = v.y } var <T> Vec4T<T>.xxx get() = Vec3T(x, x, x); set(v) { x = v.x; y = v.x; z = v.x } var <T> Vec4T<T>.yyy get() = Vec3T(y, y, y); set(v) { x = v.y; y = v.y; z = v.y } var <T> Vec4T<T>.zzz get() = Vec3T(z, z, z); set(v) { x = v.z; y = v.z; z = v.z } var <T> Vec4T<T>.xxxx get() = Vec4T(x, x, x, x); set(v) { x = v.x; y = v.x; z = v.x; w = v.x } var <T> Vec4T<T>.xxxy get() = Vec4T(x, x, x, y); set(v) { x = v.x; y = v.x; z = v.x; w = v.y } var <T> Vec4T<T>.xxxz get() = Vec4T(x, x, x, z); set(v) { x = v.x; y = v.x; z = v.x; w = v.z } var <T> Vec4T<T>.xxxw get() = Vec4T(x, x, x, w); set(v) { x = v.x; y = v.x; z = v.x; w = v.w } var <T> Vec4T<T>.xxyx get() = Vec4T(x, x, y, x); set(v) { x = v.x; y = v.x; z = v.y; w = v.x } var <T> Vec4T<T>.xxyy get() = Vec4T(x, x, y, y); set(v) { x = v.x; y = v.x; z = v.y; w = v.y } var <T> Vec4T<T>.xxyz get() = Vec4T(x, x, y, z); set(v) { x = v.x; y = v.x; z = v.y; w = v.z } var <T> Vec4T<T>.xxyw get() = Vec4T(x, x, y, w); set(v) { x = v.x; y = v.x; z = v.y; w = v.w } var <T> Vec4T<T>.xxzx get() = Vec4T(x, x, z, x); set(v) { x = v.x; y = v.x; z = v.z; w = v.x } var <T> Vec4T<T>.xxzy get() = Vec4T(x, x, z, y); set(v) { x = v.x; y = v.x; z = v.z; w = v.y } var <T> Vec4T<T>.xxzz get() = Vec4T(x, x, z, z); set(v) { x = v.x; y = v.x; z = v.z; w = v.z } var <T> Vec4T<T>.xxzw get() = Vec4T(x, x, z, w); set(v) { x = v.x; y = v.x; z = v.z; w = v.w } var <T> Vec4T<T>.xxwx get() = Vec4T(x, x, w, x); set(v) { x = v.x; y = v.x; z = v.w; w = v.x } var <T> Vec4T<T>.xxwy get() = Vec4T(x, x, w, y); set(v) { x = v.x; y = v.x; z = v.w; w = v.y } var <T> Vec4T<T>.xxwz get() = Vec4T(x, x, w, z); set(v) { x = v.x; y = v.x; z = v.w; w = v.z } var <T> Vec4T<T>.xxww get() = Vec4T(x, x, w, w); set(v) { x = v.x; y = v.x; z = v.w; w = v.w } var <T> Vec4T<T>.xyxx get() = Vec4T(x, y, x, x); set(v) { x = v.x; y = v.y; z = v.x; w = v.x } var <T> Vec4T<T>.xyxy get() = Vec4T(x, y, x, y); set(v) { x = v.x; y = v.y; z = v.x; w = v.y } var <T> Vec4T<T>.xyxz get() = Vec4T(x, y, x, z); set(v) { x = v.x; y = v.y; z = v.x; w = v.z } var <T> Vec4T<T>.xyxw get() = Vec4T(x, y, x, w); set(v) { x = v.x; y = v.y; z = v.x; w = v.w } var <T> Vec4T<T>.xyyx get() = Vec4T(x, y, y, x); set(v) { x = v.x; y = v.y; z = v.y; w = v.x } var <T> Vec4T<T>.xyyy get() = Vec4T(x, y, y, y); set(v) { x = v.x; y = v.y; z = v.y; w = v.y } var <T> Vec4T<T>.xyyz get() = Vec4T(x, y, y, z); set(v) { x = v.x; y = v.y; z = v.y; w = v.z } var <T> Vec4T<T>.xyyw get() = Vec4T(x, y, y, w); set(v) { x = v.x; y = v.y; z = v.y; w = v.w } var <T> Vec4T<T>.xyzx get() = Vec4T(x, y, z, x); set(v) { x = v.x; y = v.y; z = v.z; w = v.x } var <T> Vec4T<T>.xyzy get() = Vec4T(x, y, z, y); set(v) { x = v.x; y = v.y; z = v.z; w = v.y } var <T> Vec4T<T>.xyzz get() = Vec4T(x, y, z, z); set(v) { x = v.x; y = v.y; z = v.z; w = v.z } var <T> Vec4T<T>.xyzw get() = Vec4T(x, y, z, w); set(v) { x = v.x; y = v.y; z = v.z; w = v.w } var <T> Vec4T<T>.xywx get() = Vec4T(x, y, w, x); set(v) { x = v.x; y = v.y; z = v.w; w = v.x } var <T> Vec4T<T>.xywy get() = Vec4T(x, y, w, y); set(v) { x = v.x; y = v.y; z = v.w; w = v.y } var <T> Vec4T<T>.xywz get() = Vec4T(x, y, w, z); set(v) { x = v.x; y = v.y; z = v.w; w = v.z } var <T> Vec4T<T>.xyww get() = Vec4T(x, y, w, w); set(v) { x = v.x; y = v.y; z = v.w; w = v.w } var <T> Vec4T<T>.xzxx get() = Vec4T(x, z, x, x); set(v) { x = v.x; y = v.z; z = v.x; w = v.x } var <T> Vec4T<T>.xzxy get() = Vec4T(x, z, x, y); set(v) { x = v.x; y = v.z; z = v.x; w = v.y } var <T> Vec4T<T>.xzxz get() = Vec4T(x, z, x, z); set(v) { x = v.x; y = v.z; z = v.x; w = v.z } var <T> Vec4T<T>.xzxw get() = Vec4T(x, z, x, w); set(v) { x = v.x; y = v.z; z = v.x; w = v.w } var <T> Vec4T<T>.xzyx get() = Vec4T(x, z, y, x); set(v) { x = v.x; y = v.z; z = v.y; w = v.x } var <T> Vec4T<T>.xzyy get() = Vec4T(x, z, y, y); set(v) { x = v.x; y = v.z; z = v.y; w = v.y } var <T> Vec4T<T>.xzyz get() = Vec4T(x, z, y, z); set(v) { x = v.x; y = v.z; z = v.y; w = v.z } var <T> Vec4T<T>.xzyw get() = Vec4T(x, z, y, w); set(v) { x = v.x; y = v.z; z = v.y; w = v.w } var <T> Vec4T<T>.xzzx get() = Vec4T(x, z, z, x); set(v) { x = v.x; y = v.z; z = v.z; w = v.x } var <T> Vec4T<T>.xzzy get() = Vec4T(x, z, z, y); set(v) { x = v.x; y = v.z; z = v.z; w = v.y } var <T> Vec4T<T>.xzzz get() = Vec4T(x, z, z, z); set(v) { x = v.x; y = v.z; z = v.z; w = v.z } var <T> Vec4T<T>.xzzw get() = Vec4T(x, z, z, w); set(v) { x = v.x; y = v.z; z = v.z; w = v.w } var <T> Vec4T<T>.xzwx get() = Vec4T(x, z, w, x); set(v) { x = v.x; y = v.z; z = v.w; w = v.x } var <T> Vec4T<T>.xzwy get() = Vec4T(x, z, w, y); set(v) { x = v.x; y = v.z; z = v.w; w = v.y } var <T> Vec4T<T>.xzwz get() = Vec4T(x, z, w, z); set(v) { x = v.x; y = v.z; z = v.w; w = v.z } var <T> Vec4T<T>.xzww get() = Vec4T(x, z, w, w); set(v) { x = v.x; y = v.z; z = v.w; w = v.w } var <T> Vec4T<T>.xwxx get() = Vec4T(x, w, x, x); set(v) { x = v.x; y = v.w; z = v.x; w = v.x } var <T> Vec4T<T>.xwxy get() = Vec4T(x, w, x, y); set(v) { x = v.x; y = v.w; z = v.x; w = v.y } var <T> Vec4T<T>.xwxz get() = Vec4T(x, w, x, z); set(v) { x = v.x; y = v.w; z = v.x; w = v.z } var <T> Vec4T<T>.xwxw get() = Vec4T(x, w, x, w); set(v) { x = v.x; y = v.w; z = v.x; w = v.w } var <T> Vec4T<T>.xwyx get() = Vec4T(x, w, y, x); set(v) { x = v.x; y = v.w; z = v.y; w = v.x } var <T> Vec4T<T>.xwyy get() = Vec4T(x, w, y, y); set(v) { x = v.x; y = v.w; z = v.y; w = v.y } var <T> Vec4T<T>.xwyz get() = Vec4T(x, w, y, z); set(v) { x = v.x; y = v.w; z = v.y; w = v.z } var <T> Vec4T<T>.xwyw get() = Vec4T(x, w, y, w); set(v) { x = v.x; y = v.w; z = v.y; w = v.w } var <T> Vec4T<T>.xwzx get() = Vec4T(x, w, z, x); set(v) { x = v.x; y = v.w; z = v.z; w = v.x } var <T> Vec4T<T>.xwzy get() = Vec4T(x, w, z, y); set(v) { x = v.x; y = v.w; z = v.z; w = v.y } var <T> Vec4T<T>.xwzz get() = Vec4T(x, w, z, z); set(v) { x = v.x; y = v.w; z = v.z; w = v.z } var <T> Vec4T<T>.xwzw get() = Vec4T(x, w, z, w); set(v) { x = v.x; y = v.w; z = v.z; w = v.w } var <T> Vec4T<T>.xwwx get() = Vec4T(x, w, w, x); set(v) { x = v.x; y = v.w; z = v.w; w = v.x } var <T> Vec4T<T>.xwwy get() = Vec4T(x, w, w, y); set(v) { x = v.x; y = v.w; z = v.w; w = v.y } var <T> Vec4T<T>.xwwz get() = Vec4T(x, w, w, z); set(v) { x = v.x; y = v.w; z = v.w; w = v.z } var <T> Vec4T<T>.xwww get() = Vec4T(x, w, w, w); set(v) { x = v.x; y = v.w; z = v.w; w = v.w } var <T> Vec4T<T>.yxxx get() = Vec4T(y, x, x, x); set(v) { x = v.y; y = v.x; z = v.x; w = v.x } var <T> Vec4T<T>.yxxy get() = Vec4T(y, x, x, y); set(v) { x = v.y; y = v.x; z = v.x; w = v.y } var <T> Vec4T<T>.yxxz get() = Vec4T(y, x, x, z); set(v) { x = v.y; y = v.x; z = v.x; w = v.z } var <T> Vec4T<T>.yxxw get() = Vec4T(y, x, x, w); set(v) { x = v.y; y = v.x; z = v.x; w = v.w } var <T> Vec4T<T>.yxyx get() = Vec4T(y, x, y, x); set(v) { x = v.y; y = v.x; z = v.y; w = v.x } var <T> Vec4T<T>.yxyy get() = Vec4T(y, x, y, y); set(v) { x = v.y; y = v.x; z = v.y; w = v.y } var <T> Vec4T<T>.yxyz get() = Vec4T(y, x, y, z); set(v) { x = v.y; y = v.x; z = v.y; w = v.z } var <T> Vec4T<T>.yxyw get() = Vec4T(y, x, y, w); set(v) { x = v.y; y = v.x; z = v.y; w = v.w } var <T> Vec4T<T>.yxzx get() = Vec4T(y, x, z, x); set(v) { x = v.y; y = v.x; z = v.z; w = v.x } var <T> Vec4T<T>.yxzy get() = Vec4T(y, x, z, y); set(v) { x = v.y; y = v.x; z = v.z; w = v.y } var <T> Vec4T<T>.yxzz get() = Vec4T(y, x, z, z); set(v) { x = v.y; y = v.x; z = v.z; w = v.z } var <T> Vec4T<T>.yxzw get() = Vec4T(y, x, z, w); set(v) { x = v.y; y = v.x; z = v.z; w = v.w } var <T> Vec4T<T>.yxwx get() = Vec4T(y, x, w, x); set(v) { x = v.y; y = v.x; z = v.w; w = v.x } var <T> Vec4T<T>.yxwy get() = Vec4T(y, x, w, y); set(v) { x = v.y; y = v.x; z = v.w; w = v.y } var <T> Vec4T<T>.yxwz get() = Vec4T(y, x, w, z); set(v) { x = v.y; y = v.x; z = v.w; w = v.z } var <T> Vec4T<T>.yxww get() = Vec4T(y, x, w, w); set(v) { x = v.y; y = v.x; z = v.w; w = v.w } var <T> Vec4T<T>.yyxx get() = Vec4T(y, y, x, x); set(v) { x = v.y; y = v.y; z = v.x; w = v.x } var <T> Vec4T<T>.yyxy get() = Vec4T(y, y, x, y); set(v) { x = v.y; y = v.y; z = v.x; w = v.y } var <T> Vec4T<T>.yyxz get() = Vec4T(y, y, x, z); set(v) { x = v.y; y = v.y; z = v.x; w = v.z } var <T> Vec4T<T>.yyxw get() = Vec4T(y, y, x, w); set(v) { x = v.y; y = v.y; z = v.x; w = v.w } var <T> Vec4T<T>.yyyx get() = Vec4T(y, y, y, x); set(v) { x = v.y; y = v.y; z = v.y; w = v.x } var <T> Vec4T<T>.yyyy get() = Vec4T(y, y, y, y); set(v) { x = v.y; y = v.y; z = v.y; w = v.y } var <T> Vec4T<T>.yyyz get() = Vec4T(y, y, y, z); set(v) { x = v.y; y = v.y; z = v.y; w = v.z } var <T> Vec4T<T>.yyyw get() = Vec4T(y, y, y, w); set(v) { x = v.y; y = v.y; z = v.y; w = v.w } var <T> Vec4T<T>.yyzx get() = Vec4T(y, y, z, x); set(v) { x = v.y; y = v.y; z = v.z; w = v.x } var <T> Vec4T<T>.yyzy get() = Vec4T(y, y, z, y); set(v) { x = v.y; y = v.y; z = v.z; w = v.y } var <T> Vec4T<T>.yyzz get() = Vec4T(y, y, z, z); set(v) { x = v.y; y = v.y; z = v.z; w = v.z } var <T> Vec4T<T>.yyzw get() = Vec4T(y, y, z, w); set(v) { x = v.y; y = v.y; z = v.z; w = v.w } var <T> Vec4T<T>.yywx get() = Vec4T(y, y, w, x); set(v) { x = v.y; y = v.y; z = v.w; w = v.x } var <T> Vec4T<T>.yywy get() = Vec4T(y, y, w, y); set(v) { x = v.y; y = v.y; z = v.w; w = v.y } var <T> Vec4T<T>.yywz get() = Vec4T(y, y, w, z); set(v) { x = v.y; y = v.y; z = v.w; w = v.z } var <T> Vec4T<T>.yyww get() = Vec4T(y, y, w, w); set(v) { x = v.y; y = v.y; z = v.w; w = v.w } var <T> Vec4T<T>.yzxx get() = Vec4T(y, z, x, x); set(v) { x = v.y; y = v.z; z = v.x; w = v.x } var <T> Vec4T<T>.yzxy get() = Vec4T(y, z, x, y); set(v) { x = v.y; y = v.z; z = v.x; w = v.y } var <T> Vec4T<T>.yzxz get() = Vec4T(y, z, x, z); set(v) { x = v.y; y = v.z; z = v.x; w = v.z } var <T> Vec4T<T>.yzxw get() = Vec4T(y, z, x, w); set(v) { x = v.y; y = v.z; z = v.x; w = v.w } var <T> Vec4T<T>.yzyx get() = Vec4T(y, z, y, x); set(v) { x = v.y; y = v.z; z = v.y; w = v.x } var <T> Vec4T<T>.yzyy get() = Vec4T(y, z, y, y); set(v) { x = v.y; y = v.z; z = v.y; w = v.y } var <T> Vec4T<T>.yzyz get() = Vec4T(y, z, y, z); set(v) { x = v.y; y = v.z; z = v.y; w = v.z } var <T> Vec4T<T>.yzyw get() = Vec4T(y, z, y, w); set(v) { x = v.y; y = v.z; z = v.y; w = v.w } var <T> Vec4T<T>.yzzx get() = Vec4T(y, z, z, x); set(v) { x = v.y; y = v.z; z = v.z; w = v.x } var <T> Vec4T<T>.yzzy get() = Vec4T(y, z, z, y); set(v) { x = v.y; y = v.z; z = v.z; w = v.y } var <T> Vec4T<T>.yzzz get() = Vec4T(y, z, z, z); set(v) { x = v.y; y = v.z; z = v.z; w = v.z } var <T> Vec4T<T>.yzzw get() = Vec4T(y, z, z, w); set(v) { x = v.y; y = v.z; z = v.z; w = v.w } var <T> Vec4T<T>.yzwx get() = Vec4T(y, z, w, x); set(v) { x = v.y; y = v.z; z = v.w; w = v.x } var <T> Vec4T<T>.yzwy get() = Vec4T(y, z, w, y); set(v) { x = v.y; y = v.z; z = v.w; w = v.y } var <T> Vec4T<T>.yzwz get() = Vec4T(y, z, w, z); set(v) { x = v.y; y = v.z; z = v.w; w = v.z } var <T> Vec4T<T>.yzww get() = Vec4T(y, z, w, w); set(v) { x = v.y; y = v.z; z = v.w; w = v.w } var <T> Vec4T<T>.ywxx get() = Vec4T(y, w, x, x); set(v) { x = v.y; y = v.w; z = v.x; w = v.x } var <T> Vec4T<T>.ywxy get() = Vec4T(y, w, x, y); set(v) { x = v.y; y = v.w; z = v.x; w = v.y } var <T> Vec4T<T>.ywxz get() = Vec4T(y, w, x, z); set(v) { x = v.y; y = v.w; z = v.x; w = v.z } var <T> Vec4T<T>.ywxw get() = Vec4T(y, w, x, w); set(v) { x = v.y; y = v.w; z = v.x; w = v.w } var <T> Vec4T<T>.ywyx get() = Vec4T(y, w, y, x); set(v) { x = v.y; y = v.w; z = v.y; w = v.x } var <T> Vec4T<T>.ywyy get() = Vec4T(y, w, y, y); set(v) { x = v.y; y = v.w; z = v.y; w = v.y } var <T> Vec4T<T>.ywyz get() = Vec4T(y, w, y, z); set(v) { x = v.y; y = v.w; z = v.y; w = v.z } var <T> Vec4T<T>.ywyw get() = Vec4T(y, w, y, w); set(v) { x = v.y; y = v.w; z = v.y; w = v.w } var <T> Vec4T<T>.ywzx get() = Vec4T(y, w, z, x); set(v) { x = v.y; y = v.w; z = v.z; w = v.x } var <T> Vec4T<T>.ywzy get() = Vec4T(y, w, z, y); set(v) { x = v.y; y = v.w; z = v.z; w = v.y } var <T> Vec4T<T>.ywzz get() = Vec4T(y, w, z, z); set(v) { x = v.y; y = v.w; z = v.z; w = v.z } var <T> Vec4T<T>.ywzw get() = Vec4T(y, w, z, w); set(v) { x = v.y; y = v.w; z = v.z; w = v.w } var <T> Vec4T<T>.ywwx get() = Vec4T(y, w, w, x); set(v) { x = v.y; y = v.w; z = v.w; w = v.x } var <T> Vec4T<T>.ywwy get() = Vec4T(y, w, w, y); set(v) { x = v.y; y = v.w; z = v.w; w = v.y } var <T> Vec4T<T>.ywwz get() = Vec4T(y, w, w, z); set(v) { x = v.y; y = v.w; z = v.w; w = v.z } var <T> Vec4T<T>.ywww get() = Vec4T(y, w, w, w); set(v) { x = v.y; y = v.w; z = v.w; w = v.w } var <T> Vec4T<T>.zxxx get() = Vec4T(z, x, x, x); set(v) { x = v.z; y = v.x; z = v.x; w = v.x } var <T> Vec4T<T>.zxxy get() = Vec4T(z, x, x, y); set(v) { x = v.z; y = v.x; z = v.x; w = v.y } var <T> Vec4T<T>.zxxz get() = Vec4T(z, x, x, z); set(v) { x = v.z; y = v.x; z = v.x; w = v.z } var <T> Vec4T<T>.zxxw get() = Vec4T(z, x, x, w); set(v) { x = v.z; y = v.x; z = v.x; w = v.w } var <T> Vec4T<T>.zxyx get() = Vec4T(z, x, y, x); set(v) { x = v.z; y = v.x; z = v.y; w = v.x } var <T> Vec4T<T>.zxyy get() = Vec4T(z, x, y, y); set(v) { x = v.z; y = v.x; z = v.y; w = v.y } var <T> Vec4T<T>.zxyz get() = Vec4T(z, x, y, z); set(v) { x = v.z; y = v.x; z = v.y; w = v.z } var <T> Vec4T<T>.zxyw get() = Vec4T(z, x, y, w); set(v) { x = v.z; y = v.x; z = v.y; w = v.w } var <T> Vec4T<T>.zxzx get() = Vec4T(z, x, z, x); set(v) { x = v.z; y = v.x; z = v.z; w = v.x } var <T> Vec4T<T>.zxzy get() = Vec4T(z, x, z, y); set(v) { x = v.z; y = v.x; z = v.z; w = v.y } var <T> Vec4T<T>.zxzz get() = Vec4T(z, x, z, z); set(v) { x = v.z; y = v.x; z = v.z; w = v.z } var <T> Vec4T<T>.zxzw get() = Vec4T(z, x, z, w); set(v) { x = v.z; y = v.x; z = v.z; w = v.w } var <T> Vec4T<T>.zxwx get() = Vec4T(z, x, w, x); set(v) { x = v.z; y = v.x; z = v.w; w = v.x } var <T> Vec4T<T>.zxwy get() = Vec4T(z, x, w, y); set(v) { x = v.z; y = v.x; z = v.w; w = v.y } var <T> Vec4T<T>.zxwz get() = Vec4T(z, x, w, z); set(v) { x = v.z; y = v.x; z = v.w; w = v.z } var <T> Vec4T<T>.zxww get() = Vec4T(z, x, w, w); set(v) { x = v.z; y = v.x; z = v.w; w = v.w } var <T> Vec4T<T>.zyxx get() = Vec4T(z, y, x, x); set(v) { x = v.z; y = v.y; z = v.x; w = v.x } var <T> Vec4T<T>.zyxy get() = Vec4T(z, y, x, y); set(v) { x = v.z; y = v.y; z = v.x; w = v.y } var <T> Vec4T<T>.zyxz get() = Vec4T(z, y, x, z); set(v) { x = v.z; y = v.y; z = v.x; w = v.z } var <T> Vec4T<T>.zyxw get() = Vec4T(z, y, x, w); set(v) { x = v.z; y = v.y; z = v.x; w = v.w } var <T> Vec4T<T>.zyyx get() = Vec4T(z, y, y, x); set(v) { x = v.z; y = v.y; z = v.y; w = v.x } var <T> Vec4T<T>.zyyy get() = Vec4T(z, y, y, y); set(v) { x = v.z; y = v.y; z = v.y; w = v.y } var <T> Vec4T<T>.zyyz get() = Vec4T(z, y, y, z); set(v) { x = v.z; y = v.y; z = v.y; w = v.z } var <T> Vec4T<T>.zyyw get() = Vec4T(z, y, y, w); set(v) { x = v.z; y = v.y; z = v.y; w = v.w } var <T> Vec4T<T>.zyzx get() = Vec4T(z, y, z, x); set(v) { x = v.z; y = v.y; z = v.z; w = v.x } var <T> Vec4T<T>.zyzy get() = Vec4T(z, y, z, y); set(v) { x = v.z; y = v.y; z = v.z; w = v.y } var <T> Vec4T<T>.zyzz get() = Vec4T(z, y, z, z); set(v) { x = v.z; y = v.y; z = v.z; w = v.z } var <T> Vec4T<T>.zyzw get() = Vec4T(z, y, z, w); set(v) { x = v.z; y = v.y; z = v.z; w = v.w } var <T> Vec4T<T>.zywx get() = Vec4T(z, y, w, x); set(v) { x = v.z; y = v.y; z = v.w; w = v.x } var <T> Vec4T<T>.zywy get() = Vec4T(z, y, w, y); set(v) { x = v.z; y = v.y; z = v.w; w = v.y } var <T> Vec4T<T>.zywz get() = Vec4T(z, y, w, z); set(v) { x = v.z; y = v.y; z = v.w; w = v.z } var <T> Vec4T<T>.zyww get() = Vec4T(z, y, w, w); set(v) { x = v.z; y = v.y; z = v.w; w = v.w } var <T> Vec4T<T>.zzxx get() = Vec4T(z, z, x, x); set(v) { x = v.z; y = v.z; z = v.x; w = v.x } var <T> Vec4T<T>.zzxy get() = Vec4T(z, z, x, y); set(v) { x = v.z; y = v.z; z = v.x; w = v.y } var <T> Vec4T<T>.zzxz get() = Vec4T(z, z, x, z); set(v) { x = v.z; y = v.z; z = v.x; w = v.z } var <T> Vec4T<T>.zzxw get() = Vec4T(z, z, x, w); set(v) { x = v.z; y = v.z; z = v.x; w = v.w } var <T> Vec4T<T>.zzyx get() = Vec4T(z, z, y, x); set(v) { x = v.z; y = v.z; z = v.y; w = v.x } var <T> Vec4T<T>.zzyy get() = Vec4T(z, z, y, y); set(v) { x = v.z; y = v.z; z = v.y; w = v.y } var <T> Vec4T<T>.zzyz get() = Vec4T(z, z, y, z); set(v) { x = v.z; y = v.z; z = v.y; w = v.z } var <T> Vec4T<T>.zzyw get() = Vec4T(z, z, y, w); set(v) { x = v.z; y = v.z; z = v.y; w = v.w } var <T> Vec4T<T>.zzzx get() = Vec4T(z, z, z, x); set(v) { x = v.z; y = v.z; z = v.z; w = v.x } var <T> Vec4T<T>.zzzy get() = Vec4T(z, z, z, y); set(v) { x = v.z; y = v.z; z = v.z; w = v.y } var <T> Vec4T<T>.zzzz get() = Vec4T(z, z, z, z); set(v) { x = v.z; y = v.z; z = v.z; w = v.z } var <T> Vec4T<T>.zzzw get() = Vec4T(z, z, z, w); set(v) { x = v.z; y = v.z; z = v.z; w = v.w } var <T> Vec4T<T>.zzwx get() = Vec4T(z, z, w, x); set(v) { x = v.z; y = v.z; z = v.w; w = v.x } var <T> Vec4T<T>.zzwy get() = Vec4T(z, z, w, y); set(v) { x = v.z; y = v.z; z = v.w; w = v.y } var <T> Vec4T<T>.zzwz get() = Vec4T(z, z, w, z); set(v) { x = v.z; y = v.z; z = v.w; w = v.z } var <T> Vec4T<T>.zzww get() = Vec4T(z, z, w, w); set(v) { x = v.z; y = v.z; z = v.w; w = v.w } var <T> Vec4T<T>.zwxx get() = Vec4T(z, w, x, x); set(v) { x = v.z; y = v.w; z = v.x; w = v.x } var <T> Vec4T<T>.zwxy get() = Vec4T(z, w, x, y); set(v) { x = v.z; y = v.w; z = v.x; w = v.y } var <T> Vec4T<T>.zwxz get() = Vec4T(z, w, x, z); set(v) { x = v.z; y = v.w; z = v.x; w = v.z } var <T> Vec4T<T>.zwxw get() = Vec4T(z, w, x, w); set(v) { x = v.z; y = v.w; z = v.x; w = v.w } var <T> Vec4T<T>.zwyx get() = Vec4T(z, w, y, x); set(v) { x = v.z; y = v.w; z = v.y; w = v.x } var <T> Vec4T<T>.zwyy get() = Vec4T(z, w, y, y); set(v) { x = v.z; y = v.w; z = v.y; w = v.y } var <T> Vec4T<T>.zwyz get() = Vec4T(z, w, y, z); set(v) { x = v.z; y = v.w; z = v.y; w = v.z } var <T> Vec4T<T>.zwyw get() = Vec4T(z, w, y, w); set(v) { x = v.z; y = v.w; z = v.y; w = v.w } var <T> Vec4T<T>.zwzx get() = Vec4T(z, w, z, x); set(v) { x = v.z; y = v.w; z = v.z; w = v.x } var <T> Vec4T<T>.zwzy get() = Vec4T(z, w, z, y); set(v) { x = v.z; y = v.w; z = v.z; w = v.y } var <T> Vec4T<T>.zwzz get() = Vec4T(z, w, z, z); set(v) { x = v.z; y = v.w; z = v.z; w = v.z } var <T> Vec4T<T>.zwzw get() = Vec4T(z, w, z, w); set(v) { x = v.z; y = v.w; z = v.z; w = v.w } var <T> Vec4T<T>.zwwx get() = Vec4T(z, w, w, x); set(v) { x = v.z; y = v.w; z = v.w; w = v.x } var <T> Vec4T<T>.zwwy get() = Vec4T(z, w, w, y); set(v) { x = v.z; y = v.w; z = v.w; w = v.y } var <T> Vec4T<T>.zwwz get() = Vec4T(z, w, w, z); set(v) { x = v.z; y = v.w; z = v.w; w = v.z } var <T> Vec4T<T>.zwww get() = Vec4T(z, w, w, w); set(v) { x = v.z; y = v.w; z = v.w; w = v.w } var <T> Vec4T<T>.wxxx get() = Vec4T(w, x, x, x); set(v) { x = v.w; y = v.x; z = v.x; w = v.x } var <T> Vec4T<T>.wxxy get() = Vec4T(w, x, x, y); set(v) { x = v.w; y = v.x; z = v.x; w = v.y } var <T> Vec4T<T>.wxxz get() = Vec4T(w, x, x, z); set(v) { x = v.w; y = v.x; z = v.x; w = v.z } var <T> Vec4T<T>.wxxw get() = Vec4T(w, x, x, w); set(v) { x = v.w; y = v.x; z = v.x; w = v.w } var <T> Vec4T<T>.wxyx get() = Vec4T(w, x, y, x); set(v) { x = v.w; y = v.x; z = v.y; w = v.x } var <T> Vec4T<T>.wxyy get() = Vec4T(w, x, y, y); set(v) { x = v.w; y = v.x; z = v.y; w = v.y } var <T> Vec4T<T>.wxyz get() = Vec4T(w, x, y, z); set(v) { x = v.w; y = v.x; z = v.y; w = v.z } var <T> Vec4T<T>.wxyw get() = Vec4T(w, x, y, w); set(v) { x = v.w; y = v.x; z = v.y; w = v.w } var <T> Vec4T<T>.wxzx get() = Vec4T(w, x, z, x); set(v) { x = v.w; y = v.x; z = v.z; w = v.x } var <T> Vec4T<T>.wxzy get() = Vec4T(w, x, z, y); set(v) { x = v.w; y = v.x; z = v.z; w = v.y } var <T> Vec4T<T>.wxzz get() = Vec4T(w, x, z, z); set(v) { x = v.w; y = v.x; z = v.z; w = v.z } var <T> Vec4T<T>.wxzw get() = Vec4T(w, x, z, w); set(v) { x = v.w; y = v.x; z = v.z; w = v.w } var <T> Vec4T<T>.wxwx get() = Vec4T(w, x, w, x); set(v) { x = v.w; y = v.x; z = v.w; w = v.x } var <T> Vec4T<T>.wxwy get() = Vec4T(w, x, w, y); set(v) { x = v.w; y = v.x; z = v.w; w = v.y } var <T> Vec4T<T>.wxwz get() = Vec4T(w, x, w, z); set(v) { x = v.w; y = v.x; z = v.w; w = v.z } var <T> Vec4T<T>.wxww get() = Vec4T(w, x, w, w); set(v) { x = v.w; y = v.x; z = v.w; w = v.w } var <T> Vec4T<T>.wyxx get() = Vec4T(w, y, x, x); set(v) { x = v.w; y = v.y; z = v.x; w = v.x } var <T> Vec4T<T>.wyxy get() = Vec4T(w, y, x, y); set(v) { x = v.w; y = v.y; z = v.x; w = v.y } var <T> Vec4T<T>.wyxz get() = Vec4T(w, y, x, z); set(v) { x = v.w; y = v.y; z = v.x; w = v.z } var <T> Vec4T<T>.wyxw get() = Vec4T(w, y, x, w); set(v) { x = v.w; y = v.y; z = v.x; w = v.w } var <T> Vec4T<T>.wyyx get() = Vec4T(w, y, y, x); set(v) { x = v.w; y = v.y; z = v.y; w = v.x } var <T> Vec4T<T>.wyyy get() = Vec4T(w, y, y, y); set(v) { x = v.w; y = v.y; z = v.y; w = v.y } var <T> Vec4T<T>.wyyz get() = Vec4T(w, y, y, z); set(v) { x = v.w; y = v.y; z = v.y; w = v.z } var <T> Vec4T<T>.wyyw get() = Vec4T(w, y, y, w); set(v) { x = v.w; y = v.y; z = v.y; w = v.w } var <T> Vec4T<T>.wyzx get() = Vec4T(w, y, z, x); set(v) { x = v.w; y = v.y; z = v.z; w = v.x } var <T> Vec4T<T>.wyzy get() = Vec4T(w, y, z, y); set(v) { x = v.w; y = v.y; z = v.z; w = v.y } var <T> Vec4T<T>.wyzz get() = Vec4T(w, y, z, z); set(v) { x = v.w; y = v.y; z = v.z; w = v.z } var <T> Vec4T<T>.wyzw get() = Vec4T(w, y, z, w); set(v) { x = v.w; y = v.y; z = v.z; w = v.w } var <T> Vec4T<T>.wywx get() = Vec4T(w, y, w, x); set(v) { x = v.w; y = v.y; z = v.w; w = v.x } var <T> Vec4T<T>.wywy get() = Vec4T(w, y, w, y); set(v) { x = v.w; y = v.y; z = v.w; w = v.y } var <T> Vec4T<T>.wywz get() = Vec4T(w, y, w, z); set(v) { x = v.w; y = v.y; z = v.w; w = v.z } var <T> Vec4T<T>.wyww get() = Vec4T(w, y, w, w); set(v) { x = v.w; y = v.y; z = v.w; w = v.w } var <T> Vec4T<T>.wzxx get() = Vec4T(w, z, x, x); set(v) { x = v.w; y = v.z; z = v.x; w = v.x } var <T> Vec4T<T>.wzxy get() = Vec4T(w, z, x, y); set(v) { x = v.w; y = v.z; z = v.x; w = v.y } var <T> Vec4T<T>.wzxz get() = Vec4T(w, z, x, z); set(v) { x = v.w; y = v.z; z = v.x; w = v.z } var <T> Vec4T<T>.wzxw get() = Vec4T(w, z, x, w); set(v) { x = v.w; y = v.z; z = v.x; w = v.w } var <T> Vec4T<T>.wzyx get() = Vec4T(w, z, y, x); set(v) { x = v.w; y = v.z; z = v.y; w = v.x } var <T> Vec4T<T>.wzyy get() = Vec4T(w, z, y, y); set(v) { x = v.w; y = v.z; z = v.y; w = v.y } var <T> Vec4T<T>.wzyz get() = Vec4T(w, z, y, z); set(v) { x = v.w; y = v.z; z = v.y; w = v.z } var <T> Vec4T<T>.wzyw get() = Vec4T(w, z, y, w); set(v) { x = v.w; y = v.z; z = v.y; w = v.w } var <T> Vec4T<T>.wzzx get() = Vec4T(w, z, z, x); set(v) { x = v.w; y = v.z; z = v.z; w = v.x } var <T> Vec4T<T>.wzzy get() = Vec4T(w, z, z, y); set(v) { x = v.w; y = v.z; z = v.z; w = v.y } var <T> Vec4T<T>.wzzz get() = Vec4T(w, z, z, z); set(v) { x = v.w; y = v.z; z = v.z; w = v.z } var <T> Vec4T<T>.wzzw get() = Vec4T(w, z, z, w); set(v) { x = v.w; y = v.z; z = v.z; w = v.w } var <T> Vec4T<T>.wzwx get() = Vec4T(w, z, w, x); set(v) { x = v.w; y = v.z; z = v.w; w = v.x } var <T> Vec4T<T>.wzwy get() = Vec4T(w, z, w, y); set(v) { x = v.w; y = v.z; z = v.w; w = v.y } var <T> Vec4T<T>.wzwz get() = Vec4T(w, z, w, z); set(v) { x = v.w; y = v.z; z = v.w; w = v.z } var <T> Vec4T<T>.wzww get() = Vec4T(w, z, w, w); set(v) { x = v.w; y = v.z; z = v.w; w = v.w } var <T> Vec4T<T>.wwxx get() = Vec4T(w, w, x, x); set(v) { x = v.w; y = v.w; z = v.x; w = v.x } var <T> Vec4T<T>.wwxy get() = Vec4T(w, w, x, y); set(v) { x = v.w; y = v.w; z = v.x; w = v.y } var <T> Vec4T<T>.wwxz get() = Vec4T(w, w, x, z); set(v) { x = v.w; y = v.w; z = v.x; w = v.z } var <T> Vec4T<T>.wwxw get() = Vec4T(w, w, x, w); set(v) { x = v.w; y = v.w; z = v.x; w = v.w } var <T> Vec4T<T>.wwyx get() = Vec4T(w, w, y, x); set(v) { x = v.w; y = v.w; z = v.y; w = v.x } var <T> Vec4T<T>.wwyy get() = Vec4T(w, w, y, y); set(v) { x = v.w; y = v.w; z = v.y; w = v.y } var <T> Vec4T<T>.wwyz get() = Vec4T(w, w, y, z); set(v) { x = v.w; y = v.w; z = v.y; w = v.z } var <T> Vec4T<T>.wwyw get() = Vec4T(w, w, y, w); set(v) { x = v.w; y = v.w; z = v.y; w = v.w } var <T> Vec4T<T>.wwzx get() = Vec4T(w, w, z, x); set(v) { x = v.w; y = v.w; z = v.z; w = v.x } var <T> Vec4T<T>.wwzy get() = Vec4T(w, w, z, y); set(v) { x = v.w; y = v.w; z = v.z; w = v.y } var <T> Vec4T<T>.wwzz get() = Vec4T(w, w, z, z); set(v) { x = v.w; y = v.w; z = v.z; w = v.z } var <T> Vec4T<T>.wwzw get() = Vec4T(w, w, z, w); set(v) { x = v.w; y = v.w; z = v.z; w = v.w } var <T> Vec4T<T>.wwwx get() = Vec4T(w, w, w, x); set(v) { x = v.w; y = v.w; z = v.w; w = v.x } var <T> Vec4T<T>.wwwy get() = Vec4T(w, w, w, y); set(v) { x = v.w; y = v.w; z = v.w; w = v.y } var <T> Vec4T<T>.wwwz get() = Vec4T(w, w, w, z); set(v) { x = v.w; y = v.w; z = v.w; w = v.z } var <T> Vec4T<T>.wwww get() = Vec4T(w, w, w, w); set(v) { x = v.w; y = v.w; z = v.w; w = v.w }
0
Kotlin
0
2
b384f2a430c0f714237e07621a01f094d9f5ee75
28,112
Pumpkin-Engine
Apache License 2.0
core/game/src/test/kotlin/com/ekezet/othello/core/game/ValidMovesKtTest.kt
atomgomba
754,770,216
false
{"Kotlin": 209676}
package com.ekezet.othello.core.game import com.ekezet.othello.core.data.models.Disk import com.ekezet.othello.core.data.models.flip import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue internal class ValidMovesKtTest { private val subject = Disk.Dark private val other = subject.flip() @Test fun `findValidIndices should return something`() { val input1 = arrayOf(subject, other, null) val result1 = findValidIndices(input1, subject) assertEquals(setOf(ValidSegment(0, 2, false)), result1, "Unexpected result1") val input2 = arrayOf(null, subject, other, null) val result2 = findValidIndices(input2, subject) assertEquals(setOf(ValidSegment(1, 3, false)), result2, "Unexpected result2") val input3 = arrayOf(subject, other, other, null, null, other, subject) val result3 = findValidIndices(input3, subject) assertEquals(setOf(ValidSegment(0, 3, false), ValidSegment(4, 6, true)), result3, "Unexpected result3") val input4 = arrayOf(subject, other, other, null, null) val result4 = findValidIndices(input4, subject) assertEquals(setOf(ValidSegment(0, 3, false)), result4, "Unexpected result4") val input5 = arrayOf(null, null, subject, other, other, null) val result5 = findValidIndices(input5, subject) assertEquals(setOf(ValidSegment(2, 5, false)), result5, "Unexpected result5") } @Test fun `findValidIndices should return nothing`() { val input1 = arrayOf(other, other, other, subject) val result1 = findValidIndices(input1, subject) assertTrue(result1.isEmpty(), "Unexpected result1") val input2: Array<Disk?> = arrayOf(null, null, null, null) val result2 = findValidIndices(input2, subject) assertTrue(result2.isEmpty(), "Unexpected result2") val input3 = arrayOf(subject, other, other, subject, null) val result3 = findValidIndices(input3, subject) assertTrue(result3.isEmpty(), "Unexpected result3") val input4 = arrayOf(other, other, other, null, null) val result4 = findValidIndices(input4, subject) assertTrue(result4.isEmpty(), "Unexpected result4") } @Test fun `parts should return correct result`() { val input1 = ValidSegment(0 to 0, 2 to 0, false) val result1 = input1.parts() val expected1 = setOf(1 to 0) assertEquals(expected1, result1, "Unexpected result1") val input2 = ValidSegment(2 to 0, 0 to 0, false) val result2 = input2.parts() val expected2 = setOf(1 to 0) assertEquals(expected2, result2, "Unexpected result2") val input3 = ValidSegment(0 to 0, 0 to 2, false) val result3 = input3.parts() val expected3 = setOf(0 to 1) assertEquals(expected3, result3, "Unexpected result3") val input4 = ValidSegment(0 to 2, 0 to 0, false) val result4 = input4.parts() val expected4 = setOf(0 to 1) assertEquals(expected4, result4, "Unexpected result4") val input5 = ValidSegment(0 to 0, 3 to 3, false) val result5 = input5.parts() val expected5 = setOf(1 to 1, 2 to 2) assertEquals(expected5, result5, "Unexpected result5") val input6 = ValidSegment(3 to 3, 0 to 0, false) val result6 = input6.parts() val expected6 = setOf(1 to 1, 2 to 2) assertEquals(expected6, result6, "Unexpected result6") val input7 = ValidSegment(2 to 6, 4 to 4, false) val result7 = input7.parts() val expected7 = setOf(3 to 5) assertEquals(expected7, result7, "Unexpected result7") } }
0
Kotlin
0
1
6cda8f72d06c7ac33b8899a3425bfc22d7c852f4
3,711
othello
Apache License 2.0
domain/src/main/java/com/dennytech/domain/utils/Helpers.kt
OlukaDenis
740,856,818
false
{"Kotlin": 55503}
package com.dennytech.domain.utils import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale object Helpers { fun dateStringToMillis(timestamp: String): Long { val inputFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()) val date = inputFormat.parse(timestamp) return date?.time ?: 0L } fun addDaysToDate(timestamp: String, daysToAdd: Int): Long { val inputFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()) val date = inputFormat.parse(timestamp) val calendar = Calendar.getInstance() calendar.time = date!! calendar.add(Calendar.DAY_OF_MONTH, daysToAdd) return calendar.time.time } fun longToString(date: Long): String { val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()) return sdf.format(date) } fun addDaysToTimestamp(timestamp: String, daysToAdd: Int) : String { val endDateLong = addDaysToDate(timestamp, daysToAdd) return longToString(endDateLong) } }
0
Kotlin
0
0
b48257019acf0a7739289c62ff5441e12ec5a001
1,087
pay-dash
The Unlicense
domain/src/main/java/com/dennytech/domain/utils/Helpers.kt
OlukaDenis
740,856,818
false
{"Kotlin": 55503}
package com.dennytech.domain.utils import java.text.SimpleDateFormat import java.util.Calendar import java.util.Locale object Helpers { fun dateStringToMillis(timestamp: String): Long { val inputFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()) val date = inputFormat.parse(timestamp) return date?.time ?: 0L } fun addDaysToDate(timestamp: String, daysToAdd: Int): Long { val inputFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()) val date = inputFormat.parse(timestamp) val calendar = Calendar.getInstance() calendar.time = date!! calendar.add(Calendar.DAY_OF_MONTH, daysToAdd) return calendar.time.time } fun longToString(date: Long): String { val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()) return sdf.format(date) } fun addDaysToTimestamp(timestamp: String, daysToAdd: Int) : String { val endDateLong = addDaysToDate(timestamp, daysToAdd) return longToString(endDateLong) } }
0
Kotlin
0
0
b48257019acf0a7739289c62ff5441e12ec5a001
1,087
pay-dash
The Unlicense
src/test/kotlin/org/eclipse/tractusx/managedidentitywallets/BusinessPartnerDataMockedService.kt
eclipse-tractusx
531,494,665
false
{"Kotlin": 744116, "Smarty": 2971, "Dockerfile": 470, "Shell": 323}
/******************************************************************************** * Copyright (c) 2021,2023 Contributors to the Eclipse Foundation * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ package org.eclipse.tractusx.managedidentitywallets import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Deferred import org.eclipse.tractusx.managedidentitywallets.models.WalletDto import org.eclipse.tractusx.managedidentitywallets.services.IBusinessPartnerDataService class BusinessPartnerDataMockedService: IBusinessPartnerDataService { override suspend fun pullDataAndUpdateBaseWalletCredentialsAsync( identifier: String? ): Deferred<Boolean> { return CompletableDeferred(true) } override suspend fun issueAndStoreBaseWalletCredentialsAsync( walletHolderDto: WalletDto, type: String, data: Any? ): Deferred<Boolean> { return CompletableDeferred(true) } override suspend fun issueAndSendBaseWalletCredentialsForSelfManagedWalletsAsync( targetWallet: WalletDto, connectionId: String, webhookUrl: String?, type: String, data: Any? ): Deferred<Boolean> { return CompletableDeferred(true) } }
3
Kotlin
5
1
33537fdf039a771d551d175173d4c37d8dd17846
1,957
managed-identity-wallets-archived
Apache License 2.0
application/src/main/kotlin/no/nav/poao_tilgang/application/client/veilarbarena/VeilarbarenaClient.kt
navikt
491,417,288
false
null
package no.nav.poao_tilgang.application.client.veilarbarena import no.nav.poao_tilgang.core.domain.NavEnhetId import no.nav.poao_tilgang.core.domain.NorskIdent interface VeilarbarenaClient { fun hentBrukerOppfolgingsenhetId(norskIdent: NorskIdent): NavEnhetId? }
2
Kotlin
2
1
bb3c9f5f3d03f0192e623cf114f752318027e9c3
268
poao-tilgang
MIT License
app/src/main/java/com/thedearbear/nnov/journal/DayEntry.kt
TheDearbear
828,962,865
false
{"Kotlin": 188230}
package com.thedearbear.nnov.journal import java.time.LocalDate data class DayEntry( val date: LocalDate, val type: DayType = DayType.NORMAL, val typeSpecific: String? = null, val lessons: List<Lesson> = listOf() )
0
Kotlin
0
0
00c3ce0d1c7b21f96b591d1fa8b4372423a91e66
233
DigitalJournal
MIT License
app/src/main/java/com/example/happylife/LicenseListActivity.kt
aerimforest
377,703,215
true
{"Kotlin": 99297}
package com.example.happylife import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.happylife.databinding.ActivityLicenseListBinding class LicenseListActivity : AppCompatActivity() { private lateinit var binding: ActivityLicenseListBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_license_list) binding = ActivityLicenseListBinding.inflate(layoutInflater) val view = binding.root setContentView(view) binding.licenseListCategoryName.text = intent.getStringExtra("name") // 1위 자격증 선택 binding.linearlayoutNameOfRank1License.setOnClickListener { val intent = Intent(this, LicenseDetailInfo::class.java) intent.putExtra("name", binding.tvNameOfRank1License.text.toString()) startActivity(intent) } // 필터 선택 binding.filterBtnListLicense.setOnClickListener { val bottomSheet = BottomFilterSheetDialog() bottomSheet.show(supportFragmentManager, bottomSheet.tag) } // 뒤로가기 버튼 클릭 binding.btnBackwardToLicenseInfo.setOnClickListener { finish() } } }
0
Kotlin
1
0
16087c2819f40834bd6c8b5cb313e8835379f25f
1,301
JAGYEOKDAN_Android
MIT License
app/src/main/java/com/example/happylife/LicenseListActivity.kt
aerimforest
377,703,215
true
{"Kotlin": 99297}
package com.example.happylife import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.happylife.databinding.ActivityLicenseListBinding class LicenseListActivity : AppCompatActivity() { private lateinit var binding: ActivityLicenseListBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_license_list) binding = ActivityLicenseListBinding.inflate(layoutInflater) val view = binding.root setContentView(view) binding.licenseListCategoryName.text = intent.getStringExtra("name") // 1위 자격증 선택 binding.linearlayoutNameOfRank1License.setOnClickListener { val intent = Intent(this, LicenseDetailInfo::class.java) intent.putExtra("name", binding.tvNameOfRank1License.text.toString()) startActivity(intent) } // 필터 선택 binding.filterBtnListLicense.setOnClickListener { val bottomSheet = BottomFilterSheetDialog() bottomSheet.show(supportFragmentManager, bottomSheet.tag) } // 뒤로가기 버튼 클릭 binding.btnBackwardToLicenseInfo.setOnClickListener { finish() } } }
0
Kotlin
1
0
16087c2819f40834bd6c8b5cb313e8835379f25f
1,301
JAGYEOKDAN_Android
MIT License
memo-compiler-processing/src/main/java/com/zeoflow/memo/compiler/processing/ksp/KspExecutableParameterElement.kt
zeoflow
356,543,825
false
null
package com.zeoflow.memo.compiler.processing.ksp import com.zeoflow.memo.compiler.processing.XAnnotated import com.zeoflow.memo.compiler.processing.XExecutableParameterElement import com.zeoflow.memo.compiler.processing.XType import com.zeoflow.memo.compiler.processing.ksp.KspAnnotated.UseSiteFilter.Companion.NO_USE_SITE_OR_METHOD_PARAMETER import com.google.devtools.ksp.symbol.KSValueParameter internal class KspExecutableParameterElement( env: KspProcessingEnv, val method: KspExecutableElement, val parameter: KSValueParameter, ) : KspElement(env, parameter), XExecutableParameterElement, XAnnotated by KspAnnotated.create(env, parameter, NO_USE_SITE_OR_METHOD_PARAMETER) { override val equalityItems: Array<out Any?> get() = arrayOf(method, parameter) // todo constantValueData override val constantValue: Any get() = TODO("Not yet implemented") override val name: String get() = parameter.name?.asString() ?: "_no_param_name" override val type: KspType by lazy { parameter.typeAsMemberOf( functionDeclaration = method.declaration, ksType = method.containing.type?.ksType ).let { env.wrap( originatingReference = parameter.type, ksType = it ) } } override val fallbackLocationText: String get() = "$name in ${method.fallbackLocationText}" override fun asMemberOf(other: XType): KspType { if (method.containing.type?.isSameType(other) != false) { return type } check(other is KspType) return parameter.typeAsMemberOf( functionDeclaration = method.declaration, ksType = other.ksType ).let { env.wrap( originatingReference = parameter.type, ksType = it ) } } override fun kindName(): String { return "function parameter" } }
4
Kotlin
13
18
a1af0efdb7f2bb89035afc1d1bd9033d02f01503
1,986
memo
Apache License 2.0
src/main/kotlin/org/smart/home/simulator/entities/smartHome/SmartHomeRepository.kt
NLCProject
494,882,867
false
null
package org.smart.home.simulator.entities.smartHome import org.isc.utils.genericCrudl.services.RepositoryService import org.smart.home.simulator.entities.smartHome.interfaces.ISmartHomeRepository import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service @Service class SmartHomeRepository @Autowired constructor( repository: ISmartHomeRepository ) : RepositoryService<SmartHomeEntity>(repository = repository)
0
Kotlin
0
0
ea4e3c44fcca642ca8ade4c0498a1cdd6c9ba440
466
SmartHomeSimulator
The Unlicense
plugins/git4idea/src/git4idea/merge/dialog/OptionListCellRenderer.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.merge.dialog import com.intellij.ui.SimpleColoredComponent import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.popup.list.ListPopupImpl import com.intellij.ui.popup.list.PopupListElementRenderer import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.EmptyIcon import com.intellij.util.ui.JBInsets import com.intellij.util.ui.LafIconLookup import javax.swing.JComponent import javax.swing.JList class OptionListCellRenderer<T>( private val optionInfoProvider: (T) -> OptionInfo<T>, private val optionSelectedPredicate: (T) -> Boolean, private val optionSelectablePredicate: (T) -> Boolean, private val optionLongestDescription: String, listPopup: ListPopupImpl ) : PopupListElementRenderer<T>(listPopup) { private lateinit var optionComponent: SimpleColoredComponent override fun customizeComponent(list: JList<out T>, value: T, isSelected: Boolean) { super.customizeComponent(list, value, isSelected) val optionInfo: OptionInfo<T> = optionInfoProvider(value) val optionSelected = optionSelectedPredicate(value) val optionSelectable = optionSelectablePredicate(value) val descriptionAttributes = when { isSelected -> SimpleTextAttributes.SELECTED_SIMPLE_CELL_ATTRIBUTES optionSelectable -> SimpleTextAttributes.REGULAR_ATTRIBUTES else -> SimpleTextAttributes.GRAYED_ATTRIBUTES } val flagAttributes = if (isSelected) SimpleTextAttributes.SELECTED_SIMPLE_CELL_ATTRIBUTES else SimpleTextAttributes.GRAYED_ATTRIBUTES val checkmarkIcon = LafIconLookup.getIcon("checkmark", isSelected, false) optionComponent.apply { clear() append(optionInfo.description, descriptionAttributes) appendTextPadding(getFontMetrics(font).stringWidth(optionLongestDescription) + JBUIScale.scale(OFFSET_BETWEEN_OPTIONS_TEXT)) append(optionInfo.flag, flagAttributes) icon = if (optionSelected) checkmarkIcon else EmptyIcon.create(checkmarkIcon) } } override fun createItemComponent(): JComponent { createLabel() optionComponent = SimpleColoredComponent().apply { ipad = JBInsets.emptyInsets() } return layoutComponent(optionComponent) } companion object { private const val OFFSET_BETWEEN_OPTIONS_TEXT = 50 } }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
2,393
intellij-community
Apache License 2.0
app/src/main/java/taokdao/plugins/engine/rhino/controller/EngineController.kt
TIIEHenry
287,228,001
false
{"JavaScript": 47779, "Kotlin": 24585, "Java": 6400, "CSS": 1148}
package taokdao.plugins.engine.rhino.controller import taokdao.api.main.IMainContext import taokdao.api.plugin.bean.PluginManifest import taokdao.api.plugin.engine.PluginEnginePool import taokdao.api.plugin.entrance.BaseDynamicPluginEntrance import taokdao.plugins.engine.rhino.engine.RhinoPluginEngine class EngineController:BaseDynamicPluginEntrance() { private lateinit var rhinoPluginEngine: RhinoPluginEngine override fun onCreate(iMainContext: IMainContext, pluginManifest: PluginManifest) { rhinoPluginEngine = RhinoPluginEngine(iMainContext, pluginManifest.pluginDir) PluginEnginePool.getInstance().add(rhinoPluginEngine) } override fun onDestroy(iMainContext: IMainContext, pluginManifest: PluginManifest) { PluginEnginePool.getInstance().remove(rhinoPluginEngine) } fun getEngine(): RhinoPluginEngine { return rhinoPluginEngine } }
0
JavaScript
0
0
d312581509c93fc7cdde5351c2c8f8dde7ae9f21
907
TaoKDao-APK_Plugin-RhinoEngine
Apache License 2.0
LargeDynamicProject/featureA/baseA/src/main/java/com/devrel/experiment/large/dynamic/feature/a/Foo1346.kt
skimarxall
212,285,318
false
{"Markdown": 13, "Text": 10, "Ignore List": 24, "Gradle": 272, "Shell": 13, "Java Properties": 19, "XML": 1020, "Batchfile": 11, "Kotlin": 14867, "Java": 160, "Proguard": 13, "YAML": 10, "CMake": 1, "C": 1, "INI": 3}
package com.devrel.experiment.large.dynamic.feature.a annotation class Foo1346Fancy @Foo1346Fancy class Foo1346 { fun foo0(){ Foo1345().foo8() } fun foo1(){ foo0() } fun foo2(){ foo1() } fun foo3(){ foo2() } fun foo4(){ foo3() } fun foo5(){ foo4() } fun foo6(){ foo5() } fun foo7(){ foo6() } fun foo8(){ foo7() } }
1
null
1
1
e027d45a465c98c5ddbf33c68deb09a6e5975aab
396
app-bundle-samples
Apache License 2.0
matrix-sdk-android/src/main/java/org/matrix/android/sdk/internal/crypto/algorithms/IMXEncrypting.kt
ginnyTheCat
310,769,850
false
{"Gradle": 8, "Markdown": 16, "Java Properties": 2, "Shell": 19, "Text": 43, "Ignore List": 7, "Batchfile": 1, "EditorConfig": 1, "YAML": 2, "INI": 2, "Proguard": 5, "XML": 768, "Kotlin": 2184, "Java": 12, "JavaScript": 4, "JSON": 5, "HTML": 2, "Python": 2, "FreeMarker": 2, "Fluent": 7}
/* * Copyright 2015 OpenMarket Ltd * Copyright 2017 Vector Creations Ltd * Copyright 2020 The Matrix.org Foundation C.I.C. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.matrix.android.sdk.internal.crypto.algorithms import org.matrix.android.sdk.api.session.events.model.Content /** * An interface for encrypting data */ internal interface IMXEncrypting { /** * Encrypt an event content according to the configuration of the room. * * @param eventContent the content of the event. * @param eventType the type of the event. * @param userIds the room members the event will be sent to. * @return the encrypted content */ suspend fun encryptEventContent(eventContent: Content, eventType: String, userIds: List<String>): Content /** * In Megolm, each recipient maintains a record of the ratchet value which allows * them to decrypt any messages sent in the session after the corresponding point * in the conversation. If this value is compromised, an attacker can similarly * decrypt past messages which were encrypted by a key derived from the * compromised or subsequent ratchet values. This gives 'partial' forward * secrecy. * * To mitigate this issue, the application should offer the user the option to * discard historical conversations, by winding forward any stored ratchet values, * or discarding sessions altogether. */ fun discardSessionKey() /** * Re-shares a session key with devices if the key has already been * sent to them. * * @param sessionId The id of the outbound session to share. * @param userId The id of the user who owns the target device. * @param deviceId The id of the target device. * @param senderKey The key of the originating device for the session. * * @return true in case of success */ suspend fun reshareKey(sessionId: String, userId: String, deviceId: String, senderKey: String): Boolean }
1
null
1
1
ee1d5faf0d59f9cc1c058d45fae3e811d97740fd
2,616
matrix-android-sdk2
Apache License 2.0
data/src/main/java/xyz/loshine/nga/data/entity/TopicDetailsData.kt
loshine
150,576,469
false
null
package xyz.loshine.nga.data.entity import com.google.gson.annotations.SerializedName data class TopicDetailsData( @SerializedName("__CU") val currentUser: Any, @SerializedName("__GLOBAL") val global: Any, @SerializedName("__U") val userList: Map<String, Map<String, Any>>, @SerializedName("__T") val topic: TopicDetail, @SerializedName("__R") val rows: Map<String, TopicRow>, @SerializedName("__R__ROWS_PAGE") val pageSize: Int, @SerializedName("__ROWS") val rowsSize: Int ) { data class TopicDetail( val fid: Int = 0, val tid: Int = 0, val tpcurl: String = "", @SerializedName("quote_from") val quoteFrom: Int = 0, val author: String = "", val subject: String = "", @SerializedName("quote_to") val quoteTo: String = "", val icon: Int = 0, @SerializedName("postdate") val postDate: Long = 0, val locked: Int = 0, val recommend: Int = 0, val digest: Int = 0, val tpid: Int = 0, @SerializedName("authorid") val authorId: Int = 0, val type: Int = 0, val replies: Int = 0, @SerializedName("lastposter") val lastPoster: String = "", @SerializedName("lastpost") val lastPost: Long = 0, @SerializedName("topic_misc") val topicMisc: String = "", @SerializedName("lastmodify") val lastModify: Long = 0, @SerializedName("this_visit_rows") val thisVisitRows: Int = 0 ) data class TopicRow( val pid: Int = 0, val fid: Int = 0, val tid: Int = 0, @SerializedName("authorid") val authorId: Int = 0, val type: Int = 0, val score: Int = 0, @SerializedName("score_2") val score2: Int = 0, val recommend: Int = 0, @SerializedName("postdate") val postDate: String = "", val subject: String = "", @SerializedName("alterinfo") val alterInfo: String = "", val content: String = "", @SerializedName("lou") val index: Int = 0, // @SerializedName("content_length") val contentLength: Int = 0, @SerializedName("from_client") val fromClient: String? = null, @SerializedName("postdatetimestamp") val postDateTimestamp: Int = 0 ) }
0
null
1
2
c116d8b6d1ebbe88a99f973b695c1be483f00dc9
2,477
NationalGayAlliance
MIT License
game/plugin/navigation/door/src/door.kt
ultraviolet-jordan
482,152,097
false
null
package org.apollo.plugin.navigation.door import org.apollo.game.action.DistancedAction import org.apollo.game.model.Direction import org.apollo.game.model.Position import org.apollo.game.model.World import org.apollo.game.model.entity.Player import org.apollo.game.model.entity.obj.DynamicGameObject import org.apollo.game.model.entity.obj.GameObject import org.apollo.game.model.event.PlayerEvent import org.apollo.game.plugin.api.findObject import org.apollo.net.message.Message import java.util.Objects enum class DoorType { LEFT, RIGHT, NOT_SUPPORTED } class Door(private val gameObject: GameObject) { companion object { val LEFT_HINGE_ORIENTATION: HashMap<Direction, Direction> = hashMapOf( Direction.NORTH to Direction.WEST, Direction.SOUTH to Direction.EAST, Direction.WEST to Direction.SOUTH, Direction.EAST to Direction.NORTH ) val RIGHT_HINGE_ORIENTATION: HashMap<Direction, Direction> = hashMapOf( Direction.NORTH to Direction.EAST, Direction.SOUTH to Direction.WEST, Direction.WEST to Direction.NORTH, Direction.EAST to Direction.SOUTH ) val toggledDoors: HashMap<GameObject, GameObject> = hashMapOf() val LEFT_HINGED = setOf(1516, 1536, 1533) val RIGHT_HINGED = setOf(1519, 1530, 4465, 4467, 3014, 3017, 3018, 3019) /** * Find a given door in the world * @param world The [World] the door lives in * @param position The [Position] of the door * @param objectId The [GameObject] id of the door */ fun find(world: World, position: Position, objectId: Int): Door? { val region = world.regionRepository.fromPosition(position) val gameObject = region.findObject(position, objectId).orElseGet(null) return if (gameObject == null) { null } else { Door(gameObject) } } } /** * Returns the supported doors by the system * See [DoorType] */ fun supported(): Boolean { return type() !== DoorType.NOT_SUPPORTED } /** * Computes the given door type by which id exists in * the supported left and right hinged doors */ fun type(): DoorType { return when { gameObject.id in LEFT_HINGED -> DoorType.LEFT gameObject.id in RIGHT_HINGED -> DoorType.RIGHT else -> DoorType.NOT_SUPPORTED } } /** * Toggles a given [GameObject] orientation and position * Stores the door state in toggleDoors class variable */ fun toggle() { val world = gameObject.world val regionRepository = world.regionRepository regionRepository.fromPosition(gameObject.position).removeEntity(gameObject) val originalDoor: GameObject? = toggledDoors[gameObject] if (originalDoor == null) { val position = movePosition() val orientation: Int = translateDirection()?.toOrientationInteger() ?: gameObject.orientation val toggledDoor = DynamicGameObject.createPublic(world, gameObject.id, position, gameObject.type, orientation) regionRepository.fromPosition(position).addEntity(toggledDoor) toggledDoors.put(toggledDoor, gameObject) } else { toggledDoors.remove(gameObject) regionRepository.fromPosition(originalDoor.position).addEntity(originalDoor) } } /** * Calculates the position to move the door based on orientation */ private fun movePosition(): Position { return gameObject.position.step(1, Direction.WNES[gameObject.orientation]) } /** * Calculates the orientation of the door based on * if it is right or left hinged door */ private fun translateDirection(): Direction? { val direction = Direction.WNES[gameObject.orientation] return when (type()) { DoorType.LEFT -> LEFT_HINGE_ORIENTATION[direction] DoorType.RIGHT -> RIGHT_HINGE_ORIENTATION[direction] DoorType.NOT_SUPPORTED -> null } } } class OpenDoorAction(private val player: Player, private val door: Door, position: Position) : DistancedAction<Player>( 0, true, player, position, DISTANCE) { companion object { /** * The distance threshold that must be reached before the door is opened. */ const val DISTANCE = 1 /** * Starts a [OpenDoorAction] for the specified [Player], terminating the [Message] that triggered. */ fun start(message: Message, player: Player, door: Door, position: Position) { player.startAction(OpenDoorAction(player, door, position)) message.terminate() } } override fun executeAction() { if (player.world.submit(OpenDoorEvent(player))) { player.turnTo(position) door.toggle() } stop() } override fun equals(other: Any?): Boolean { return other is OpenDoorAction && position == other.position && player == other.player } override fun hashCode(): Int = Objects.hash(position, player) } class OpenDoorEvent(player: Player) : PlayerEvent(player)
0
null
5
5
656755cca55b2ee4ed4288d051c2dfbb1b61386e
5,354
apollo
BSD Zero Clause License
app/src/main/java/fr/free/nrw/commons/wikidata/WikidataDisambiguationItems.kt
commons-app
42,032,884
false
null
package fr.free.nrw.commons.wikidata enum class WikidataDisambiguationItems(val id: String) { DISAMBIGUATION_PAGE("Q4167410"), INTERNAL_ITEM("Q17442446"), CATEGORY("Q4167836"); companion object { fun isDisambiguationItem(ids: List<String>) = values().any { disambiguationItem: WikidataDisambiguationItems -> ids.any { id -> disambiguationItem.id == id } } } }
571
null
1179
997
93f1e1ec299a78dac8a013ea21414272c1675e7b
423
apps-android-commons
Apache License 2.0
plugins/kotlin/idea/tests/testData/refactoring/introduceParameter/resultedTypeWithJava.kt
JetBrains
2,489,216
false
null
private fun bar() { val b = Tester(<selection>ActionToolbar.foo</selection>) }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
82
intellij-community
Apache License 2.0
app/src/test/java/ru/a1024bits/bytheway/viewmodel/DisplayUsersViewModelTest.kt
NooAn
103,396,921
false
{"Gradle": 3, "YAML": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Java Properties": 2, "Proguard": 1, "Kotlin": 78, "XML": 106, "JSON": 1, "Java": 1}
package ru.a1024bits.bytheway.viewmodel import android.util.Log import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import ru.a1024bits.bytheway.model.User import ru.a1024bits.bytheway.repository.Filter import ru.a1024bits.bytheway.util.Constants.END_DATE import ru.a1024bits.bytheway.util.Constants.FIRST_INDEX_CITY import ru.a1024bits.bytheway.util.Constants.LAST_INDEX_CITY import ru.a1024bits.bytheway.util.Constants.START_DATE import java.util.* private val AGE_PARAMETER = "age" private val PHONE_PARAMETER = "phone" private val EMAIL_PARAMETER = "email" private val LAST_NAME_PARAMETER = "lastName" private val NAME_PARAMETER = "name" private val BUDGET_PARAMETER = "budget" @RunWith(JUnit4::class) class DisplayUsersViewModelTest { private lateinit var displayUsersViewModel: DisplayUsersViewModel val countAllUsers = 50 val countSimilarUsers = 5 @Before fun initialize() { displayUsersViewModel = DisplayUsersViewModel(null) Log.d("testing", "start fun \"initialize\" in DisplayUsersViewModelTest(junit)") } @Test fun testFilterUsersByFilters() { var filter = Filter() var filtrationValue = "15" filter.startAge = filtrationValue.toInt() - 1 filter.endAge = filtrationValue.toInt() + 1 var usersForFilterFiltration = generateUsersForFiltration(countAllUsers, countSimilarUsers, AGE_PARAMETER, filtrationValue) displayUsersViewModel.filterUsersByOptions(usersForFilterFiltration, filter) Assert.assertEquals(usersForFilterFiltration.size, countSimilarUsers) filter = Filter() filtrationValue = "13232" filter.startBudget = filtrationValue.toInt() - 1 filter.endBudget = filtrationValue.toInt() + 1 usersForFilterFiltration = generateUsersForFiltration(countAllUsers, countSimilarUsers, BUDGET_PARAMETER, filtrationValue) displayUsersViewModel.filterUsersByOptions(usersForFilterFiltration, filter) Assert.assertEquals(usersForFilterFiltration.size, countSimilarUsers) filter = Filter() filtrationValue = Calendar.getInstance().timeInMillis.toString() filter.endDate = filtrationValue.toLong() + 10 usersForFilterFiltration = generateUsersForFiltration(countAllUsers, countSimilarUsers, END_DATE, filtrationValue) displayUsersViewModel.filterUsersByOptions(usersForFilterFiltration, filter) Assert.assertEquals(usersForFilterFiltration.size, countSimilarUsers) filter = Filter() filtrationValue = Calendar.getInstance().timeInMillis.toString() filter.startDate = filtrationValue.toLong() - 10 usersForFilterFiltration = generateUsersForFiltration(countAllUsers, countSimilarUsers, START_DATE, filtrationValue) displayUsersViewModel.filterUsersByOptions(usersForFilterFiltration, filter) Assert.assertEquals(usersForFilterFiltration.size, countSimilarUsers) filter = Filter() filtrationValue = "CityOne" filter.startCity = filtrationValue usersForFilterFiltration = generateUsersForFiltration(countAllUsers, countSimilarUsers, FIRST_INDEX_CITY, filtrationValue) displayUsersViewModel.filterUsersByOptions(usersForFilterFiltration, filter) Assert.assertEquals(usersForFilterFiltration.size, countSimilarUsers) filter = Filter() filtrationValue = "CityTwo" filter.endCity = filtrationValue usersForFilterFiltration = generateUsersForFiltration(countAllUsers, countSimilarUsers, LAST_INDEX_CITY, filtrationValue) displayUsersViewModel.filterUsersByOptions(usersForFilterFiltration, filter) Assert.assertEquals(usersForFilterFiltration.size, countSimilarUsers) } @Test fun testFilterUsersByStringInRandomVariable() { var queryStringFiltration = "ExampleName" var variableName = NAME_PARAMETER Assert.assertEquals(displayUsersViewModel.filterUsersByString( queryStringFiltration, generateUsersForFiltration(countAllUsers, countSimilarUsers, variableName, queryStringFiltration) ).size, countSimilarUsers) variableName = EMAIL_PARAMETER queryStringFiltration = "<EMAIL>" Assert.assertEquals(displayUsersViewModel.filterUsersByString( queryStringFiltration, generateUsersForFiltration(countAllUsers, countSimilarUsers, variableName, queryStringFiltration) ).size, countSimilarUsers) variableName = AGE_PARAMETER queryStringFiltration = "17" Assert.assertEquals(displayUsersViewModel.filterUsersByString( queryStringFiltration, generateUsersForFiltration(countAllUsers, countSimilarUsers, variableName, queryStringFiltration) ).size, countSimilarUsers) variableName = LAST_NAME_PARAMETER queryStringFiltration = "ExampleLastName" Assert.assertEquals(displayUsersViewModel.filterUsersByString( queryStringFiltration, generateUsersForFiltration(countAllUsers, countSimilarUsers, variableName, queryStringFiltration) ).size, countSimilarUsers) variableName = PHONE_PARAMETER queryStringFiltration = "380123456789" Assert.assertEquals(displayUsersViewModel.filterUsersByString( queryStringFiltration, generateUsersForFiltration(countAllUsers, countSimilarUsers, variableName, queryStringFiltration) ).size, countSimilarUsers) variableName = FIRST_INDEX_CITY queryStringFiltration = "CityFirst" Assert.assertEquals(displayUsersViewModel.filterUsersByString( queryStringFiltration, generateUsersForFiltration(countAllUsers, countSimilarUsers, variableName, queryStringFiltration) ).size, countSimilarUsers) variableName = LAST_INDEX_CITY queryStringFiltration = "CityLast" Assert.assertEquals(displayUsersViewModel.filterUsersByString( queryStringFiltration, generateUsersForFiltration(countAllUsers, countSimilarUsers, variableName, queryStringFiltration) ).size, countSimilarUsers) } private fun generateUsersForFiltration(countAllUsers: Int, countSimilarUsers: Int, currentFiltrationVariable: String, valueFiltrationVariable: String): MutableList<User> { val originalUsers = ArrayList<User>() for (i in 0 until countSimilarUsers) { val currentUser = User() when (currentFiltrationVariable) { AGE_PARAMETER -> currentUser.age = valueFiltrationVariable.toInt() PHONE_PARAMETER -> currentUser.phone = valueFiltrationVariable EMAIL_PARAMETER -> currentUser.email = valueFiltrationVariable LAST_NAME_PARAMETER -> currentUser.lastName = valueFiltrationVariable FIRST_INDEX_CITY -> currentUser.cities[FIRST_INDEX_CITY] = valueFiltrationVariable LAST_INDEX_CITY -> currentUser.cities[LAST_INDEX_CITY] = valueFiltrationVariable NAME_PARAMETER -> currentUser.name = valueFiltrationVariable BUDGET_PARAMETER -> currentUser.budget = valueFiltrationVariable.toLong() END_DATE -> currentUser.dates[END_DATE] = valueFiltrationVariable.toLong() START_DATE -> currentUser.dates[START_DATE] = valueFiltrationVariable.toLong() } originalUsers.add(currentUser) } for (i in 0 until countAllUsers - countSimilarUsers) originalUsers.add(User()) return originalUsers } }
0
Kotlin
0
5
cead3342689933c01f251bfb8048d87088783bee
7,602
bytheway
MIT License
app/src/main/java/com/rmnivnv/cryptomoon/model/rxbus/RxBus.kt
ivnvrmn
98,931,608
false
null
package com.rmnivnv.cryptomoon.model.rxbus import io.reactivex.Observable import io.reactivex.subjects.PublishSubject /** * Created by rmnivnv on 25/07/2017. */ object RxBus { private val publisher = PublishSubject.create<Any>() fun publish(event: Any) = publisher.onNext(event) // Listen should return an Observable and not the publisher // Using ofType we filter only events that match that class type fun <T> listen(eventType: Class<T>): Observable<T> = publisher.ofType(eventType) }
2
null
14
113
4d1651ce680fbf49e71cafb7d49e2d49d059b5fd
514
CryptoMoon
Apache License 2.0
app/src/main/java/com/earth/angel/appphoto/fragment/PhotoFragment.kt
engineerrep
643,933,914
false
{"Java": 2291635, "Kotlin": 1651449}
package com.earth.angel.appphoto.fragment import android.os.Bundle import android.util.Log import android.view.View import androidx.fragment.app.activityViewModels import com.earth.angel.R import com.earth.angel.appphoto.PhotoEditActivity import com.earth.angel.databinding.FragmentPhotoBinding import com.earth.angel.event.ShareSuccessEvent import com.earth.angel.util.DataReportUtils import com.earth.angel.util.DateUtils import com.earth.libbase.base.AppViewModel import com.earth.libbase.base.BaseFragment import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode class PhotoFragment : BaseFragment<FragmentPhotoBinding>() { override fun getLayoutId(): Int = R.layout.fragment_photo private val mAppViewModel: AppViewModel by activityViewModels() override fun initFragment(view: View, savedInstanceState: Bundle?) { mBinding?.run { handler = this@PhotoFragment ivEditPhoto.setOnClickListener { if (DateUtils.isFastClick()){ DataReportUtils.getInstance().report("Click_post") Log.e("11","11") PhotoEditActivity.openPhotoEditActivity(requireActivity(), true) } } llPost.setOnClickListener { if (DateUtils.isFastClick()) { DataReportUtils.getInstance().report("Click_post") PhotoEditActivity.openPhotoEditActivity(requireActivity(), true) // ShareUtil.share(requireContext()) } } llShare.setOnClickListener { if (DateUtils.isFastClick()) { DataReportUtils.getInstance().report("Click_post") // mAppViewModel?.showLoading() // ShareUtil.share(requireContext()) } } } } @Subscribe(threadMode = ThreadMode.MAIN) fun onMessageEventEvent(event: ShareSuccessEvent) { mAppViewModel?.dismissLoading() } override fun onHiddenChanged(hidden: Boolean) { super.onHiddenChanged(hidden) if (!hidden) { EventBus.getDefault().register(this) }else{ EventBus.getDefault().unregister(this) } } }
1
null
1
1
415e0417870b6ff2c84a9798d1f3f3a4e6921354
2,331
EarthAngel
MIT License
app/src/main/java/com/ardakazanci/anlikmotivasyon/ui/main/ui/profile/otherprofile/OtherProfileFragment.kt
ardakazanci
229,326,545
false
null
package com.ardakazanci.anlikmotivasyon.ui.main.ui.profile.otherprofile import androidx.lifecycle.ViewModelProviders import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.lifecycle.Observer import com.ardakazanci.anlikmotivasyon.R import com.ardakazanci.anlikmotivasyon.databinding.OtherprofileFragmentBinding class OtherProfileFragment : Fragment() { companion object { fun newInstance() = OtherProfileFragment() } private lateinit var viewModel: OtherProfileViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val binding = DataBindingUtil.inflate<OtherprofileFragmentBinding>( inflater, R.layout.otherprofile_fragment, container, false ) viewModel = ViewModelProviders.of(this).get(OtherProfileViewModel::class.java) arguments!!.let { arguments -> val args = OtherProfileFragmentArgs.fromBundle(arguments) viewModel._otherUserId.value = args.userid } viewModel.otherUserIsFollow.observe(this, Observer { if (it) { binding.btnFollow.visibility = View.INVISIBLE binding.btnUnfollow.visibility = View.VISIBLE } else { binding.btnFollow.visibility = View.VISIBLE binding.btnUnfollow.visibility = View.INVISIBLE } }) binding.otherprofileviewmodel = viewModel binding.lifecycleOwner = this return binding.root } override fun onDestroyView() { super.onDestroyView() viewModel.onClearedCoroutines() } }
1
Kotlin
5
45
0b3628b9c9757904f1e4dbdeb757fb1ab84c4704
1,886
Heyyoo
Apache License 2.0
idea/tests/testData/intentions/removeEmptyParenthesesFromLambdaCall/afterLambda6.kt
JetBrains
278,369,660
false
null
// IS_APPLICABLE: false object A { object B { class C { fun returnFun(fn: () -> Unit): (() -> Unit) -> Unit = {} } } } fun test() { A.B.C().returnFun {} ()<caret> {} }
1
null
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
209
intellij-kotlin
Apache License 2.0
feature/wiki/src/androidTest/kotlin/com/github/felipehjcosta/marvelapp/wiki/utils/Extensions.kt
felipehjcosta
73,579,053
false
{"Gradle Kotlin DSL": 10, "Shell": 2, "Java Properties": 2, "Gradle": 1, "Text": 1, "Ignore List": 9, "Batchfile": 1, "YAML": 4, "Markdown": 1, "Proguard": 10, "XML": 46, "JSON": 13, "Kotlin": 122, "Java": 2}
package com.github.felipehjcosta.marvelapp.wiki.utils import android.content.Context import androidx.test.core.app.ApplicationProvider fun readAsset(fileName: String) = ApplicationProvider.getApplicationContext<Context>() .assets .open(fileName) .bufferedReader() .use { it.readText() }
0
Kotlin
0
16
f48c56c345622ac6dcf3fc8203c2b77114b5077b
320
marvel-app
MIT License
agp-7.1.0-alpha01/tools/base/build-system/gradle-core/src/main/java/com/android/build/api/component/analytics/AnalyticsEnabledPackaging.kt
jomof
502,039,754
false
{"Java": 35519326, "Kotlin": 22849138, "C++": 2171001, "HTML": 1377915, "Starlark": 915536, "C": 141955, "Shell": 110207, "RenderScript": 58853, "Python": 25635, "CMake": 18109, "Batchfile": 12180, "Perl": 9310, "Dockerfile": 5690, "Makefile": 4535, "CSS": 4148, "JavaScript": 3488, "PureBasic": 2359, "GLSL": 1628, "AIDL": 1117, "Prolog": 277}
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.api.component.analytics import com.android.build.api.variant.JniLibsPackaging import com.android.build.api.variant.Packaging import com.android.build.api.variant.ResourcesPackaging import com.android.tools.build.gradle.internal.profile.VariantPropertiesMethodType import com.google.wireless.android.sdk.stats.GradleBuildVariant import javax.inject.Inject open class AnalyticsEnabledPackaging @Inject constructor( open val delegate: Packaging, val stats: GradleBuildVariant.Builder ) : Packaging { override val jniLibs: JniLibsPackaging get() { stats.variantApiAccessBuilder.addVariantPropertiesAccessBuilder().type = VariantPropertiesMethodType.JNI_LIBS_PACKAGING_OPTIONS_VALUE return delegate.jniLibs } override val resources: ResourcesPackaging get() { stats.variantApiAccessBuilder.addVariantPropertiesAccessBuilder().type = VariantPropertiesMethodType.RESOURCES_PACKAGING_OPTIONS_VALUE return delegate.resources } }
1
Java
1
0
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
1,707
CppBuildCacheWorkInProgress
Apache License 2.0
HongUtils/src/main/java/com/hongwen/hongutils/image/BitmapUtils.kt
hardlove
225,118,279
false
{"Gradle": 22, "YAML": 1, "Markdown": 4, "Batchfile": 2, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 20, "INI": 13, "Proguard": 19, "XML": 270, "Java": 77, "Kotlin": 38, "JSON": 2}
package com.hongwen.hongutils.image import android.content.ContentValues import android.content.Context import android.content.Intent import android.content.res.Resources import android.graphics.* import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import android.net.Uri import android.os.Build import android.provider.MediaStore import android.util.Log import android.view.LayoutInflater import android.view.View import androidx.annotation.LayoutRes import java.io.* import java.net.URL object BitmapUtils { /** * * @param context * @param bitmap * @param storePath 保存图片的目录 * @return * */ @Deprecated( "", replaceWith = ReplaceWith("saveBitmapToGallery(context: Context, bitmap: Bitmap, displayName: String)") ) fun saveImageToGallery(context: Context, bitmap: Bitmap, storePath: String): Boolean { val appDir = File(storePath) if (!appDir.exists()) { appDir.mkdir() } val fileName = System.currentTimeMillis().toString() + ".png" val file = File(appDir, fileName) try { // val fos = FileOutputStream(file) // //通过io流的方式来压缩保存图片 // val isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos) // fos.flush() // fos.close() //把文件插入到系统图库 MediaStore.Images.Media.insertImage( context.contentResolver, file.absolutePath, fileName, null ) //保存图片后发送广播通知更新数据库 val uri = Uri.fromFile(file) context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri)) return /*isSuccess*/true } catch (e: IOException) { e.printStackTrace() } return false } fun saveBitmapToGallery(context: Context, bitmap: Bitmap, displayName: String) { // 获取图库的Uri val contentUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY) } else { MediaStore.Images.Media.EXTERNAL_CONTENT_URI } val contentResolver = context.contentResolver // 创建保存图片的元数据 val contentValues = ContentValues().apply { put(MediaStore.Images.Media.DISPLAY_NAME, displayName) put(MediaStore.Images.Media.MIME_TYPE, "image/png") } // 向图库插入新图片的元数据,并获取图片的Uri val imageUri = contentResolver.insert(contentUri, contentValues) // 如果成功获取到图片的Uri,则将Bitmap压缩成PNG格式并保存到该Uri指定的路径 imageUri?.let { uri -> //打开一个输出流,该流将写入图片数据 contentResolver.openOutputStream(uri)?.use { outputStream -> bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream) } } } /** * 将bitmap 按照指定的尺寸缩放 * * @param bitmap * @param reqWidth * @param reqHeight * @return */ fun decodeSampledBitmap(bitmap: Bitmap, reqWidth: Int, reqHeight: Int): Bitmap { val width = bitmap.width val height = bitmap.height // 计算缩放比例 val scaleWidth = reqWidth / width val scaleHeight = reqHeight / height // 缩放比例,如小于1就设置为1 var bili = Math.max(scaleWidth, scaleHeight) bili = Math.max(bili, 1) // 取得想要缩放的matrix参数 val matrix = Matrix() matrix.postScale(1.0f / bili, 1.0f / bili) //长和宽放大缩小的比例 return Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true) } /** * 将已经在界面上显示的View转成为Bitmap * * @param v * @return */ fun convertView2Bitmap(v: View): Bitmap { val bitmap = Bitmap.createBitmap(v.width, v.height, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) canvas.drawColor(Color.WHITE) // RectF rectf=new RectF(0,0,480,800); // canvas.drawArc(rectf, 0, -90, false, paint); v.draw(canvas) return bitmap } /** * 加载静态xml布局资生成Bitmap * * @param context * @param layoutRes xml 布局资源ID * @param onInitCallBack 数据初始化回调 */ fun convertViewToBitmap( context: Context, @LayoutRes layoutRes: Int, onInitCallBack: (View) -> Unit, ): Bitmap { val root = LayoutInflater.from(context).inflate(layoutRes, null) onInitCallBack(root) //测量 val width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) val height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) root.measure(width, height) val measuredWidth = root.measuredWidth val measuredHeight = root.measuredHeight //再次测量(避免子View无法正常显示) root.measure( View.MeasureSpec.makeMeasureSpec(measuredWidth, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(measuredHeight, View.MeasureSpec.EXACTLY) ) //布局 root.layout(0, 0, measuredWidth, measuredHeight) val bitmap = Bitmap.createBitmap(measuredWidth, measuredHeight, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) root.draw(canvas) return bitmap } /** * 加载静态View布局资生成Bitmap * * @param context * @param view 布局资源 */ fun convertViewToBitmap(context: Context, root: View): Bitmap { //测量 val width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) val height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED) root.measure(width, height) val measuredWidth = root.measuredWidth val measuredHeight = root.measuredHeight // //再次测量(避免子View无法正常显示) // root.measure( // View.MeasureSpec.makeMeasureSpec(measuredWidth, View.MeasureSpec.EXACTLY), // View.MeasureSpec.makeMeasureSpec(measuredHeight, View.MeasureSpec.EXACTLY) // ) //布局 root.layout(0, 0, measuredWidth, measuredHeight) val bitmap = Bitmap.createBitmap(measuredWidth, measuredHeight, Bitmap.Config.ARGB_8888) val canvas = Canvas(bitmap) root.draw(canvas) return bitmap } /** * 获取网络或本地缩略图 * @param imageUrl 图片的url地址 * @param defResID 默认本地占位资源ID * @return */ fun loadImageFromURL(imageUrl: String, w: Int, h: Int): Bitmap? { var bitmap: Bitmap? = null try { // 可以在这里通过文件名来判断,是否本地有此图片 bitmap = BitmapFactory.decodeStream(URL(imageUrl).openStream()) } catch (e: Exception) { e.printStackTrace() } if (bitmap != null) { val matrix = Matrix() val width = bitmap.width val height = bitmap.height val scaleWidth = w.toFloat() / width val scaleHeight = h.toFloat() / height matrix.postScale(scaleWidth, scaleHeight) bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true) } else { Log.d("test", "not null drawable") } return bitmap } fun loadImageFromURL(imageUrl: String, size: Int): Bitmap? { var bitmap: Bitmap? = null try { // 可以在这里通过文件名来判断,是否本地有此图片 bitmap = BitmapFactory.decodeStream(URL(imageUrl).openStream()) } catch (e: Exception) { e.printStackTrace() } if (bitmap != null) { val matrix = Matrix() val width = bitmap.width val height = bitmap.height val scaleWidth = size.toFloat() / width val scaleHeight = size.toFloat() / height val scale = Math.max(scaleWidth, scaleHeight) matrix.postScale(scale, scale) bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true) } else { Log.d("test", "not null drawable") } return bitmap } fun loadImageFromFile(file: File, size: Int): Bitmap? { var bitmap: Bitmap? = null try { // 可以在这里通过文件名来判断,是否本地有此图片 bitmap = BitmapFactory.decodeFile(file.absolutePath) } catch (e: Exception) { e.printStackTrace() } if (bitmap != null) { val matrix = Matrix() val width = bitmap.width val height = bitmap.height val scaleWidth = size.toFloat() / width val scaleHeight = size.toFloat() / height val scale = Math.max(scaleWidth, scaleHeight) matrix.postScale(scale, scale) bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true) } else { Log.d("test", "not null drawable") } return bitmap } /** * bitmap 2 drawable * * @param bitmap * @return */ @JvmStatic fun convertBitmap2Drawable(bitmap: Bitmap): Drawable { return BitmapDrawable(Resources.getSystem(), bitmap) } /** * drawable 2 bitmap * * @param drawable * @return */ @JvmStatic fun drawableToBitmap(drawable: Drawable): Bitmap { val bitmap = Bitmap.createBitmap( drawable.intrinsicWidth, drawable.intrinsicHeight, if (drawable.opacity != PixelFormat.OPAQUE) Bitmap.Config.ARGB_8888 else Bitmap.Config.RGB_565 ) val canvas = Canvas(bitmap) drawable.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight) drawable.draw(canvas) return bitmap } /** * 解析图片的尺寸信息 * options.outWidth :图片的宽度 * options.outHeight:图片的高度 * * @param pathName * @return */ fun getBitmapOptions(pathName: String): BitmapFactory.Options { val options = BitmapFactory.Options() options.inJustDecodeBounds = true BitmapFactory.decodeFile(pathName, options) return options } /** * 保存Bitmap至本地 * * @param bitmap * @param file */ @JvmStatic fun saveBitmapFile(bitmap: Bitmap, file: File?) { var bos: BufferedOutputStream? = null try { bos = BufferedOutputStream(FileOutputStream(file)) bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos) bos.flush() } catch (e: java.lang.Exception) { e.printStackTrace() } finally { close(bos) } } @JvmStatic fun close(c: Closeable?) { // java.lang.IncompatibleClassChangeError: interface not implemented if (c is Closeable) { try { c.close() } catch (e: java.lang.Exception) { // silence } } } }
0
Java
3
1
01f034e83b366a28fd483518420e294f3f79e116
10,753
UiLibrary
Apache License 2.0
app/src/main/java/com/foreveross/atwork/modules/newsSummary/adapter/OftenReadRvAdapter.kt
AoEiuV020
421,650,297
false
{"Java": 8618305, "Kotlin": 1733509, "JavaScript": 719597, "CSS": 277438, "HTML": 111559}
package com.foreveross.atwork.modules.newsSummary.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.foreverht.db.service.repository.UnreadSubcriptionMRepository import com.foreveross.atwork.R import com.foreveross.atwork.infrastructure.model.app.App import com.foreveross.atwork.utils.AvatarHelper class OftenReadRvAdapter: RecyclerView.Adapter<OftenReadRvAdapter.ViewHolder> { companion object { const val TYPE_IN = 0 const val TYPE_OUT = 1 const val TYPE_INT_OTHER = 2 const val USE_RESON = "立即使用" const val HAS_GET = "已领取" } var items: List<App>? = null var context: Context? = null var itemClick: ItemClick? = null constructor(items: List<App>, context: Context) { this.items = items this.context = context } fun setItemClickListener(itemClick: ItemClick) { this.itemClick = itemClick } fun updateData(items: List<App>) { this.items = items notifyDataSetChanged() } override fun getItemCount(): Int { return items!!.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { if (this.items!![position].mAppName != null) { holder.excText.text = this.items!![position].mAppName } if (this.items!![position].mAppId != null) { AvatarHelper.setAppAvatarById(holder.image, this.items!![position].mAppId, this.items!![position].mOrgId, true, true) val dataList = UnreadSubcriptionMRepository.getInstance().queryByAppId(this.items!![position].mAppId) if(dataList.size > 0){ holder.ivPointUnread.visibility = View.VISIBLE }else{ holder.ivPointUnread.visibility = View.GONE } } holder.rlJump.setOnClickListener { itemClick!!.OnItemClick(position,this.items!![position]) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val v = LayoutInflater.from(parent.context).inflate(R.layout.item_news_summary_often_read, parent, false) as LinearLayout return ViewHolder(v) } class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView!!) { var image: ImageView = itemView!!.findViewById(R.id.imgBody) as ImageView var ivPointUnread: ImageView = itemView!!.findViewById(R.id.ivPointUnread) as ImageView var excText: TextView = itemView!!.findViewById(R.id.excText) as TextView var rlJump: LinearLayout = itemView!!.findViewById(R.id.rlJump) as LinearLayout } interface ItemClick { fun OnItemClick(position: Int, app: App) } }
1
null
1
1
1c4ca5bdaea6d5230d851fb008cf2578a23b2ce5
2,908
w6s_lite_android
MIT License
api/src/main/java/com/vk/sdk/api/widgets/dto/WidgetsWidgetPageDto.kt
VKCOM
16,025,583
false
null
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * 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. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.widgets.dto import com.google.gson.annotations.SerializedName import com.vk.sdk.api.base.dto.BaseObjectCount import kotlin.Int import kotlin.String /** * @param comments * @param date - Date when widgets on the page has been initialized firstly in Unixtime * @param description - Page description * @param id - Page ID * @param likes * @param pageId - page_id parameter value * @param photo - URL of the preview image * @param title - Page title * @param url - Page absolute URL */ data class WidgetsWidgetPage( @SerializedName("comments") val comments: BaseObjectCount? = null, @SerializedName("date") val date: Int? = null, @SerializedName("description") val description: String? = null, @SerializedName("id") val id: Int? = null, @SerializedName("likes") val likes: BaseObjectCount? = null, @SerializedName("page_id") val pageId: String? = null, @SerializedName("photo") val photo: String? = null, @SerializedName("title") val title: String? = null, @SerializedName("url") val url: String? = null )
69
null
3
440
3dd6d9e3bc10ce9e77c3ea9331cc753f704f8f79
2,495
vk-android-sdk
MIT License
src/com/silverkeytech/android_rivers/db/BookmarkCollectionKind.kt
svtk
13,240,006
false
null
package com.silverkeytech.android_rivers.db public enum class BookmarkCollectionKind{ RIVER LINK NONE }
0
null
2
7
b86837bc1035bbf891fae0065eec0cb71d701cb7
118
AndroidRivers
Apache License 2.0
Section 8/KotlinNotes-master/app/src/main/java/com/markodevcic/kotlinnotes/notes/NotesAdapter.kt
PacktPublishing
187,770,226
false
null
package com.markodevcic.kotlinnotes.notes import android.view.ViewGroup import com.markodevcic.kotlinnotes.data.Note import io.realm.RealmRecyclerViewAdapter import io.realm.RealmResults import org.jetbrains.anko.AnkoContext class NotesAdapter(private var notes: RealmResults<Note>, autoUpdate: Boolean) : RealmRecyclerViewAdapter<Note, NotesViewHolder>(notes, autoUpdate) { override fun onBindViewHolder(holder: NotesViewHolder, position: Int) { val note = notes[position] holder.bind(note) } override fun getItemCount(): Int { return notes.size } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NotesViewHolder { return NotesViewHolder(NotesUi().createView(AnkoContext.create(parent.context, parent))) } fun onResultsChanged(results: RealmResults<Note>) { notes = results super.updateData(notes) } }
1
null
2
3
79ca85b1ac6d71408dfa8ed2061785aa42dc111f
846
Mastering-Kotlin-for-Android-Development
MIT License
core/src/com/floor13/game/util/SidedTextureResolver.kt
FantAsylum
98,576,459
false
{"Kotlin": 29138, "Java": 938}
package com.floor13.game.util import com.badlogic.gdx.graphics.g2d.TextureAtlas import com.badlogic.gdx.graphics.g2d.TextureRegion import ktx.collections.* import com.floor13.game.core.map.Map import com.floor13.game.core.map.Tile import com.floor13.game.core.map.Ground import com.floor13.game.core.map.Wall import com.floor13.game.core.map.Door import com.floor13.game.core.Position /** * @param atlas atlas for resolving textures */ class SidedTextureResolver( private val atlas: TextureAtlas, private val width: Int, private val height: Int, private val isSameTexture: (Int, Int, Int, Int) -> Boolean ) { private val cache: Array<Array<MutableMap<String, TextureRegion>>> = Array( width, { Array(height, { mutableMapOf<String, TextureRegion>() })} ) private val variants = gdxArrayOf<TextureRegion>() constructor(atlas: TextureAtlas, map: Map) : this( atlas, map.width, map.height, { x1, y1, x2, y2 -> map[x1, y1] sameTileTypeAs map[x2, y2] } ) fun getTexture(name: String, x: Int, y: Int): TextureRegion { val isAlreadyCached = cache[x][y][name] != null return if (isAlreadyCached) { cache[x][y][name]!! } else { val suffix = StringBuilder() // order convention: urld if (y == height - 1 || isSameTexture(x, y + 1, x, y)) suffix.append('u') if (x == width - 1 || isSameTexture(x + 1, y, x, y)) suffix.append('r') if (x == 0 || isSameTexture(x - 1, y, x, y)) suffix.append('l') if (y == 0 || isSameTexture(x, y - 1, x, y)) suffix.append('d') val exactName = "${name}_${suffix}" val genericName = "${name}_a" variants.clear() for (region in atlas.getRegions()) if (region.name == exactName || region.name == genericName) variants.add(region) val result = variants.random() cache[x][y][name] = result result } } companion object { private infix fun Tile.sameTileTypeAs(tile: Tile): Boolean { // review this solution if you added additional Tile types return this is Ground && tile is Ground || (!(this is Ground) && !(tile is Ground)) } } }
4
Kotlin
0
0
ccca7395bff9225cc1a497fd94bad58c37aae9ce
2,363
Floor--13
MIT License
src/main/kotlin/org/graphomance/vendor/neo4j/NeoIdentifier.kt
grzegorz-aniol
161,749,625
false
{"Markdown": 5, "Gradle": 2, "YAML": 3, "Dotenv": 1, "INI": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Kotlin": 49, "Cypher": 4}
package org.graphomance.vendor.neo4j import org.graphomance.api.NodeIdentifier import org.graphomance.api.RelationshipIdentifier class NeoIdentifier( val id: Long // TODO: change to element ID ) : NodeIdentifier, RelationshipIdentifier { companion object { fun toLong(id: NodeIdentifier) = (id as NeoIdentifier).id fun toLong(id: RelationshipIdentifier) = (id as NeoIdentifier).id } }
1
null
1
1
4107d3a7ff5599659ded084f62a954f0c8d557d3
414
graphomance
MIT License
list/src/main/java/archtree/list/adapter/bindable/DefaultBindableLinearLayoutAdapter.kt
Mordag
129,695,558
false
{"Gradle": 10, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 9, "Batchfile": 1, "Markdown": 8, "YAML": 1, "Proguard": 8, "XML": 18, "Kotlin": 60, "Java": 1}
package archtree.list.adapter.bindable import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.annotation.LayoutRes import androidx.databinding.DataBindingComponent import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ViewModel import androidx.recyclerview.widget.RecyclerView import archtree.list.item.BindableListItem import archtree.list.item.DataContextAwareViewHolder import java.util.* open class DefaultBindableLinearLayoutAdapter(private val context: Context) : BindableLinearLayoutAdapter() { private val itemList = ArrayList<BindableListItem>() private var itemLayout: Int = 0 private var viewModel: ViewModel? = null private var dataBindingComponent: Any? = null private var lifecycleOwner: LifecycleOwner? = null private var dataBindingComponentKey: Int? = null private var lifecycleOwnerKey: Int? = null override fun onUpdate(list: List<BindableListItem>, @LayoutRes itemLayout: Int?, viewModel: ViewModel?, dataBindingComponent: Any?, dataBindingComponentKey: Int?, lifecycleOwner: LifecycleOwner?, lifecycleOwnerKey: Int?) { this.itemLayout = itemLayout ?: 0 this.viewModel = viewModel this.dataBindingComponent = dataBindingComponent this.lifecycleOwner = lifecycleOwner this.dataBindingComponentKey = dataBindingComponentKey this.lifecycleOwnerKey = lifecycleOwnerKey itemList.clear() itemList.addAll(list) notifyDataSetChanged() } override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): RecyclerView.ViewHolder { //use the first item in list to determine the correct item layout that should be used val itemLayoutRes = itemList.firstOrNull()?.onDetermineLayoutRes(viewType) ?: itemLayout val realDataBindingComponent: DataBindingComponent? = if (dataBindingComponent != null) { try { dataBindingComponent as? DataBindingComponent? } catch (e: ClassCastException) { null } } else null val binding = DataBindingUtil.inflate<ViewDataBinding>( LayoutInflater.from(context), itemLayoutRes, viewGroup, false, realDataBindingComponent ) val dataBindingKey = dataBindingComponentKey if (dataBindingKey != null) binding.setVariable(dataBindingKey, realDataBindingComponent) val lifecycleKey = lifecycleOwnerKey if (lifecycleKey != null) binding.setVariable(lifecycleKey, lifecycleOwner) if (lifecycleOwner != null) binding.lifecycleOwner = lifecycleOwner return DataContextAwareViewHolder(binding, viewType) } override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) { if (viewHolder is DataContextAwareViewHolder) viewHolder.onBind(itemList[position], viewModel) } override val itemCount: Int get() = itemList.size override fun getType(position: Int): Int = itemList[position].getItemViewType() }
0
Kotlin
1
2
8daf284b9ae3d908c545b82bc42abdc86baec1c4
3,291
archtree
Apache License 2.0
list/src/main/java/archtree/list/adapter/bindable/DefaultBindableLinearLayoutAdapter.kt
Mordag
129,695,558
false
{"Gradle": 10, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 9, "Batchfile": 1, "Markdown": 8, "YAML": 1, "Proguard": 8, "XML": 18, "Kotlin": 60, "Java": 1}
package archtree.list.adapter.bindable import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.annotation.LayoutRes import androidx.databinding.DataBindingComponent import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ViewModel import androidx.recyclerview.widget.RecyclerView import archtree.list.item.BindableListItem import archtree.list.item.DataContextAwareViewHolder import java.util.* open class DefaultBindableLinearLayoutAdapter(private val context: Context) : BindableLinearLayoutAdapter() { private val itemList = ArrayList<BindableListItem>() private var itemLayout: Int = 0 private var viewModel: ViewModel? = null private var dataBindingComponent: Any? = null private var lifecycleOwner: LifecycleOwner? = null private var dataBindingComponentKey: Int? = null private var lifecycleOwnerKey: Int? = null override fun onUpdate(list: List<BindableListItem>, @LayoutRes itemLayout: Int?, viewModel: ViewModel?, dataBindingComponent: Any?, dataBindingComponentKey: Int?, lifecycleOwner: LifecycleOwner?, lifecycleOwnerKey: Int?) { this.itemLayout = itemLayout ?: 0 this.viewModel = viewModel this.dataBindingComponent = dataBindingComponent this.lifecycleOwner = lifecycleOwner this.dataBindingComponentKey = dataBindingComponentKey this.lifecycleOwnerKey = lifecycleOwnerKey itemList.clear() itemList.addAll(list) notifyDataSetChanged() } override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): RecyclerView.ViewHolder { //use the first item in list to determine the correct item layout that should be used val itemLayoutRes = itemList.firstOrNull()?.onDetermineLayoutRes(viewType) ?: itemLayout val realDataBindingComponent: DataBindingComponent? = if (dataBindingComponent != null) { try { dataBindingComponent as? DataBindingComponent? } catch (e: ClassCastException) { null } } else null val binding = DataBindingUtil.inflate<ViewDataBinding>( LayoutInflater.from(context), itemLayoutRes, viewGroup, false, realDataBindingComponent ) val dataBindingKey = dataBindingComponentKey if (dataBindingKey != null) binding.setVariable(dataBindingKey, realDataBindingComponent) val lifecycleKey = lifecycleOwnerKey if (lifecycleKey != null) binding.setVariable(lifecycleKey, lifecycleOwner) if (lifecycleOwner != null) binding.lifecycleOwner = lifecycleOwner return DataContextAwareViewHolder(binding, viewType) } override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) { if (viewHolder is DataContextAwareViewHolder) viewHolder.onBind(itemList[position], viewModel) } override val itemCount: Int get() = itemList.size override fun getType(position: Int): Int = itemList[position].getItemViewType() }
0
Kotlin
1
2
8daf284b9ae3d908c545b82bc42abdc86baec1c4
3,291
archtree
Apache License 2.0
app/src/main/java/com/leichui/shortviedeo/http/OkGoStringCallBack.kt
kknet
378,407,063
false
{"Java": 1891463, "Kotlin": 227641}
package com.leichui.shortviedeo.http import android.content.Context import com.leichui.conghua.utils.L import com.leichui.conghua.utils.dissMissDialog import com.leichui.conghua.utils.showWiteDialog import com.lzy.okgo.callback.StringCallback import com.lzy.okgo.model.Response import com.lzy.okgo.request.base.Request abstract class OkGoStringCallBack<S>(val context: Context, val clazz: Class<S>, val openDialog: Boolean = true, val showtoast: Boolean = true,val checkData: Boolean = true ) : StringCallback() { override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>?) { super.onStart(request) if (openDialog) { showWiteDialog(context) } } override fun onSuccess(response: Response<String>?) { if (null == response) { onError(null) return } val bean = json(context, response!!.body(), clazz,showtoast,checkData) if (null != bean) { onSuccess2Bean(bean) } else { response.exception = IllegalStateException("json 解析出错---返回---${response.body()}") onError(response) } } abstract fun onSuccess2Bean(bean: S) override fun onFinish() { super.onFinish() dissMissDialog() } override fun onError(response: Response<String>?) { super.onError(response) if (null != response) { L("请求出错---" + response.exception) } else { L("请求出错---返回null") } } }
0
Java
1
0
8f8f69b200886d4b6671bcc0b2eb11a5343fd7fd
1,524
VideoChat
Apache License 2.0
app/src/main/java/com/guilla/lab/mvp/views/BaseView.kt
FGuillRepo
189,380,725
false
null
package com.guilla.lab.mvp.views /** * Created by dino on 20/03/15. */ interface BaseView { fun showProgress() fun hideProgress() fun showError(message: String) }
0
Kotlin
0
0
3a13a8ea883b79160c8741984cb98a4ebe65fb28
181
Sample_RepositoryList_Dagger
Apache License 2.0
src/main/kotlin/dev/meanmail/codeInsight/completion/directives/ngx_http_core_module.kt
meanmail-dev
315,109,527
false
{"Kotlin": 167591, "Java": 34357, "Lex": 3299, "HTML": 1064}
package dev.meanmail.codeInsight.completion.directives // https://nginx.org/en/docs/http/ngx_http_core_module.html val absoluteRedirect = ToggleDirective("absolute_redirect", true) val aio = ToggleDirective("aio", false) val aioWrite = ToggleDirective("aio_write", false) val alias = Directive("alias") val authDelay = Directive( "auth_delay", defaultValue = "0s" ) val chunkedTransferEncoding = ToggleDirective("chunked_transfer_encoding", true) val clientBodyBufferSize = Directive("client_body_buffer_size") val clientBodyInFileOnly = Directive( "client_body_in_file_only", setOf("on", "clean", "off"), defaultValue = "off" ) val clientBodyInSingleBuffer = ToggleDirective("client_body_in_single_buffer", false) val clientBodyTempPath = Directive( "client_body_temp_path", defaultValue = "client_body_temp" ) val clientBodyTimeout = Directive( "client_body_timeout", defaultValue = "60s" ) val clientHeaderBufferSize = Directive( "client_header_buffer_size", defaultValue = "1k" ) val clientHeaderTimeout = Directive( "client_header_timeout", defaultValue = "60s" ) val clientMaxBodySize = Directive( "client_max_body_size", defaultValue = "1m" ) val connectionPoolSize = Directive("connection_pool_size") val defaultType = Directive( "default_type", defaultValue = "text/plain" ) val directio = Directive( "directio", defaultValue = "off" ) val directioAlignment = Directive( "directio_alignment", defaultValue = "512" ) val disableSymlinks = Directive( "disable_symlinks", defaultValue = "off" ) val errorPage = Directive("error_page") val etag = ToggleDirective("etag", true) val ifModifiedSince = Directive( "if_modified_since", setOf("on", "exact", "before"), defaultValue = "exact" ) val ignoreInvalidHeaders = ToggleDirective("ignore_invalid_headers", true) val internal = Directive("internal") val keepaliveDisable = Directive( "keepalive_disable", defaultValue = "msie6" ) val keepaliveRequests = Directive( "keepalive_requests", defaultValue = "1000" ) val keepaliveTime = Directive( "keepalive_time", defaultValue = "1h" ) val keepaliveTimeout = Directive( "keepalive_timeout", defaultValue = "75s" ) val largeClientHeaderBuffers = Directive( "large_client_header_buffers", defaultValue = "4 8k" ) val limitExcept = Directive( "limit_except", children = setOf( accessLog, allow, authBasic, authBasicUserFile, authJwt, authJwtKeyFile, authJwtKeyRequest, authJwtRequire, authJwtType, deny, jsBodyFilter, jsContent, jsHeaderFilter, perl, proxyPass, ) ) val limitRate = Directive( "limit_rate", defaultValue = "0" ) val limitRateAfter = Directive( "limit_rate_after", defaultValue = "0" ) val lingeringClose = Directive( "lingering_close", setOf("off", "on", "always"), defaultValue = "on" ) val lingeringTime = Directive( "lingering_time", defaultValue = "30s" ) val lingeringTimeout = Directive( "lingering_timeout", defaultValue = "5s" ) val logNotFound = ToggleDirective("log_not_found", true) val logSubrequest = ToggleDirective("log_subrequest", false) val maxErrors = Directive( "max_errors", defaultValue = "5" ) val maxRanges = Directive("max_ranges") val mergeSlashes = ToggleDirective("merge_slashes", true) val msiePadding = ToggleDirective("msie_padding", true) val msieRefresh = ToggleDirective("msie_refresh", false) val openFileCache = Directive( "open_file_cache", defaultValue = "off" ) val openFileCacheErrors = ToggleDirective("open_file_cache_errors", false) val openFileCacheMinUses = Directive( "open_file_cache_min_uses", defaultValue = "1" ) val openFileCacheValid = Directive( "open_file_cache_valid", defaultValue = "60s" ) val outputBuffers = Directive( "output_buffers", defaultValue = "2 32k" ) val protocol = Directive("protocol") val portInRedirect = ToggleDirective("port_in_redirect", true) val postponeOutput = Directive( "postpone_output", defaultValue = "1460" ) val readAhead = Directive( "read_ahead", defaultValue = "0" ) val recursiveErrorPages = ToggleDirective("recursive_error_pages", false) val requestPoolSize = Directive( "request_pool_size", defaultValue = "4k" ) val resetTimedoutConnection = ToggleDirective("reset_timedout_connection", false) val resolver = Directive( "resolver", defaultValue = "off" ) val resolverTimeout = Directive( "resolver_timeout", defaultValue = "30s" ) val root = Directive( "root", defaultValue = "html" ) val satisfy = Directive( "satisfy", setOf("all", "any"), defaultValue = "all" ) val sendLowat = Directive( "send_lowat", defaultValue = "0" ) val sendTimeout = Directive( "send_timeout", defaultValue = "60s" ) val sendfile = ToggleDirective("sendfile", false) val sendfileMaxChunk = Directive( "sendfile_max_chunk", defaultValue = "2m" ) val serverNameInRedirect = ToggleDirective("server_name_in_redirect", false) val serverNamesHashBucketSize = Directive("server_names_hash_bucket_size") val serverNamesHashMaxSize = Directive( "server_names_hash_max_size", defaultValue = "512" ) val serverTokens = Directive( "server_tokens", defaultValue = "on" ) val subrequestOutputBufferSize = Directive("subrequest_output_buffer_size") val tcpNodelay = ToggleDirective("tcp_nodelay", true) val tcpNopush = ToggleDirective("tcp_nopush", false) val timeout = Directive( "timeout", defaultValue = "60s" ) val tryFiles = Directive("try_files") val types = Directive("types") val typesHashBucketSize = Directive( "types_hash_bucket_size", defaultValue = "64" ) val typesHashMaxSize = Directive( "types_hash_max_size", defaultValue = "1024" ) val underscoresInHeaders = ToggleDirective("underscores_in_headers", false) val variablesHashBucketSize = Directive( "variables_hash_bucket_size", defaultValue = "64" ) val variablesHashMaxSize = Directive( "variables_hash_max_size", defaultValue = "1024" ) val location = RecursiveDirective( "location", children = setOf( `break`, `if`, `return`, absoluteRedirect, accessLog, addAfterBody, addBeforeBody, addHeader, additionTypes, addTrailer, aio, aioWrite, alias, allow, ancientBrowser, ancientBrowserValue, api, authBasic, authBasicUserFile, authDelay, authJwt, authJwtKeyFile, authJwtKeyRequest, authJwtLeeway, authJwtRequire, authJwtType, authRequest, authRequestSet, autoindex, autoindexExactSize, autoindexFormat, autoindexLocaltime, charset, charsetTypes, chunkedTransferEncoding, clientBodyBufferSize, clientBodyInFileOnly, clientBodyInSingleBuffer, clientBodyTempPath, clientBodyTimeout, clientMaxBodySize, createFullPutPath, davAccess, davMethods, defaultType, deny, directio, directioAlignment, disableSymlinks, emptyGif, errorLog, errorPage, etag, expires, f4f, f4FBufferSize, fastcgiBind, fastcgiBuffering, fastcgiBuffers, fastcgiBufferSize, fastcgiBusyBuffersSize, fastcgiCache, fastcgiCacheBackgroundUpdate, fastcgiCacheBypass, fastcgiCacheKey, fastcgiCacheLock, fastcgiCacheLockAge, fastcgiCacheLockTimeout, fastcgiCacheMaxRangeOffset, fastcgiCacheMethods, fastcgiCacheMinUses, fastcgiCachePurge, fastcgiCacheRevalidate, fastcgiCacheUseStale, fastcgiCacheValid, fastcgiCatchStderr, fastcgiConnectTimeout, fastcgiForceRanges, fastcgiHideHeader, fastcgiIgnoreClientAbort, fastcgiIgnoreHeaders, fastcgiIndex, fastcgiInterceptErrors, fastcgiKeepConn, fastcgiLimitRate, fastcgiMaxTempFileSize, fastcgiNextUpstream, fastcgiNextUpstreamTimeout, fastcgiNextUpstreamTries, fastcgiNoCache, fastcgiParam, fastcgiPass, fastcgiPassHeader, fastcgiPassRequestBody, fastcgiPassRequestHeaders, fastcgiReadTimeout, fastcgiRequestBuffering, fastcgiSendLowat, fastcgiSendTimeout, fastcgiSocketKeepalive, fastcgiSplitPathInfo, fastcgiStore, fastcgiStoreAccess, fastcgiTempFileWriteSize, fastcgiTempPath, flv, grpcBind, grpcBufferSize, grpcConnectTimeout, grpcHideHeader, grpcIgnoreHeaders, grpcInterceptErrors, grpcNextUpstream, grpcNextUpstreamTimeout, grpcNextUpstreamTries, grpcPass, grpcSetHeader, grpcSocketKeepalive, grpcSslCertificate, grpcSslCertificateKey, grpcSslCiphers, grpcSslConfCommand, grpcSslCrl, grpcSslName, grpcSslPasswordFile, grpcSslProtocols, grpcSslServerName, grpcSslSessionReuse, grpcSslTrustedCertificate, grpcSslVerify, grpcSslVerifyDepth, gunzip, gunzipBuffers, gzip, gzipBuffers, gzipCompLevel, gzipDisable, gzipHttpVersion, gzipMinLength, gzipProxied, gzipStatic, gzipTypes, gzipVary, healthCheck, hls, hlsBuffers, hlsForwardArgs, hlsFragment, hlsMp4BufferSize, hlsMp4MaxBufferSize, http2ChunkSize, http2Push, http2PushPreload, ifModifiedSince, imageFilter, imageFilterBuffer, imageFilterInterlace, imageFilterJpegQuality, imageFilterSharpen, imageFilterTransparency, imageFilterWebpQuality, index, internal, jsBodyFilter, jsContent, jsFetchCiphers, jsFetchProtocols, jsFetchTrustedCertificate, jsFetchVerifyDepth, jsHeaderFilter, keepaliveDisable, keepaliveRequests, keepaliveTime, keepaliveTimeout, limitConn, limitConnDryRun, limitConnLogLevel, limitConnStatus, limitExcept, limitRate, limitRateAfter, limitReq, limitReqDryRun, limitReqLogLevel, limitReqStatus, lingeringClose, lingeringTime, lingeringTimeout, locationIf, logNotFound, logSubrequest, maxRanges, memcachedBind, memcachedBufferSize, memcachedConnectTimeout, memcachedForceRanges, memcachedGzipFlag, memcachedNextUpstream, memcachedNextUpstreamTimeout, memcachedNextUpstreamTries, memcachedPass, memcachedReadTimeout, memcachedSendTimeout, memcachedSocketKeepalive, minDeleteDepth, mirror, mirrorRequestBody, modernBrowser, modernBrowserValue, mp4BufferSize, mp4LimitRate, mp4LimitRateAfter, mp4MaxBufferSize, mp4MaxBufferSize, mp4StartKeyFrame, mp4, msiePadding, msieRefresh, openFileCache, openFileCacheErrors, openFileCacheMinUses, openFileCacheValid, openLogFileCache, outputBuffers, overrideCharset, perl, portInRedirect, postponeOutput, proxyBind, proxyBuffering, proxyBuffers, proxyBufferSize, proxyBusyBuffersSize, proxyCache, proxyCacheBackgroundUpdate, proxyCacheBypass, proxyCacheConvertHead, proxyCacheKey, proxyCacheLock, proxyCacheLockAge, proxyCacheLockTimeout, proxyCacheMaxRangeOffset, proxyCacheMethods, proxyCacheMinUses, proxyCachePurge, proxyCacheRevalidate, proxyCacheUseStale, proxyCacheValid, proxyConnectTimeout, proxyCookieDomain, proxyCookieFlags, proxyCookiePath, proxyForceRanges, proxyHeadersHashBucketSize, proxyHeadersHashMaxSize, proxyHideHeader, proxyHttpVersion, proxyIgnoreClientAbort, proxyIgnoreHeaders, proxyInterceptErrors, proxyLimitRate, proxyMaxTempFileSize, proxyMethod, proxyNextUpstream, proxyNextUpstreamTimeout, proxyNextUpstreamTries, proxyNoCache, proxyPass, proxyPassHeader, proxyPassRequestBody, proxyPassRequestHeaders, proxyReadTimeout, proxyRedirect, proxyRequestBuffering, proxySendLowat, proxySendTimeout, proxySetBody, proxySetHeader, proxySocketKeepalive, proxySslCertificate, proxySslCertificateKey, proxySslCiphers, proxySslConfCommand, proxySslCrl, proxySslName, proxySslPasswordFile, proxySslProtocols, proxySslServerName, proxySslSessionReuse, proxySslTrustedCertificate, proxySslVerify, proxySslVerifyDepth, proxyStore, proxyStoreAccess, proxyTempFileWriteSize, proxyTempPath, randomIndex, readAhead, realIpHeader, realIpRecursive, recursiveErrorPages, refererHashBucketSize, refererHashMaxSize, resetTimedoutConnection, resolver, resolverTimeout, rewrite, rewriteLog, root, satisfy, scgiBind, scgiBuffering, scgiBuffers, scgiBufferSize, scgiBusyBuffersSize, scgiCache, scgiCacheBackgroundUpdate, scgiCacheBypass, scgiCacheKey, scgiCacheLock, scgiCacheLockAge, scgiCacheLockTimeout, scgiCacheMaxRangeOffset, scgiCacheMethods, scgiCacheMinUses, scgiCachePurge, scgiCacheRevalidate, scgiCacheUseStale, scgiCacheValid, scgiConnectTimeout, scgiForceRanges, scgiHideHeader, scgiIgnoreClientAbort, scgiIgnoreHeaders, scgiInterceptErrors, scgiLimitRate, scgiMaxTempFileSize, scgiNextUpstream, scgiNextUpstreamTimeout, scgiNextUpstreamTries, scgiNoCache, scgiParam, scgiPass, scgiPassHeader, scgiPassRequestBody, scgiPassRequestHeaders, scgiReadTimeout, scgiRequestBuffering, scgiSendTimeout, scgiSocketKeepalive, scgiStore, scgiStoreAccess, scgiTempFileWriteSize, scgiTempPath, secureLink, secureLinkMd5, secureLinkSecret, sendfile, sendfileMaxChunk, sendLowat, sendTimeout, serverNameInRedirect, serverTokens, sessionLog, set, setRealIpFrom, slice, sourceCharset, spdyChunkSize, ssi, ssiLastModified, ssiMinFileChunk, ssiSilentErrors, ssiTypes, ssiValueLength, statusZone, stubStatus, subFilter, subFilterLastModified, subFilterOnce, subFilterTypes, subrequestOutputBufferSize, tcpNodelay, tcpNopush, tryFiles, types, typesHashBucketSize, typesHashMaxSize, uninitializedVariableWarn, upstreamConf, userid, useridDomain, useridFlags, useridMark, useridName, useridP3P, useridPath, useridService, uwsgiBind, uwsgiBuffering, uwsgiBuffers, uwsgiBufferSize, uwsgiBusyBuffersSize, uwsgiCache, uwsgiCacheBackgroundUpdate, uwsgiCacheBypass, uwsgiCacheKey, uwsgiCacheLock, uwsgiCacheLockAge, uwsgiCacheLockTimeout, uwsgiCacheMaxRangeOffset, uwsgiCacheMethods, uwsgiCacheMinUses, uwsgiCachePurge, uwsgiCacheRevalidate, uwsgiCacheUseStale, uwsgiCacheValid, uwsgiConnectTimeout, uwsgiForceRanges, uwsgiHideHeader, uwsgiIgnoreClientAbort, uwsgiIgnoreHeaders, uwsgiInterceptErrors, uwsgiLimitRate, uwsgiMaxTempFileSize, uwsgiModifier1, uwsgiModifier2, uwsgiNextUpstream, uwsgiNextUpstreamTimeout, uwsgiNextUpstreamTries, uwsgiNoCache, uwsgiParam, uwsgiPass, uwsgiPassHeader, uwsgiPassRequestBody, uwsgiPassRequestHeaders, uwsgiReadTimeout, uwsgiRequestBuffering, uwsgiSendTimeout, uwsgiSocketKeepalive, uwsgiSslCertificate, uwsgiSslCertificateKey, uwsgiSslCiphers, uwsgiSslConfCommand, uwsgiSslCrl, uwsgiSslName, uwsgiSslPasswordFile, uwsgiSslProtocols, uwsgiSslServerName, uwsgiSslSessionReuse, uwsgiSslTrustedCertificate, uwsgiSslVerify, uwsgiSslVerifyDepth, uwsgiStore, uwsgiStoreAccess, uwsgiTempFileWriteSize, uwsgiTempPath, validReferers, xmlEntities, xsltLastModified, xsltParam, xsltStringParam, xsltStylesheet, xsltTypes, ) ) val listen = Directive( "listen", defaultValue = "*:80 | *:8000" ) val serverName = Directive( "server_name", defaultValue = "" ) val server = Directive( "server", children = setOf( `break`, `if`, `return`, absoluteRedirect, accessLog, addAfterBody, addBeforeBody, addHeader, additionTypes, addTrailer, aio, aioWrite, allow, ancientBrowser, ancientBrowserValue, authBasic, authBasicUserFile, authDelay, authJwt, authJwtKeyFile, authJwtKeyRequest, authJwtLeeway, authJwtRequire, authJwtType, authRequest, authRequestSet, autoindex, autoindexExactSize, autoindexFormat, autoindexLocaltime, charset, charsetTypes, chunkedTransferEncoding, clientBodyBufferSize, clientBodyInFileOnly, clientBodyInSingleBuffer, clientBodyTempPath, clientBodyTimeout, clientHeaderBufferSize, clientHeaderTimeout, clientMaxBodySize, connectionPoolSize, createFullPutPath, davAccess, davMethods, defaultType, deny, directio, directioAlignment, disableSymlinks, errorLog, errorPage, etag, expires, f4FBufferSize, fastcgiBind, fastcgiBuffering, fastcgiBuffers, fastcgiBufferSize, fastcgiBusyBuffersSize, fastcgiCache, fastcgiCacheBackgroundUpdate, fastcgiCacheBypass, fastcgiCacheKey, fastcgiCacheLock, fastcgiCacheLockAge, fastcgiCacheLockTimeout, fastcgiCacheMaxRangeOffset, fastcgiCacheMethods, fastcgiCacheMinUses, fastcgiCachePurge, fastcgiCacheRevalidate, fastcgiCacheUseStale, fastcgiCacheValid, fastcgiCatchStderr, fastcgiConnectTimeout, fastcgiForceRanges, fastcgiHideHeader, fastcgiIgnoreClientAbort, fastcgiIgnoreHeaders, fastcgiIndex, fastcgiInterceptErrors, fastcgiKeepConn, fastcgiLimitRate, fastcgiMaxTempFileSize, fastcgiNextUpstream, fastcgiNextUpstreamTimeout, fastcgiNextUpstreamTries, fastcgiNoCache, fastcgiParam, fastcgiPassHeader, fastcgiPassRequestBody, fastcgiPassRequestHeaders, fastcgiReadTimeout, fastcgiRequestBuffering, fastcgiSendLowat, fastcgiSendTimeout, fastcgiSocketKeepalive, fastcgiStore, fastcgiStoreAccess, fastcgiTempFileWriteSize, fastcgiTempPath, grpcBind, grpcBufferSize, grpcConnectTimeout, grpcHideHeader, grpcIgnoreHeaders, grpcInterceptErrors, grpcNextUpstream, grpcNextUpstreamTimeout, grpcNextUpstreamTries, grpcSetHeader, grpcSocketKeepalive, grpcSslCertificate, grpcSslCertificateKey, grpcSslCiphers, grpcSslConfCommand, grpcSslCrl, grpcSslName, grpcSslPasswordFile, grpcSslProtocols, grpcSslServerName, grpcSslSessionReuse, grpcSslTrustedCertificate, grpcSslVerify, grpcSslVerifyDepth, gunzip, gunzipBuffers, gzip, gzipBuffers, gzipCompLevel, gzipDisable, gzipHttpVersion, gzipMinLength, gzipProxied, gzipStatic, gzipTypes, gzipVary, hlsBuffers, hlsForwardArgs, hlsFragment, hlsMp4BufferSize, hlsMp4MaxBufferSize, http2BodyPrereadSize, http2ChunkSize, http2IdleTimeout, http2MaxConcurrentPushes, http2MaxConcurrentStreams, http2MaxFieldSize, http2MaxHeaderSize, http2MaxRequests, http2Push, http2PushPreload, http2RecvTimeout, ifModifiedSince, ignoreInvalidHeaders, imageFilterBuffer, imageFilterInterlace, imageFilterJpegQuality, imageFilterSharpen, imageFilterTransparency, imageFilterWebpQuality, index, jsFetchCiphers, jsFetchProtocols, jsFetchTrustedCertificate, jsFetchVerifyDepth, keepaliveDisable, keepaliveRequests, keepaliveTime, keepaliveTimeout, largeClientHeaderBuffers, limitConn, limitConnDryRun, limitConnLogLevel, limitConnStatus, limitRate, limitRateAfter, limitReq, limitReqDryRun, limitReqLogLevel, limitReqStatus, lingeringClose, lingeringTime, lingeringTimeout, listen, location, logNotFound, logSubrequest, maxErrors, maxRanges, memcachedBind, memcachedBufferSize, memcachedConnectTimeout, memcachedForceRanges, memcachedGzipFlag, memcachedNextUpstream, memcachedNextUpstreamTimeout, memcachedNextUpstreamTries, memcachedReadTimeout, memcachedSendTimeout, memcachedSocketKeepalive, mergeSlashes, minDeleteDepth, mirror, mirrorRequestBody, modernBrowser, modernBrowserValue, mp4BufferSize, mp4LimitRate, mp4LimitRateAfter, mp4MaxBufferSize, mp4StartKeyFrame, msiePadding, msieRefresh, openFileCache, openFileCacheErrors, openFileCacheMinUses, openFileCacheValid, openLogFileCache, outputBuffers, overrideCharset, portInRedirect, postponeOutput, protocol, proxyBind, proxyBuffering, proxyBuffers, proxyBufferSize, proxyBusyBuffersSize, proxyCache, proxyCacheBackgroundUpdate, proxyCacheBypass, proxyCacheConvertHead, proxyCacheKey, proxyCacheLock, proxyCacheLockAge, proxyCacheLockTimeout, proxyCacheMaxRangeOffset, proxyCacheMethods, proxyCacheMinUses, proxyCachePurge, proxyCacheRevalidate, proxyCacheUseStale, proxyCacheValid, proxyConnectTimeout, proxyCookieDomain, proxyCookieFlags, proxyCookiePath, proxyForceRanges, proxyHeadersHashBucketSize, proxyHeadersHashMaxSize, proxyHideHeader, proxyHttpVersion, proxyIgnoreClientAbort, proxyIgnoreHeaders, proxyInterceptErrors, proxyLimitRate, proxyMaxTempFileSize, proxyMethod, proxyNextUpstream, proxyNextUpstreamTimeout, proxyNextUpstreamTries, proxyNoCache, proxyPassHeader, proxyPassRequestBody, proxyPassRequestHeaders, proxyReadTimeout, proxyRedirect, proxyRequestBuffering, proxySendLowat, proxySendTimeout, proxySetBody, proxySetHeader, proxySocketKeepalive, proxySslCertificate, proxySslCertificateKey, proxySslCiphers, proxySslConfCommand, proxySslCrl, proxySslName, proxySslPasswordFile, proxySslProtocols, proxySslServerName, proxySslSessionReuse, proxySslTrustedCertificate, proxySslVerify, proxySslVerifyDepth, proxyStore, proxyStoreAccess, proxyTempFileWriteSize, proxyTempPath, readAhead, realIpHeader, realIpRecursive, recursiveErrorPages, refererHashBucketSize, refererHashMaxSize, requestPoolSize, resetTimedoutConnection, resolver, resolverTimeout, rewrite, rewriteLog, root, satisfy, scgiBind, scgiBuffering, scgiBuffers, scgiBufferSize, scgiBusyBuffersSize, scgiCache, scgiCacheBackgroundUpdate, scgiCacheBypass, scgiCacheKey, scgiCacheLock, scgiCacheLockAge, scgiCacheLockTimeout, scgiCacheMaxRangeOffset, scgiCacheMethods, scgiCacheMinUses, scgiCachePurge, scgiCacheRevalidate, scgiCacheUseStale, scgiCacheValid, scgiConnectTimeout, scgiForceRanges, scgiHideHeader, scgiIgnoreClientAbort, scgiIgnoreHeaders, scgiInterceptErrors, scgiLimitRate, scgiMaxTempFileSize, scgiNextUpstream, scgiNextUpstreamTimeout, scgiNextUpstreamTries, scgiNoCache, scgiParam, scgiPassHeader, scgiPassRequestBody, scgiPassRequestHeaders, scgiReadTimeout, scgiRequestBuffering, scgiSendTimeout, scgiSocketKeepalive, scgiStore, scgiStoreAccess, scgiTempFileWriteSize, scgiTempPath, secureLink, secureLinkMd5, sendfile, sendfileMaxChunk, sendLowat, sendTimeout, serverName, serverNameInRedirect, serverTokens, sessionLog, set, setRealIpFrom, slice, sourceCharset, spdyChunkSize, spdyHeadersComp, ssi, ssiLastModified, ssiMinFileChunk, ssiSilentErrors, ssiTypes, ssiValueLength, ssl, sslBufferSize, sslCertificate, sslCertificateKey, sslCiphers, sslClientCertificate, sslConfCommand, sslCrl, sslDhparam, sslEarlyData, sslEcdhCurve, sslOcsp, sslOcspCache, sslOcspResponder, sslPasswordFile, sslPreferServerCiphers, sslProtocols, sslRejectHandshake, sslSessionCache, sslSessionTicketKey, sslSessionTickets, sslSessionTimeout, sslStapling, sslStaplingFile, sslStaplingResponder, sslStaplingVerify, sslTrustedCertificate, sslVerifyClient, sslVerifyDepth, statusZone, stubStatus, subFilter, subFilterLastModified, subFilterOnce, subFilterTypes, subrequestOutputBufferSize, tcpNodelay, tcpNopush, timeout, tryFiles, types, typesHashBucketSize, typesHashMaxSize, underscoresInHeaders, uninitializedVariableWarn, userid, useridDomain, useridFlags, useridMark, useridName, useridP3P, useridPath, useridService, uwsgiBind, uwsgiBuffering, uwsgiBuffers, uwsgiBufferSize, uwsgiBusyBuffersSize, uwsgiCache, uwsgiCacheBackgroundUpdate, uwsgiCacheBypass, uwsgiCacheKey, uwsgiCacheLock, uwsgiCacheLockAge, uwsgiCacheLockTimeout, uwsgiCacheMaxRangeOffset, uwsgiCacheMethods, uwsgiCacheMinUses, uwsgiCachePurge, uwsgiCacheRevalidate, uwsgiCacheUseStale, uwsgiCacheValid, uwsgiConnectTimeout, uwsgiForceRanges, uwsgiHideHeader, uwsgiIgnoreClientAbort, uwsgiIgnoreHeaders, uwsgiInterceptErrors, uwsgiLimitRate, uwsgiMaxTempFileSize, uwsgiModifier1, uwsgiModifier2, uwsgiNextUpstream, uwsgiNextUpstreamTimeout, uwsgiNextUpstreamTries, uwsgiNoCache, uwsgiParam, uwsgiPassHeader, uwsgiPassRequestBody, uwsgiPassRequestHeaders, uwsgiReadTimeout, uwsgiRequestBuffering, uwsgiSendTimeout, uwsgiSocketKeepalive, uwsgiSslCertificate, uwsgiSslCertificateKey, uwsgiSslCiphers, uwsgiSslConfCommand, uwsgiSslCrl, uwsgiSslName, uwsgiSslPasswordFile, uwsgiSslProtocols, uwsgiSslServerName, uwsgiSslSessionReuse, uwsgiSslTrustedCertificate, uwsgiSslVerify, uwsgiSslVerifyDepth, uwsgiStore, uwsgiStoreAccess, uwsgiTempFileWriteSize, uwsgiTempPath, validReferers, xmlEntities, xsltLastModified, xsltParam, xsltStringParam, xsltTypes, ) ) val http = Directive( "http", children = setOf( absoluteRedirect, accessLog, addAfterBody, addBeforeBody, addHeader, additionTypes, addTrailer, aio, aioWrite, allow, ancientBrowser, ancientBrowserValue, authBasic, authBasicUserFile, authDelay, authJwt, authJwtClaimSet, authJwtHeaderSet, authJwtKeyFile, authJwtKeyRequest, authJwtLeeway, authJwtRequire, authJwtType, authRequest, authRequestSet, autoindex, autoindexExactSize, autoindexFormat, autoindexLocaltime, charset, charsetMap, charsetTypes, chunkedTransferEncoding, clientBodyBufferSize, clientBodyInFileOnly, clientBodyInSingleBuffer, clientBodyTempPath, clientBodyTimeout, clientHeaderBufferSize, clientHeaderTimeout, clientMaxBodySize, connectionPoolSize, createFullPutPath, davAccess, davMethods, defaultType, deny, directio, directioAlignment, disableSymlinks, errorLog, errorPage, etag, expires, f4FBufferSize, fastcgiBind, fastcgiBuffering, fastcgiBuffers, fastcgiBufferSize, fastcgiBusyBuffersSize, fastcgiCache, fastcgiCacheBackgroundUpdate, fastcgiCacheBypass, fastcgiCacheKey, fastcgiCacheLock, fastcgiCacheLockAge, fastcgiCacheLockTimeout, fastcgiCacheMaxRangeOffset, fastcgiCacheMethods, fastcgiCacheMinUses, fastcgiCachePath, fastcgiCachePurge, fastcgiCacheRevalidate, fastcgiCacheUseStale, fastcgiCacheValid, fastcgiCatchStderr, fastcgiConnectTimeout, fastcgiForceRanges, fastcgiHideHeader, fastcgiIgnoreClientAbort, fastcgiIgnoreHeaders, fastcgiIndex, fastcgiInterceptErrors, fastcgiKeepConn, fastcgiLimitRate, fastcgiMaxTempFileSize, fastcgiNextUpstream, fastcgiNextUpstreamTimeout, fastcgiNextUpstreamTries, fastcgiNoCache, fastcgiParam, fastcgiPassHeader, fastcgiPassRequestBody, fastcgiPassRequestHeaders, fastcgiReadTimeout, fastcgiRequestBuffering, fastcgiSendLowat, fastcgiSendTimeout, fastcgiSocketKeepalive, fastcgiStore, fastcgiStoreAccess, fastcgiTempFileWriteSize, fastcgiTempPath, geo, geoipCity, geoipCountry, geoipOrg, geoipProxy, geoipProxyRecursive, grpcBind, grpcBufferSize, grpcConnectTimeout, grpcHideHeader, grpcIgnoreHeaders, grpcInterceptErrors, grpcNextUpstream, grpcNextUpstreamTimeout, grpcNextUpstreamTries, grpcSetHeader, grpcSocketKeepalive, grpcSslCertificate, grpcSslCertificateKey, grpcSslCiphers, grpcSslConfCommand, grpcSslCrl, grpcSslName, grpcSslPasswordFile, grpcSslProtocols, grpcSslServerName, grpcSslSessionReuse, grpcSslTrustedCertificate, grpcSslVerify, grpcSslVerifyDepth, gunzip, gunzipBuffers, gzip, gzipBuffers, gzipCompLevel, gzipDisable, gzipHttpVersion, gzipMinLength, gzipProxied, gzipStatic, gzipTypes, gzipVary, hlsBuffers, hlsForwardArgs, hlsFragment, hlsMp4BufferSize, hlsMp4MaxBufferSize, http2BodyPrereadSize, http2ChunkSize, http2IdleTimeout, http2MaxConcurrentPushes, http2MaxConcurrentStreams, http2MaxFieldSize, http2MaxHeaderSize, http2MaxRequests, http2Push, http2PushPreload, http2RecvBufferSize, http2RecvTimeout, ifModifiedSince, ignoreInvalidHeaders, imageFilterBuffer, imageFilterInterlace, imageFilterJpegQuality, imageFilterSharpen, imageFilterTransparency, imageFilterWebpQuality, index, jsFetchCiphers, jsFetchProtocols, jsFetchTrustedCertificate, jsFetchVerifyDepth, jsImport, jsInclude, jsPath, jsSet, jsVar, keepaliveDisable, keepaliveRequests, keepaliveTime, keepaliveTimeout, keyval, keyvalZone, largeClientHeaderBuffers, limitConn, limitConnDryRun, limitConnLogLevel, limitConnStatus, limitConnZone, limitRate, limitRateAfter, limitReq, limitReqDryRun, limitReqLogLevel, limitReqStatus, limitReqZone, limitZone, lingeringClose, lingeringTime, lingeringTimeout, logFormat, logNotFound, logSubrequest, map, mapHashBucketSize, mapHashMaxSize, match, maxRanges, memcachedBind, memcachedBufferSize, memcachedConnectTimeout, memcachedForceRanges, memcachedGzipFlag, memcachedNextUpstream, memcachedNextUpstreamTimeout, memcachedNextUpstreamTries, memcachedReadTimeout, memcachedSendTimeout, memcachedSocketKeepalive, mergeSlashes, minDeleteDepth, mirror, mirrorRequestBody, modernBrowser, modernBrowserValue, mp4BufferSize, mp4LimitRate, mp4LimitRateAfter, mp4MaxBufferSize, mp4StartKeyFrame, msiePadding, msieRefresh, openFileCache, openFileCacheErrors, openFileCacheMinUses, openFileCacheValid, openLogFileCache, outputBuffers, overrideCharset, perlModules, perlRequire, perlSet, portInRedirect, postponeOutput, proxyBind, proxyBuffering, proxyBuffers, proxyBufferSize, proxyBusyBuffersSize, proxyCache, proxyCacheBackgroundUpdate, proxyCacheBypass, proxyCacheConvertHead, proxyCacheKey, proxyCacheLock, proxyCacheLockAge, proxyCacheLockTimeout, proxyCacheMaxRangeOffset, proxyCacheMethods, proxyCacheMinUses, proxyCachePath, proxyCachePurge, proxyCacheRevalidate, proxyCacheUseStale, proxyCacheValid, proxyConnectTimeout, proxyCookieDomain, proxyCookieFlags, proxyCookiePath, proxyForceRanges, proxyHeadersHashBucketSize, proxyHeadersHashMaxSize, proxyHideHeader, proxyHttpVersion, proxyIgnoreClientAbort, proxyIgnoreHeaders, proxyInterceptErrors, proxyLimitRate, proxyMaxTempFileSize, proxyMethod, proxyNextUpstream, proxyNextUpstreamTimeout, proxyNextUpstreamTries, proxyNoCache, proxyPassHeader, proxyPassRequestBody, proxyPassRequestHeaders, proxyReadTimeout, proxyRedirect, proxyRequestBuffering, proxySendLowat, proxySendTimeout, proxySetBody, proxySetHeader, proxySocketKeepalive, proxySslCertificate, proxySslCertificateKey, proxySslCiphers, proxySslConfCommand, proxySslCrl, proxySslName, proxySslPasswordFile, proxySslProtocols, proxySslServerName, proxySslSessionReuse, proxySslTrustedCertificate, proxySslVerify, proxySslVerifyDepth, proxyStore, proxyStoreAccess, proxyTempFileWriteSize, proxyTempPath, readAhead, realIpHeader, realIpRecursive, recursiveErrorPages, requestPoolSize, resetTimedoutConnection, resolver, resolverTimeout, rewriteLog, root, satisfy, scgiBind, scgiBuffering, scgiBuffers, scgiBufferSize, scgiBusyBuffersSize, scgiCache, scgiCacheBackgroundUpdate, scgiCacheBypass, scgiCacheKey, scgiCacheLock, scgiCacheLockAge, scgiCacheLockTimeout, scgiCacheMaxRangeOffset, scgiCacheMethods, scgiCacheMinUses, scgiCachePath, scgiCachePurge, scgiCacheRevalidate, scgiCacheUseStale, scgiCacheValid, scgiConnectTimeout, scgiForceRanges, scgiHideHeader, scgiIgnoreClientAbort, scgiIgnoreHeaders, scgiInterceptErrors, scgiLimitRate, scgiMaxTempFileSize, scgiNextUpstream, scgiNextUpstreamTimeout, scgiNextUpstreamTries, scgiNoCache, scgiParam, scgiPassHeader, scgiPassRequestBody, scgiPassRequestHeaders, scgiReadTimeout, scgiRequestBuffering, scgiSendTimeout, scgiSocketKeepalive, scgiStore, scgiStoreAccess, scgiTempFileWriteSize, scgiTempPath, secureLink, secureLinkMd5, sendfile, sendfileMaxChunk, sendLowat, sendTimeout, server, serverNameInRedirect, serverNamesHashBucketSize, serverNamesHashMaxSize, serverTokens, sessionLog, sessionLogFormat, sessionLogZone, setRealIpFrom, slice, sourceCharset, spdyChunkSize, spdyHeadersComp, splitClients, ssi, ssiLastModified, ssiMinFileChunk, ssiSilentErrors, ssiTypes, ssiValueLength, ssl, sslBufferSize, sslCertificate, sslCertificateKey, sslCiphers, sslClientCertificate, sslConfCommand, sslCrl, sslDhparam, sslEarlyData, sslEcdhCurve, sslOcsp, sslOcspCache, sslOcspResponder, sslPasswordFile, sslPreferServerCiphers, sslProtocols, sslRejectHandshake, sslSessionCache, sslSessionTicketKey, sslSessionTickets, sslSessionTimeout, sslStapling, sslStaplingFile, sslStaplingResponder, sslStaplingVerify, sslTrustedCertificate, sslVerifyClient, sslVerifyDepth, subFilter, subFilterLastModified, subFilterOnce, subFilterTypes, subrequestOutputBufferSize, tcpNodelay, tcpNopush, types, typesHashBucketSize, typesHashMaxSize, underscoresInHeaders, uninitializedVariableWarn, upstream, userid, useridDomain, useridFlags, useridMark, useridName, useridP3P, useridPath, useridService, uwsgiBind, uwsgiBuffering, uwsgiBuffers, uwsgiBufferSize, uwsgiBusyBuffersSize, uwsgiCache, uwsgiCacheBackgroundUpdate, uwsgiCacheBypass, uwsgiCacheKey, uwsgiCacheLock, uwsgiCacheLockAge, uwsgiCacheLockTimeout, uwsgiCacheMaxRangeOffset, uwsgiCacheMethods, uwsgiCacheMinUses, uwsgiCachePath, uwsgiCachePurge, uwsgiCacheRevalidate, uwsgiCacheUseStale, uwsgiCacheValid, uwsgiConnectTimeout, uwsgiForceRanges, uwsgiHideHeader, uwsgiIgnoreClientAbort, uwsgiIgnoreHeaders, uwsgiInterceptErrors, uwsgiLimitRate, uwsgiMaxTempFileSize, uwsgiModifier1, uwsgiModifier2, uwsgiNextUpstream, uwsgiNextUpstreamTimeout, uwsgiNextUpstreamTries, uwsgiNoCache, uwsgiParam, uwsgiPassHeader, uwsgiPassRequestBody, uwsgiPassRequestHeaders, uwsgiReadTimeout, uwsgiRequestBuffering, uwsgiSendTimeout, uwsgiSocketKeepalive, uwsgiSslCertificate, uwsgiSslCertificateKey, uwsgiSslCiphers, uwsgiSslConfCommand, uwsgiSslCrl, uwsgiSslName, uwsgiSslPasswordFile, uwsgiSslProtocols, uwsgiSslServerName, uwsgiSslSessionReuse, uwsgiSslTrustedCertificate, uwsgiSslVerify, uwsgiSslVerifyDepth, uwsgiStore, uwsgiStoreAccess, uwsgiTempFileWriteSize, uwsgiTempPath, variablesHashBucketSize, variablesHashMaxSize, xmlEntities, xsltLastModified, xsltParam, xsltStringParam, xsltTypes, ) ) val ngx_http_core_module = Module( "ngx_http_core_module", enabled=true, directives = setOf( absoluteRedirect, aio, aioWrite, alias, authDelay, chunkedTransferEncoding, clientBodyBufferSize, clientBodyInFileOnly, clientBodyInSingleBuffer, clientBodyTempPath, clientBodyTimeout, clientHeaderBufferSize, clientHeaderTimeout, clientMaxBodySize, connectionPoolSize, defaultType, directio, directioAlignment, disableSymlinks, errorPage, etag, http, ifModifiedSince, ignoreInvalidHeaders, internal, keepaliveDisable, keepaliveRequests, keepaliveTime, keepaliveTimeout, largeClientHeaderBuffers, limitExcept, limitRate, limitRateAfter, lingeringClose, lingeringTime, lingeringTimeout, listen, location, logNotFound, logSubrequest, maxErrors, maxRanges, mergeSlashes, msiePadding, msieRefresh, openFileCache, openFileCacheErrors, openFileCacheMinUses, openFileCacheValid, outputBuffers, portInRedirect, postponeOutput, protocol, readAhead, recursiveErrorPages, requestPoolSize, resetTimedoutConnection, resolver, resolverTimeout, root, satisfy, sendfile, sendfileMaxChunk, sendLowat, sendTimeout, server, serverName, serverNameInRedirect, serverNamesHashBucketSize, serverNamesHashMaxSize, serverTokens, subrequestOutputBufferSize, tcpNodelay, tcpNopush, timeout, tryFiles, types, typesHashBucketSize, typesHashMaxSize, underscoresInHeaders, variablesHashBucketSize, variablesHashMaxSize, ) )
8
Kotlin
6
50
1d7460d1403c331a44358d051e3bd3a26f5fc198
45,654
nginx-intellij-plugin
MIT License
App/Study_Demo/StarDrawing/app/src/main/java/com/example/stardrawing/tool/activitytool/StatusBar.kt
TIMAVICIIX
608,668,001
false
{"Kotlin": 63522, "Classic ASP": 59330, "Java": 41124, "C#": 34974, "Python": 29197, "C": 25644, "HTML": 22409, "C++": 16172, "JavaScript": 7629, "CSS": 4407}
package com.example.stardrawing.tool.activitytool import android.app.Activity import android.os.Build import android.view.View import android.view.WindowManager @Suppress("DEPRECATION") class StatusBar(activity: Activity) { private val activity: Activity init { this.activity = activity } fun setColor(tempColor: Int) { if (Build.VERSION.SDK_INT >= 21) { val view = activity.window.decorView view.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE activity.window.statusBarColor = activity.resources.getColor(tempColor) } } fun hideTitle() { if (Build.VERSION.SDK_INT >= 21) { activity.window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ) } } fun hideAll() { if ((Build.VERSION.SDK_INT > 11) && (Build.VERSION.SDK_INT < 19)) { val v = activity.window.decorView v.systemUiVisibility = View.GONE } else if (Build.VERSION.SDK_INT >= 19) { val decor = activity.window.decorView decor.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY } } fun setTextColor(isDarkBackground: Boolean) { val decor = activity.window.decorView if (isDarkBackground) { decor.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE } else { decor.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } } }
0
Kotlin
0
1
150af9ab922dbe77064176f97e618d73825e175e
2,026
TimData
MIT License
project-system-gradle/testSrc/com/android/tools/idea/ui/resourcemanager/importer/runsGradle/DefaultResDirectoryTest.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.ui.resourcemanager.importer.runsGradle import com.android.tools.idea.gradle.project.sync.snapshots.AndroidCoreTestProject import com.android.tools.idea.gradle.project.sync.snapshots.TestProjectDefinition.Companion.prepareTestProject import com.android.tools.idea.testing.AndroidProjectRule import com.android.tools.idea.testing.findAppModule import com.android.tools.idea.ui.resourcemanager.importer.getOrCreateDefaultResDirectory import com.android.tools.idea.util.androidFacet import com.google.common.truth.Truth.assertThat import com.intellij.testFramework.RunsInEdt import org.junit.Rule import org.junit.Test import java.io.File @RunsInEdt class DefaultResDirectoryTest { @get:Rule val projectRule = AndroidProjectRule.withIntegrationTestEnvironment() @Test fun testGetOrCreateDefaultResDirectoryExists() { val preparedProject = projectRule.prepareTestProject(AndroidCoreTestProject.SIMPLE_APPLICATION) assertThat(preparedProject.root.resolve("app/src/main/res").exists()).isTrue() preparedProject.open { p -> val facet = p.findAppModule().androidFacet!! val dir = getOrCreateDefaultResDirectory(facet) assertThat(dir.exists()).isTrue() assertThat(dir.isDirectory).isTrue() assertThat(dir.relativeTo(preparedProject.root)).isEqualTo(File("app/src/main/res")) } } @Test fun testGetOrCreateDefaultResDirectoryCreate() { val preparedProject = projectRule.prepareTestProject(AndroidCoreTestProject.SIMPLE_APPLICATION) assertThat(preparedProject.root.resolve("app/src/main/res").exists()).isTrue() assertThat(preparedProject.root.resolve("app/src/main/res").deleteRecursively()).isTrue() preparedProject.open { p -> val facet = p.findAppModule().androidFacet!! val dir = getOrCreateDefaultResDirectory(facet) assertThat(dir.exists()).isTrue() assertThat(dir.isDirectory).isTrue() assertThat(dir.relativeTo(preparedProject.root)).isEqualTo(File("app/src/main/res")) } } }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
2,638
android
Apache License 2.0