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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/events/CfnRuleKinesisParametersPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.events
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.services.events.CfnRule
/**
* This object enables you to specify a JSON path to extract from the event and use as the partition
* key for the Amazon Kinesis data stream, so that you can control the shard to which the event goes.
*
* If you do not include this parameter, the default is to use the `eventId` as the partition key.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.events.*;
* KinesisParametersProperty kinesisParametersProperty = KinesisParametersProperty.builder()
* .partitionKeyPath("partitionKeyPath")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-events-rule-kinesisparameters.html)
*/
@CdkDslMarker
public class CfnRuleKinesisParametersPropertyDsl {
private val cdkBuilder: CfnRule.KinesisParametersProperty.Builder =
CfnRule.KinesisParametersProperty.builder()
/**
* @param partitionKeyPath The JSON path to be extracted from the event and used as the partition
* key.
* For more information, see [Amazon Kinesis Streams Key
* Concepts](https://docs.aws.amazon.com/streams/latest/dev/key-concepts.html#partition-key) in the
* *Amazon Kinesis Streams Developer Guide* .
*/
public fun partitionKeyPath(partitionKeyPath: String) {
cdkBuilder.partitionKeyPath(partitionKeyPath)
}
public fun build(): CfnRule.KinesisParametersProperty = cdkBuilder.build()
}
| 1 | Kotlin | 0 | 0 | 17c41bdaffb2e10d31b32eb2282b73dd18be09fa | 1,858 | awscdk-dsl-kotlin | Apache License 2.0 |
src/commonMain/kotlin/responses/ItemGenre.kt | MrNuggelz | 866,645,099 | false | {"Kotlin": 132979} | package io.github.mrnuggelz.opensubsonic.responses
import kotlinx.serialization.Serializable
@Serializable
public data class ItemGenre(val name: String)
| 0 | Kotlin | 0 | 1 | 0734cbd098998abd57e9210d93963dd58c1950bc | 155 | OpenSubsonicClient | Apache License 2.0 |
app/src/main/java/com/artbird/onsite/repository/AppointmentRepository.kt | zlkca | 563,099,648 | false | null | package com.artbird.onsite.repository
import com.artbird.onsite.domain.Appointment
import com.artbird.onsite.network.AppointmentApi
import retrofit2.Response
class AppointmentRepository(){
suspend fun getAppointmentsByEmployeeId(accountId: String): Response<List<Appointment>> {
return AppointmentApi.retrofitService.getAppointmentsByEmployeeId(accountId)
}
suspend fun getAppointment(appointmentId: String): Response<Appointment>{
return AppointmentApi.retrofitService.getAppointment(appointmentId)
}
// suspend fun getAppointment(appointmentId: String): Response<Appointment>{
// return AppointmentApi.retrofitService.getAppointment(appointmentId)
// }
//
// suspend fun getAppointment(appointmentId: String): Response<Appointment>{
// return AppointmentApi.retrofitService.getAppointment(appointmentId)
// }
} | 0 | Kotlin | 0 | 0 | 514e5dc00fd80d85faada2a729ffff7204878dbd | 874 | partner-android | MIT License |
RxJava/chapter06/rxAndroid/app/src/main/java/com/leaf/rxandroid/fragments/RecyclerItem.kt | Im-Tae | 260,676,018 | false | null | package com.leaf.rxandroid.fragments
import android.graphics.drawable.Drawable
data class RecyclerItem(var image: Drawable? = null, var title: String? = null) | 0 | Kotlin | 12 | 5 | 819e4234069f03a822f8defa15cc2d37cc58fb25 | 160 | Blog_Example | MIT License |
src/main/kotlin/net/nitrin/network/ChannelHandler.kt | NitrinNET | 536,768,326 | false | null | package net.nitrin.network
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter
import net.nitrin.network.component.ComponentListener
import net.nitrin.network.component.NetworkComponent
/**
* Handles inactivity and exceptions from [NetworkComponent]
*
* @param listener gets notified when event happens
* @param component which to handle
*/
class ChannelHandler(private val listener: ComponentListener, var component: NetworkComponent): ChannelInboundHandlerAdapter() {
override fun channelInactive(context: ChannelHandlerContext) {
val channel = context.channel()
if (channel.isOpen) {
channel.close()
}
listener.disconnect(NetworkContext(component, channel))
}
@Suppress("OVERRIDE_DEPRECATION")
override fun exceptionCaught(context: ChannelHandlerContext, cause: Throwable) {
val channel = context.channel()
if (channel.isOpen) {
channel.close()
}
listener.exception(NetworkContext(component, channel))
}
} | 0 | Kotlin | 0 | 0 | 5882c797f6ff87075aef22527bc01ee1bc79ad9a | 1,072 | nitrin-network | Apache License 2.0 |
components/link-manager/src/main/kotlin/net/corda/p2p/linkmanager/sessions/events/StatefulSessionEventPublisher.kt | corda | 346,070,752 | false | null | package net.corda.p2p.linkmanager.sessions.events
import net.corda.data.p2p.event.SessionCreated
import net.corda.data.p2p.event.SessionDeleted
import net.corda.data.p2p.event.SessionDirection
import net.corda.data.p2p.event.SessionEvent
import net.corda.libs.configuration.SmartConfig
import net.corda.lifecycle.LifecycleCoordinatorFactory
import net.corda.lifecycle.domino.logic.LifecycleWithDominoTile
import net.corda.lifecycle.domino.logic.util.PublisherWithDominoLogic
import net.corda.messaging.api.publisher.config.PublisherConfig
import net.corda.messaging.api.publisher.factory.PublisherFactory
import net.corda.messaging.api.records.Record
import net.corda.schema.Schemas
class StatefulSessionEventPublisher(
coordinatorFactory: LifecycleCoordinatorFactory,
publisherFactory: PublisherFactory,
messagingConfiguration: SmartConfig,
): LifecycleWithDominoTile {
companion object {
private const val CLIENT_ID = "StatefulSessionEventPublisher"
}
private val config = PublisherConfig(CLIENT_ID)
private val publisher = PublisherWithDominoLogic(publisherFactory, coordinatorFactory, config, messagingConfiguration)
fun sessionCreated(key: String, direction: SessionDirection) {
publisher.publish(listOf(Record(Schemas.P2P.SESSION_EVENTS, key, SessionEvent(SessionCreated(direction, key)))))
}
fun sessionDeleted(key: String) {
publisher.publish(listOf(Record(Schemas.P2P.SESSION_EVENTS, key, SessionEvent(SessionDeleted(key)))))
}
override val dominoTile = publisher.dominoTile
} | 32 | null | 25 | 57 | 4c5568483411af5fa31ca995fafdd7aafe378134 | 1,564 | corda-runtime-os | Apache License 2.0 |
src/main/kotlin/com/intellij/plugin/powershell/lang/lsp/languagehost/PowerShellExtensionError.kt | ant-druha | 146,094,753 | false | {"Kotlin": 459218, "PowerShell": 87645, "Java": 33614, "Lex": 20226} | package com.intellij.plugin.powershell.lang.lsp.languagehost
class PowerShellExtensionError(msg: String) : Exception(msg) | 51 | Kotlin | 20 | 72 | 5f73e89df8ca2fb167daf451ad92b507a14352a9 | 122 | intellij-powershell | Apache License 2.0 |
src/main/kotlin/org/arend/typechecking/BinaryFileSaver.kt | i-walker | 237,828,319 | false | {"Gradle Kotlin DSL": 2, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Kotlin": 318, "Java": 3, "XML": 1, "SVG": 14, "HTML": 4, "JFlex": 1} | package org.arend.typechecking
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.psi.PsiManager
import org.arend.library.SourceLibrary
import org.arend.naming.reference.converter.ReferableConverter
import org.arend.psi.ArendFile
import org.arend.typechecking.execution.FullModulePath
class BinaryFileSaver(private val project: Project) {
private val typeCheckingService = project.service<TypeCheckingService>()
private val typecheckedModules = LinkedHashMap<ArendFile, ReferableConverter>()
init {
// TODO: Replace with AsyncFileListener?
project.messageBus.connect().subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
override fun after(events: List<VFileEvent>) {
if (typecheckedModules.isEmpty()) {
return
}
for (event in events) {
val file = (if (event is VFileContentChangeEvent && event.isFromSave) PsiManager.getInstance(project).findFile(event.file) as? ArendFile else null) ?: continue
synchronized(project) {
saveFile(file, typecheckedModules.remove(file) ?: return@synchronized)
}
}
}
})
ProjectManager.getInstance().addProjectManagerListener(project, object : ProjectManagerListener {
override fun projectClosing(closedProject: Project) {
if (closedProject == project) {
saveAll()
}
}
})
}
fun saveFile(file: ArendFile, referableConverter: ReferableConverter) {
val fullName = FullModulePath(file.libraryName ?: return, file.modulePath ?: return)
val library = typeCheckingService.libraryManager.getRegisteredLibrary(fullName.libraryName) as? SourceLibrary ?: return
if (library.supportsPersisting()) {
runReadAction { library.persistModule(fullName.modulePath, referableConverter, typeCheckingService.libraryManager.libraryErrorReporter) }
}
}
fun addToQueue(file: ArendFile, referableConverter: ReferableConverter) {
synchronized(project) {
typecheckedModules[file] = referableConverter
}
}
fun saveAll() {
synchronized(project) {
for (entry in typecheckedModules) {
saveFile(entry.key, entry.value)
}
typecheckedModules.clear()
}
}
} | 1 | null | 1 | 1 | 2d0a859283fac64d05bfd75c7e6a9bafb25eaee6 | 2,923 | intellij-arend | Apache License 2.0 |
converter-binary/app/src/androidTest/java/gparap/apps/converter_binary/MainActivityInstrumentedTest.kt | gparap | 253,560,705 | false | null | /*
* Copyright 2023 gparap
*
* 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 gparap.apps.converter_binary
import android.view.View
import androidx.test.core.app.ActivityScenario
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.RootMatchers.withDecorView
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.rules.ActivityScenarioRule
import org.hamcrest.CoreMatchers.not
import org.junit.Before
import org.junit.Rule
import org.junit.Test
class MainActivityInstrumentedTest {
@get:Rule
val rule: ActivityScenarioRule<MainActivity> = ActivityScenarioRule(MainActivity::class.java)
private var rootView: View? = null
@Before
fun setUp() {
//get main activity decor view
rule.scenario.onActivity { activity -> rootView = activity.window.decorView }
//start main activity
ActivityScenario.launch(MainActivity::class.java)
}
@Test
fun isWidgetVisible_editTextResult() {
onView(withId(R.id.editTextResult)).check(matches(isDisplayed()))
}
@Test
fun isWidgetVisible_buttonConvertToBinary() {
onView(withId(R.id.buttonConvertToBinary)).check(matches(isDisplayed()))
}
@Test
fun isWidgetVisible_buttonConvertToText() {
onView(withId(R.id.buttonConvertToText)).check(matches(isDisplayed()))
}
@Test
fun isWidgetVisible_buttonClear() {
onView(withId(R.id.buttonClear)).check(matches(isDisplayed()))
}
@Test
fun isInputEmpty_Click_buttonConvertToText() {
onView(withId(R.id.buttonClear)).perform(click())
onView(withId(R.id.buttonConvertToText)).perform(click())
onView(withText(R.string.toast_EmptyInput))
.inRoot(withDecorView(not(rootView)))
.check(matches(isDisplayed()))
}
@Test
fun isInputEmpty_Click_buttonConvertToBinary() {
onView(withId(R.id.buttonClear)).perform(click())
onView(withId(R.id.buttonConvertToBinary)).perform(click())
onView(withText(R.string.toast_EmptyInput))
.inRoot(withDecorView(not(rootView)))
.check(matches(isDisplayed()))
}
@Test
fun inputIsNotBinary() {
onView(withId(R.id.editTextResult)).perform(
typeText("!1100111"),
ViewActions.closeSoftKeyboard()
)
onView(withId(R.id.buttonConvertToText)).perform(click())
onView(withText(R.string.toast_WrongInput))
.inRoot(withDecorView(not(rootView)))
.check(matches(isDisplayed()))
}
} | 1 | Kotlin | 1 | 7 | a9bfe524e672fd27de2d6b1a48df778743bdeb47 | 3,323 | android | Apache License 2.0 |
flork-controller-core/src/main/kotlin/com/microfocus/flork/kubernetes/api/v1/reconcilers/utils/FlinkResourceDeploymentMonitor.kt | MicroFocus | 455,642,131 | false | {"Kotlin": 129929, "Java": 66230, "Shell": 11579, "Dockerfile": 997} | /*
* Copyright 2021-2022 Micro Focus or one of its affiliates
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.microfocus.flork.kubernetes.api.v1.reconcilers.utils
import io.fabric8.kubernetes.api.model.apps.Deployment
import io.fabric8.kubernetes.client.informers.ResourceEventHandler
import org.slf4j.LoggerFactory
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
class FlinkResourceDeploymentMonitor(private val namespace: String, private val name: String) : ResourceEventHandler<Deployment> {
companion object {
private val LOG = LoggerFactory.getLogger(FlinkResourceDeploymentMonitor::class.java)
}
val addedFlag = AtomicBoolean(false)
val deletionLatch = AtomicReference(CountDownLatch(1))
override fun onAdd(obj: Deployment?) {
if (addedFlag.compareAndSet(false, true)) {
LOG.info("Flink resource deployment added: {}/{}", namespace, name)
}
}
override fun onUpdate(oldObj: Deployment?, newObj: Deployment?) {
LOG.debug("Flink resource deployment updated: {}/{}", namespace, name)
}
override fun onDelete(obj: Deployment?, deletedFinalStateUnknown: Boolean) {
if (addedFlag.compareAndSet(true, false)) {
LOG.info("Flink resource deployment deleted: {}/{}", namespace, name)
deletionLatch.get().countDown()
}
}
}
| 0 | Kotlin | 1 | 1 | 06755237ce92405fcf24f4382c4e7b837ec19c63 | 1,966 | opsb-flink-k8s-operator | Apache License 2.0 |
src/main/kotlin/online/hudacek/fxradio/media/player/CustomPlayer.kt | joeyboli | 327,092,751 | true | {"Kotlin": 239593, "AppleScript": 1497} | /*
* Copyright 2020 FXRadio by hudacek.online
*
* 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 online.hudacek.fxradio.media.player
import io.humble.video.*
import io.humble.video.javaxsound.AudioFrame
import io.humble.video.javaxsound.MediaAudioConverterFactory
import javafx.concurrent.ScheduledService
import javafx.concurrent.Task
import javafx.util.Duration
import kotlinx.coroutines.*
import mu.KotlinLogging
import online.hudacek.fxradio.media.MediaPlayer
import online.hudacek.fxradio.media.MetaData
import online.hudacek.fxradio.media.MetaDataChanged
import online.hudacek.fxradio.media.StreamUnavailableException
import online.hudacek.fxradio.utils.Properties
import online.hudacek.fxradio.utils.Property
import tornadofx.Component
import tornadofx.get
import java.nio.ByteBuffer
import javax.sound.sampled.FloatControl
import javax.sound.sampled.SourceDataLine
import kotlin.reflect.full.memberProperties
import kotlin.reflect.jvm.isAccessible
data class StreamInfo(val streamId: Int, val stream: DemuxerStream, val decoder: Decoder)
//Custom Audio player using ffmpeg lib
internal class CustomPlayer : Component(), MediaPlayer {
private val logger = KotlinLogging.logger {}
private var mediaPlayerCoroutine: Job? = null
private var audioFrame: AudioFrame? = null
private var lastTriedVolumeChange = 0.0
private var streamUrl = ""
private val playerRefreshMetaProperty = Property(Properties.PLAYER_CUSTOM_REFRESH_META).get(true)
private val coroutineExceptionHandler = CoroutineExceptionHandler { _, throwable ->
logger.error(throwable) { "Stream unavailable..." }
}
override fun play(streamUrl: String) {
stop() //this player should stop itself before playing new stream
this.streamUrl = streamUrl
if (playerRefreshMetaProperty) {
metaDataService.restart()
}
mediaPlayerCoroutine = GlobalScope.launch(coroutineExceptionHandler) {
val deMuxer = Demuxer.make()
val streamInfo = deMuxer.getStream(streamUrl)
val audioStreamId = streamInfo?.streamId
val audioDecoder = streamInfo?.decoder
try {
audioDecoder?.let {
val samples = MediaAudio.make(
it.frameSize,
it.sampleRate,
it.channels,
it.channelLayout,
it.sampleFormat)
//Info about decoder
logger.debug { it }
val converter = MediaAudioConverterFactory.createConverter(
MediaAudioConverterFactory.DEFAULT_JAVA_AUDIO,
samples)
audioFrame = AudioFrame.make(converter.javaFormat)
?: throw StreamUnavailableException("No output device available!")
var rawAudio: ByteBuffer? = null
//Log audio format
logger.info { audioFrame?.format }
changeVolume(lastTriedVolumeChange)
val packet = MediaPacket.make()
while (deMuxer.read(packet) >= 0) {
if (!isActive) break
if (packet.streamIndex == audioStreamId) {
var offset = 0
var bytesRead = 0
do {
bytesRead += it.decode(samples, packet, offset)
if (samples.isComplete) {
rawAudio = converter.toJavaAudio(rawAudio, samples)
audioFrame?.play(rawAudio)
}
offset += bytesRead
} while (offset < packet.size)
}
}
do {
it.decode(samples, null, 0)
if (samples.isComplete) {
rawAudio = converter.toJavaAudio(rawAudio, samples)
audioFrame?.play(rawAudio)
}
} while (samples.isComplete)
}
} finally {
deMuxer.close()
audioFrame?.dispose()
}
}
}
override fun changeVolume(newVolume: Double): Boolean {
return try {
//Dirty hack, since the api does not provide direct access to field,
//we use reflection to get access to line field to change volume
lastTriedVolumeChange = newVolume
AudioFrame::class.memberProperties
.filter { it.name == "mLine" }[0].apply {
isAccessible = true
val lineValue = getter.call(audioFrame) as SourceDataLine
val gainControl = lineValue.getControl(FloatControl.Type.MASTER_GAIN) as FloatControl
gainControl.value = newVolume.toFloat()
}
true
} catch (e: Exception) {
logger.debug { "Can't change volume to : $newVolume" }
false
}
}
override fun stop() {
if (playerRefreshMetaProperty) {
metaDataService.cancel()
}
mediaPlayerCoroutine?.let {
if (it.isActive) {
it.cancel()
}
}
}
override fun release() = stop()
/**
* Returns opened decoder or null when error happened
*/
private fun Demuxer.getStream(streamUrl: String): StreamInfo? {
try {
this.open(streamUrl, null, false, true, null, null)
for (i in 0 until numStreams) {
val stream = getStream(i)
val decoder = stream.decoder
if (decoder != null && decoder.codecType == MediaDescriptor.Type.MEDIA_AUDIO) {
decoder.open(null, null)
return StreamInfo(i, stream, decoder)
}
}
} catch (e: Exception) {
throw StreamUnavailableException(messages["player.streamError"])
}
return null
}
/**
* Fetch new meta data from playing stream
* In Testing - may cause issues, enabled under flag
*/
private val metaDataService = object : ScheduledService<KeyValueBag>() {
init {
period = Duration.seconds(50.0)
delay = Duration.seconds(5.0)
}
override fun createTask(): Task<KeyValueBag> = FetchDataTask()
}
inner class FetchDataTask : Task<KeyValueBag>() {
override fun call(): KeyValueBag {
val deMuxer = Demuxer.make()
deMuxer.open(streamUrl, null, false, true, null, null)
val data = deMuxer.metaData
deMuxer.close()
return data
}
override fun succeeded() {
if (value.getValue("StreamTitle") != null
&& value.getValue("icy-name") != null) {
val mediaMeta = MetaData(value.getValue("icy-name"), value.getValue("StreamTitle"))
fire(MetaDataChanged(mediaMeta))
}
}
override fun failed() = exception.printStackTrace()
}
} | 0 | null | 0 | 0 | 3ac6739388711b4cbfc2c96f54024cb5e3a8c7ba | 7,902 | fxradio-main | Apache License 2.0 |
library/src/main/kotlin/org/mjdev/libs/barcodescanner/bysquare/data/invoice/MonetarySummary.kt | mimoccc | 804,873,510 | false | {"Kotlin": 244846, "Shell": 336} | package org.mjdev.libs.barcodescanner.bysquare.data.invoice
import org.mjdev.libs.barcodescanner.bysquare.base.IVerifiable
import org.mjdev.libs.barcodescanner.bysquare.base.InvalidValueException
import org.mjdev.libs.barcodescanner.bysquare.data.InvoiceBase
@Suppress("unused", "MemberVisibilityCanBePrivate")
class MonetarySummary : IVerifiable {
var invoice: InvoiceBase? = null
var paidDepositsAmount: Double = 0.0
var payableRoundingAmount: Double = 0.0
val taxCategorySummaries: TaxCategorySummaries
get() = invoice?.taxCategorySummaries ?: TaxCategorySummaries()
val alreadyClaimedTaxAmount: Double
get() {
val iterator: MutableIterator<TaxCategorySummary> = taxCategorySummaries.iterator()
var amount = 0.0
while (iterator.hasNext()) {
amount += iterator.next().alreadyClaimedTaxAmount
}
return amount
}
val alreadyClaimedTaxExclusiveAmount: Double
get() {
val iterator: Iterator<TaxCategorySummary> = taxCategorySummaries.iterator()
var amount = 0.0
while (iterator.hasNext()) {
amount += iterator.next().alreadyClaimedTaxExclusiveAmount
}
return amount
}
val alreadyClaimedTaxInclusiveAmount: Double
get() {
val iterator: Iterator<TaxCategorySummary> = taxCategorySummaries.iterator()
var amount = 0.0
while (iterator.hasNext()) {
amount += iterator.next().alreadyClaimedTaxInclusiveAmount
}
return amount
}
val differenceTaxAmount: Double
get() {
val iterator: Iterator<TaxCategorySummary> = taxCategorySummaries.iterator()
var amount = 0.0
while (iterator.hasNext()) {
amount += iterator.next().differenceTaxAmount
}
return amount
}
val differenceTaxExclusiveAmount: Double
get() {
val iterator: Iterator<TaxCategorySummary> = taxCategorySummaries.iterator()
var amount = 0.0
while (iterator.hasNext()) {
amount += iterator.next().differenceTaxExclusiveAmount
}
return amount
}
val differenceTaxInclusiveAmount: Double
get() {
val iterator: Iterator<TaxCategorySummary> = taxCategorySummaries.iterator()
var amount = 0.0
while (iterator.hasNext()) {
amount += iterator.next().differenceTaxInclusiveAmount
}
return amount
}
val payableAmount: Double
get() = differenceTaxInclusiveAmount - paidDepositsAmount + payableRoundingAmount
val taxAmount: Double
get() {
val iterator: Iterator<TaxCategorySummary> = taxCategorySummaries.iterator()
var amount = 0.0
while (iterator.hasNext()) {
amount += iterator.next().taxAmount
}
return amount
}
val taxExclusiveAmount: Double
get() {
val iterator: Iterator<TaxCategorySummary> = taxCategorySummaries.iterator()
var amount = 0.0
while (iterator.hasNext()) {
amount += iterator.next().taxExclusiveAmount
}
return amount
}
val taxInclusiveAmount: Double
get() {
val iterator: Iterator<TaxCategorySummary> = taxCategorySummaries.iterator()
var amount = 0.0
while (iterator.hasNext()) {
amount += iterator.next().taxInclusiveAmount
}
return amount
}
@Throws(InvalidValueException::class)
override fun verify() {
}
}
| 0 | Kotlin | 0 | 0 | 6f99b62284c335faeef849c5cee8771ffc760ed6 | 3,792 | barcodescanner | Apache License 2.0 |
app/src/main/java/com/example/dogglers/adapter/DogCardAdapter.kt | Vguilhen | 516,748,946 | false | {"Kotlin": 28653} | /*
* Copyright (C) 2021 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.example.dogglers.adapter
import android.content.Context
import android.media.Image
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.GridView
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.dogglers.R
import com.example.dogglers.const.Layout
import com.example.dogglers.data.DataSource
import com.example.dogglers.model.Dog
/**
* Adapter to inflate the appropriate list item layout and populate the view with information
* from the appropriate data source
*/
class DogCardAdapter(
private val context: Context?,
private val layout: Int
) : RecyclerView.Adapter<DogCardAdapter.DogCardViewHolder>() {
private val data = DataSource.dogs
/**
* Initialize view elements
*/
class DogCardViewHolder(view: View?) : RecyclerView.ViewHolder(view!!) {
val dogImage: ImageView = view!!.findViewById(R.id.dog_image)
val dogName: TextView = view!!.findViewById(R.id.dog_name)
val dogAge: TextView = view!!.findViewById(R.id.dog_age)
val dogHobbies: TextView = view!!.findViewById(R.id.dog_hobbies)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DogCardViewHolder {
val adpterLayout = when (layout) {
Layout.GRID -> {
LayoutInflater.from(parent.context)
.inflate(R.layout.grid_list_item, parent, false)
}
else -> {
LayoutInflater.from(parent.context)
.inflate(R.layout.vertical_horizontal_list_item, parent, false)
}
}
return DogCardViewHolder(adpterLayout)
}
override fun getItemCount(): Int = data.size
override fun onBindViewHolder(holder: DogCardViewHolder, position: Int) {
val resources = context?.resources
val dogItem = data[position]
holder.dogImage.setImageResource(dogItem.imageResourceId)
holder.dogName.text = dogItem.name
holder.dogHobbies.text = resources?.getString(R.string.dog_hobbies, dogItem.hobbies)
holder.dogAge.text = resources?.getString(R.string.dog_age, dogItem.age)
}
}
| 0 | Kotlin | 0 | 0 | 116f640857c966c35c082192b82014346ed1326d | 2,861 | Dogglers | Apache License 2.0 |
day_02/src/main/kotlin/io/github/zebalu/advent2020/PasswordCounter.kt | zebalu | 317,448,231 | false | null | package io.github.zebalu.advent2020
object PasswordCounter {
fun countValidByBasicRules(lines: List<String>): Int = lines.map { s -> Password(s) }.count { it.isValid() }
fun countValidByTobboganRules(lines: List<String>): Int =
lines.map { s -> TobboganPassword(s) }.count { it.isValid() }
} | 0 | Kotlin | 0 | 1 | ca54c64a07755ba044440832ba4abaa7105cdd6e | 298 | advent2020 | Apache License 2.0 |
composeApp/src/commonMain/kotlin/theme/Theme.kt | vikassuthar44 | 763,136,556 | false | {"Kotlin": 186750, "Swift": 1095, "HTML": 304} | package theme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
private val colorScheme = darkColorScheme(
primary = Primary,
secondary = Secondary,
tertiary = Tertiary,
background = Color(0xFFF2F1F6),//#f2f1f6
surface = Color(0xFFFFFBFE),
)
@Composable
fun MealAppTheme(
darkTheme: Boolean = false,
content: @Composable () -> Unit
) {
val colorScheme = colorScheme
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | 0 | Kotlin | 0 | 0 | 5a30808bd6612a99e8849fc2a8caae428035948e | 660 | mealappkmp | Apache License 2.0 |
app/src/main/java/com/frenchcommando/recipes/RecipeDetailActivity.kt | FrenchCommando | 448,447,012 | false | null | package com.frenchcommando.recipes
import android.os.Bundle
import android.text.TextUtils
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.google.android.material.appbar.CollapsingToolbarLayout
class RecipeDetailActivity : AppCompatActivity() {
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail)
val intent = intent
val recipeName = intent.getStringExtra(EXTRA_NAME)
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val collapsingToolbar: CollapsingToolbarLayout = findViewById(R.id.collapsing_toolbar)
collapsingToolbar.title = recipeName
loadBackdrop()
loadContent()
}
private fun loadBackdrop() {
val imageView: ImageView = findViewById(R.id.backdrop)
Glide.with(imageView)
.load(Recipes.getRecipe(intent.getStringExtra(EXTRA_NAME))!!.drawable)
.apply(RequestOptions.centerCropTransform())
.into(imageView)
}
private fun loadContent() {
val recipeValue: Recipe = Recipes.getRecipe(intent.getStringExtra(EXTRA_NAME))!!
val infoView: TextView = findViewById(R.id.info_content)
infoView.text = recipeValue.content.description
val ingredientsView: TextView = findViewById(R.id.ingredients_content)
ingredientsView.text = TextUtils.join("\n", recipeValue.content.ingredients)
val ovenView: TextView = findViewById(R.id.oven_content)
ovenView.text = recipeValue.content.oven
}
companion object {
const val EXTRA_NAME = "recipe_name"
}
} | 0 | Kotlin | 0 | 0 | 8c9f98d13b75a5849c0d4a4c8e82c1222aa54ce7 | 1,938 | recipes | Apache License 2.0 |
app/src/main/java/com/frenchcommando/recipes/RecipeDetailActivity.kt | FrenchCommando | 448,447,012 | false | null | package com.frenchcommando.recipes
import android.os.Bundle
import android.text.TextUtils
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.google.android.material.appbar.CollapsingToolbarLayout
class RecipeDetailActivity : AppCompatActivity() {
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail)
val intent = intent
val recipeName = intent.getStringExtra(EXTRA_NAME)
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val collapsingToolbar: CollapsingToolbarLayout = findViewById(R.id.collapsing_toolbar)
collapsingToolbar.title = recipeName
loadBackdrop()
loadContent()
}
private fun loadBackdrop() {
val imageView: ImageView = findViewById(R.id.backdrop)
Glide.with(imageView)
.load(Recipes.getRecipe(intent.getStringExtra(EXTRA_NAME))!!.drawable)
.apply(RequestOptions.centerCropTransform())
.into(imageView)
}
private fun loadContent() {
val recipeValue: Recipe = Recipes.getRecipe(intent.getStringExtra(EXTRA_NAME))!!
val infoView: TextView = findViewById(R.id.info_content)
infoView.text = recipeValue.content.description
val ingredientsView: TextView = findViewById(R.id.ingredients_content)
ingredientsView.text = TextUtils.join("\n", recipeValue.content.ingredients)
val ovenView: TextView = findViewById(R.id.oven_content)
ovenView.text = recipeValue.content.oven
}
companion object {
const val EXTRA_NAME = "recipe_name"
}
} | 0 | Kotlin | 0 | 0 | 8c9f98d13b75a5849c0d4a4c8e82c1222aa54ce7 | 1,938 | recipes | Apache License 2.0 |
src/main/kotlin/ru/justagod/processing/cutter/config/SideName.kt | JustAGod1 | 179,755,842 | false | {"Kotlin": 232280, "Java": 12281} | package ru.justagod.processing.cutter.config
import java.io.Serializable
class SideName private constructor(val name: String) : Serializable {
private val _parents = arrayListOf<SideName>()
val parents: List<SideName>
get() = _parents
fun extendsFrom(side: SideName): SideName {
_parents += side
return this
}
companion object {
private val cache = hashMapOf<String, SideName>()
@JvmStatic
fun make(name: String): SideName {
return cache.computeIfAbsent(name.toLowerCase()) { SideName(name.toLowerCase()) }
}
}
override fun toString(): String = "Side($name)"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as SideName
if (!name.equals(other.name, ignoreCase = true)) return false
return true
}
override fun hashCode(): Int {
return name.hashCode()
}
} | 0 | Kotlin | 0 | 0 | 5f635e045a6e1323571e492723110de280232c5a | 1,008 | cutter | MIT License |
src/main/kotlin/com/projectcitybuild/entities/QueuedTeleport.kt | projectcitybuild | 42,997,941 | false | null | package com.projectcitybuild.entities
import java.time.LocalDateTime
import java.util.*
data class QueuedTeleport(
val playerUUID: UUID,
val targetPlayerUUID: UUID,
val targetServerName: String,
val teleportType: TeleportType,
val isSilentTeleport: Boolean,
val createdAt: LocalDateTime,
)
enum class TeleportType {
TP,
SUMMON,
}
| 23 | Kotlin | 0 | 2 | 24c6a86aee15535c3122ba6fb57cc7ca351e32bb | 365 | PCBridge | MIT License |
app/src/main/java/com/exdb/vpabe/ui/event/EventData.kt | exsandebest | 280,267,042 | true | {"Kotlin": 120521} | package com.exdb.vpabe.ui.event
import android.location.Location
import androidx.lifecycle.MutableLiveData
import com.exdb.vpabe.models.Event
class EventData : MutableLiveData<List<Event>>()
typealias MutableLocation = MutableLiveData<Location>
| 0 | Kotlin | 0 | 0 | 38101609ab72f0c5e0ff80aca27ae3a94408d09d | 248 | VPabe | MIT License |
codebase/android/core/common/src/main/java/com/makeappssimple/abhimanyu/financemanager/android/core/common/constants/AppConstants.kt | Abhimanyu14 | 429,663,688 | false | null | package com.makeappssimple.abhimanyu.financemanager.android.core.common.constants
public object AppConstants {
public const val APP_NAME: String = "finance_manager"
public const val DATABASE_NAME: String = "finance_manager_database"
public const val DATABASE_CURRENT_VERSION_NUMBER: Int = 22
public const val DATASTORE_CURRENT_VERSION_NUMBER: Int = 4
public const val INITIAL_DATA_FILE_NAME: String = "database/initial_data.json"
public const val ZONE_ID_GMT: String = "UTC"
}
| 11 | null | 0 | 3 | 7e080a68bc038bd64d2d406b75a49e8f1ea2a791 | 502 | finance-manager | Apache License 2.0 |
player-video/app/src/androidTest/java/gparap/apps/player_video/MainActivityInstrumentedTest.kt | gparap | 253,560,705 | false | null | /*
* Copyright 2023 gparap
*
* 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 gparap.apps.player_video
import androidx.recyclerview.widget.RecyclerView
import androidx.test.core.app.ActivityScenario
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MainActivityInstrumentedTest {
private lateinit var activityScenario: ActivityScenario<MainActivity>
@Before
fun setUp() {
activityScenario = ActivityScenario.launch(MainActivity::class.java)
}
@Test
fun isVisible_recyclerViewVideos() {
onView(withId(R.id.recycler_view_videos)).check(matches(isDisplayed()))
}
@Test
fun isNotEmpty_recyclerViewVideos() {
activityScenario.onActivity {
val recyclerView = it.findViewById<RecyclerView>(R.id.recycler_view_videos)
val videoCount = recyclerView.adapter?.itemCount
if (videoCount != null) {
assert(videoCount > 0)
} else {
assert(false)
}
}
}
} | 1 | null | 1 | 7 | f156d0f405b4bab602ae187ee3f2dbfe67741689 | 1,901 | android | Apache License 2.0 |
support-core/src/main/kotlin/co/anitrend/arch/core/viewmodel/contract/ISupportViewModel.kt | fossabot | 223,555,788 | true | {"Kotlin": 288406, "Java": 19109} | package co.anitrend.arch.core.viewmodel.contract
import androidx.lifecycle.LiveData
import co.anitrend.arch.domain.entities.NetworkState
/**
* Contract for view models that aids relaying commands to an underlying repository
*
* @since v0.9.X
*/
interface ISupportViewModel<P, R> {
/**
* Use case result model
*/
val model: LiveData<R?>
/**
* Network state for main requests
*/
val networkState: LiveData<NetworkState>?
/**
* Refreshing network state
*/
val refreshState: LiveData<NetworkState>?
/**
* Checks if the live data stored in the repository has is not null
*
* @return [Boolean] true or false
*/
fun hasModelData(): Boolean = model.value != null
/**
* Starts view model operations
*
* @param parameter request payload
*/
operator fun invoke(parameter: P)
/**
* Requests the use case to perform a retry operation
*/
fun retry()
/**
* Requests the use case to perform a refresh operation
*/
fun refresh()
} | 0 | Kotlin | 0 | 0 | 50be1a136fc46fb0eaccc041ef40eca2f4c67771 | 1,072 | support-arch | Apache License 2.0 |
support-core/src/main/kotlin/co/anitrend/arch/core/viewmodel/contract/ISupportViewModel.kt | fossabot | 223,555,788 | true | {"Kotlin": 288406, "Java": 19109} | package co.anitrend.arch.core.viewmodel.contract
import androidx.lifecycle.LiveData
import co.anitrend.arch.domain.entities.NetworkState
/**
* Contract for view models that aids relaying commands to an underlying repository
*
* @since v0.9.X
*/
interface ISupportViewModel<P, R> {
/**
* Use case result model
*/
val model: LiveData<R?>
/**
* Network state for main requests
*/
val networkState: LiveData<NetworkState>?
/**
* Refreshing network state
*/
val refreshState: LiveData<NetworkState>?
/**
* Checks if the live data stored in the repository has is not null
*
* @return [Boolean] true or false
*/
fun hasModelData(): Boolean = model.value != null
/**
* Starts view model operations
*
* @param parameter request payload
*/
operator fun invoke(parameter: P)
/**
* Requests the use case to perform a retry operation
*/
fun retry()
/**
* Requests the use case to perform a refresh operation
*/
fun refresh()
} | 0 | Kotlin | 0 | 0 | 50be1a136fc46fb0eaccc041ef40eca2f4c67771 | 1,072 | support-arch | Apache License 2.0 |
app/src/main/java/com/gmrit/gdsc/fragments/CompletedFragment.kt | saikiran1224 | 436,351,656 | false | {"Kotlin": 115847} | package com.gmrit.gdsc.fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.gmrit.gdsc.R
class CompletedFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_completed, container, false)
return view
}
} | 0 | Kotlin | 0 | 2 | 052bb3e092ec624c90051c9a79c7a72072ab0026 | 558 | GDSC_GMRIT_App | MIT License |
src/main/kotlin/com/justai/jaicf/plugin/providers/StatePathReferenceContributor.kt | veptechno | 428,503,533 | true | {"Kotlin": 100333, "HTML": 1363} | package com.justai.jaicf.plugin.providers
import com.intellij.openapi.util.TextRange
import com.intellij.patterns.PlatformPatterns
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.PsiReferenceBase
import com.intellij.psi.PsiReferenceContributor
import com.intellij.psi.PsiReferenceProvider
import com.intellij.psi.PsiReferenceRegistrar
import com.intellij.util.ProcessingContext
import com.justai.jaicf.plugin.Lexeme
import com.justai.jaicf.plugin.StatePath
import com.justai.jaicf.plugin.firstStateOrSuggestion
import com.justai.jaicf.plugin.getBoundedPathExpression
import com.justai.jaicf.plugin.getFramingState
import com.justai.jaicf.plugin.identifierReference
import com.justai.jaicf.plugin.plus
import com.justai.jaicf.plugin.rangeToEndOf
import com.justai.jaicf.plugin.stringValueOrNull
import com.justai.jaicf.plugin.transit
import com.justai.jaicf.plugin.transitionsWithRanges
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
class StatePathReferenceContributor : PsiReferenceContributor() {
override fun registerReferenceProviders(registrar: PsiReferenceRegistrar) {
registrar.registerReferenceProvider(
PlatformPatterns.psiElement(KtStringTemplateExpression::class.java),
StatePathReferenceProvider()
)
}
}
class StatePathReferenceProvider : PsiReferenceProvider() {
override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<PsiReference> {
val pathExpression = element.getBoundedPathExpression() ?: return emptyArray()
val statePath = pathExpression.stringValueOrNull?.let { StatePath.parse(it) } ?: return emptyArray()
return if (pathExpression.isSimpleStringTemplate) {
var accPath = StatePath()
statePath.transitionsWithRanges()
.mapNotNull { (transition, range) ->
accPath += transition
if (transition is Lexeme.Transition.Root)
null
else
StatePsiReference(element, accPath, range.shiftRight(1))
}.toTypedArray()
} else {
arrayOf(StatePsiReference(element, statePath, element.rangeToEndOf(pathExpression)))
}
}
}
class StatePsiReference(
element: PsiElement,
path: StatePath,
textRange: TextRange = element.textRange,
) : PsiReferenceBase<PsiElement?>(element, textRange) {
private val transitionResult by lazy { element.getFramingState()?.transit(path) }
override fun resolve() = transitionResult?.firstStateOrSuggestion()?.identifierReference
}
| 0 | Kotlin | 0 | 0 | 395338825f20fbe8deaae72ee18bccdde71abc0f | 2,656 | jaicf-plugin | Apache License 2.0 |
spring-boot-starter/src/test/kotlin/com/messengerk/spring_boot_starter/TransportConfigurationTest.kt | tsantos84 | 441,781,910 | false | {"Kotlin": 40278} | package com.messengerk.spring_boot_starter
import com.messengerk.core.Envelope
import com.messengerk.core.config.MessengerConfig
import com.messengerk.core.config.TransportConfig
import com.messengerk.core.transport.Transport
import com.messengerk.core.transport.TransportFactory
import com.messengerk.core.transport.TransportRegistry
import com.messengerk.core.transport.sync.SyncTransportFactory
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.boot.autoconfigure.AutoConfigurations
import org.springframework.boot.test.context.runner.ApplicationContextRunner
import org.springframework.context.annotation.Bean
import strikt.api.expectThat
import strikt.assertions.isA
import strikt.assertions.isTrue
internal class TransportConfigurationTest {
internal class MockTransportFactory : TransportFactory {
override fun create(config: TransportConfig): Transport {
return MockTransport()
}
override fun supports(config: TransportConfig): Boolean = config.name == "mock"
}
internal class MockTransport : Transport {
override fun send(envelope: Envelope<Any>): Envelope<Any> {
return envelope
}
override fun getName(): String = "mock"
}
internal class TransportConfiguration {
@Bean
fun messengerConfig(): MessengerConfig = MessengerConfig {
transport("mock")
}
}
private lateinit var contextRunner: ApplicationContextRunner
@BeforeEach
fun setUp() {
contextRunner = ApplicationContextRunner()
.withUserConfiguration(TransportConfiguration::class.java)
.withConfiguration(AutoConfigurations.of(MessageBusConfiguration::class.java))
}
@Test
fun `It should create the TransportRegistry bean`() {
contextRunner
.withBean(MockTransportFactory::class.java)
.run {
expectThat(it).containsBean("messengerTransportRegistry")
val registry = it.getBean("messengerTransportRegistry") as TransportRegistry
expectThat(registry.has("mock")).describedAs("transport registry contains transport \"mock\"").isTrue()
}
}
@Test
fun `It should create register SyncTransportFactory`() {
contextRunner
.run {
expectThat(it).containsBean("messengerTransportSyncFactory")
val transport = it.getBean("messengerTransportSyncFactory") as TransportFactory
expectThat(transport).isA<SyncTransportFactory>()
}
}
} | 0 | Kotlin | 0 | 0 | 5358365033dfb76db9d021f7e2b12aa568e2c22d | 2,613 | messengerk | MIT License |
defitrack-rest/defitrack-protocol-service/src/main/java/io/defitrack/protocol/blur/pooling/BlurDepositPoolingMarketProvider.kt | decentri-fi | 426,174,152 | false | {"Kotlin": 1309500, "Java": 1948, "Dockerfile": 909} | package io.defitrack.protocol.application.blur
import arrow.core.nel
import io.defitrack.common.network.Network
import io.defitrack.common.utils.AsyncUtils.lazyAsync
import io.defitrack.common.utils.FormatUtilsExtensions.asEth
import io.defitrack.common.utils.map
import io.defitrack.common.utils.refreshable
import io.defitrack.architecture.conditional.ConditionalOnCompany
import io.defitrack.evm.contract.ERC20Contract
import io.defitrack.market.port.out.PoolingMarketProvider
import io.defitrack.market.domain.PoolingMarket
import io.defitrack.market.domain.PoolingMarketTokenShare
import io.defitrack.protocol.Company
import io.defitrack.protocol.Protocol
import org.springframework.stereotype.Component
import java.math.BigDecimal.TEN
@Component
@ConditionalOnCompany(Company.BLUR)
class BlurDepositPoolingMarketProvider : PoolingMarketProvider() {
val blurEthDeposit = "0x0000000000a39bb272e79075ade125fd351887ac"
val blurEthDepositContract = lazyAsync {
}
override suspend fun fetchMarkets(): List<PoolingMarket> = with(getBlockchainGateway()) {
val contract = ERC20Contract(
blurEthDeposit
)
val ether = getToken("0x0")
return create(
breakdown = refreshable {
PoolingMarketTokenShare(
ether,
getBlockchainGateway().getNativeBalance(blurEthDeposit).times(TEN.pow(18)).toBigInteger()
).nel()
},
name = "BlurEth",
identifier = blurEthDeposit,
address = blurEthDeposit,
symbol = "blurEth",
tokens = listOf(ether),
totalSupply = contract.totalSupply().map {
it.asEth(contract.readDecimals().toInt())
},
positionFetcher = defaultPositionFetcher(blurEthDeposit),
).nel()
}
override fun getProtocol(): Protocol {
return Protocol.BLUR
}
override fun getNetwork(): Network {
return Network.ETHEREUM
}
} | 59 | Kotlin | 6 | 10 | a6e3b0a35fd7d57942301574095d389501677b32 | 2,023 | defi-hub | MIT License |
charset/src/com/fleeksoft/charset/CharsetDecoder.kt | fleeksoft | 874,918,183 | false | {"Kotlin": 8845941} | package com.fleeksoft.charset
import com.fleeksoft.charset.internal.ArraysSupport
import com.fleeksoft.charset.internal.assert
import com.fleeksoft.charset.io.ByteBuffer
import com.fleeksoft.charset.io.CharBuffer
import com.fleeksoft.charset.io.CoderMalfunctionError
import kotlin.math.min
abstract class CharsetDecoder(
val charset: Charset,
val averageCharsPerByte: Float,
val maxCharsPerByte: Float
) {
init {
require(averageCharsPerByte > 0.0f) { "averageCharsPerByte must be positive, was $averageCharsPerByte" }
require(maxCharsPerByte > 0.0f) { "maxCharsPerByte must be positive, was $maxCharsPerByte" }
require(!(averageCharsPerByte > maxCharsPerByte)) { "averageCharsPerByte must not greater than maxCharsPerByte, was $averageCharsPerByte" }
}
companion object {
const val ST_RESET = 0
const val ST_CODING = 1
const val ST_END = 2
const val ST_FLUSHED = 3
val stateNames: Array<String> = arrayOf("RESET", "CODING", "CODING_END", "FLUSHED")
}
private var state: Int = ST_RESET
var malformedInputAction: CodingErrorAction = CodingErrorAction.REPORT
private set
var unmappableCharacterAction: CodingErrorAction = CodingErrorAction.REPORT
private set
protected var replacement: String = "\uFFFD"
private set
fun decode(byteBuffer: ByteBuffer, outCharBuffer: CharBuffer, endOfInput: Boolean): CoderResult {
val newState: Int = if (endOfInput) ST_END else ST_CODING
if ((state != ST_RESET) && (state != ST_CODING)
&& !(endOfInput && (state == ST_END))
) throwIllegalStateException(state, newState)
state = newState
while (true) {
var cr: CoderResult
try {
cr = decodeLoop(byteBuffer, outCharBuffer)
} catch (x: RuntimeException) {
throw CoderMalfunctionError(x)
}
if (cr.isOverflow) return cr
if (cr.isUnderflow) {
if (endOfInput && byteBuffer.hasRemaining()) {
cr = CoderResult.malformedForLength(byteBuffer.remaining())
// Fall through to malformed-input case
} else {
return cr
}
}
var action: CodingErrorAction? = null
if (cr.isMalformed) action = malformedInputAction
else if (cr.isUnmappable) action = unmappableCharacterAction
else assert(false) { cr.toString() }
if (action == CodingErrorAction.REPORT) return cr
if (action == CodingErrorAction.REPLACE) {
if (outCharBuffer.remaining() < replacement.length) return CoderResult.OVERFLOW
outCharBuffer.put(replacement)
}
if ((action == CodingErrorAction.IGNORE) || (action == CodingErrorAction.REPLACE)) {
// Skip erroneous input either way
byteBuffer.position(byteBuffer.position() + cr.length())
continue
}
assert(false)
}
}
fun decode(inByteBuffer: ByteBuffer): CharBuffer {
var n: Int = min((inByteBuffer.remaining() * averageCharsPerByte).toInt(), ArraysSupport.SOFT_MAX_ARRAY_LENGTH)
var out: CharBuffer = CharBuffer.allocate(n)
if ((n == 0) && (inByteBuffer.remaining() == 0)) return out
reset()
while (true) {
var cr: CoderResult = if (inByteBuffer.hasRemaining()) decode(inByteBuffer, out, true) else CoderResult.UNDERFLOW
if (cr.isUnderflow) cr = flush(out)
if (cr.isUnderflow) break
if (cr.isOverflow) {
// Ensure progress; n might be 0!
n = ArraysSupport.newLength(n, min(n + 1, 1024), n + 1)
val o: CharBuffer = CharBuffer.allocate(n)
out.flip()
o.put(out)
out = o
continue
}
cr.throwException()
}
out.flip()
return out
}
fun flush(out: CharBuffer): CoderResult {
if (state == ST_END) {
val cr: CoderResult = implFlush(out)
if (cr.isUnderflow) state = ST_FLUSHED
return cr
}
if (state != ST_FLUSHED) throwIllegalStateException(state, ST_FLUSHED)
return CoderResult.UNDERFLOW // Already flushed
}
abstract fun decodeLoop(byteBuffer: ByteBuffer, charBuffer: CharBuffer): CoderResult
private fun throwIllegalStateException(from: Int, to: Int) {
throw IllegalStateException("Current state = ${stateNames[from]}, new state = ${stateNames[to]}")
}
/**
* Flushes this decoder.
*
* <p> The default implementation of this method does nothing, and always
* returns {@link CoderResult#UNDERFLOW}. This method should be overridden
* by decoders that may need to write final characters to the output buffer
* once the entire input sequence has been read. </p>
*
* @param out
* The output character buffer
*
* @return A coder-result object, either {@link CoderResult#UNDERFLOW} or
* {@link CoderResult#OVERFLOW}
*/
open fun implFlush(out: CharBuffer): CoderResult {
return CoderResult.UNDERFLOW
}
/*public final CharsetDecoder onMalformedInput(CodingErrorAction newAction) {
if (newAction == null)
throw new IllegalArgumentException("Null action");
malformedInputAction = newAction;
implOnMalformedInput(newAction);
return this;
}*/
fun onMalformedInput(newAction: CodingErrorAction): CharsetDecoder {
malformedInputAction = newAction
implOnMalformedInput(newAction)
return this
}
protected open fun implOnMalformedInput(newAction: CodingErrorAction) {}
fun onUnmappableCharacter(newAction: CodingErrorAction): CharsetDecoder {
unmappableCharacterAction = newAction
implOnUnmappableCharacter(newAction)
return this
}
protected open fun implOnUnmappableCharacter(newAction: CodingErrorAction) {}
/**
* Resets this decoder, clearing any internal state.
*
* This method resets charset-independent state and also invokes the
* [implReset] method to perform any charset-specific reset actions.
*
* @return This decoder
*/
fun reset(): CharsetDecoder {
implReset()
state = ST_RESET
return this
}
/**
* Resets this decoder, clearing any charset-specific internal state.
*
* The default implementation of this method does nothing. This method
* should be overridden by decoders that maintain internal state.
*/
protected open fun implReset() {}
}
enum class CodingErrorAction {
IGNORE, REPLACE, REPORT
}
| 1 | Kotlin | 0 | 2 | a16af685a558ad177749c12d7840a7b67aece66c | 6,902 | charset | MIT License |
src/commonMain/kotlin/org.angproj.aux/pipe/PumpSource.kt | angelos-project | 677,039,667 | false | {"Kotlin": 972623, "Python": 196308} | /**
* Copyright (c) 2024 by <NAME> <<EMAIL>>.
*
* This software is available under the terms of the MIT license. Parts are licensed
* under different terms if stated. The legal terms are attached to the LICENSE file
* and are made available on:
*
* https://opensource.org/licenses/MIT
*
* SPDX-License-Identifier: MIT
*
* Contributors:
* <NAME> - initial implementation
*/
package org.angproj.aux.pipe
import org.angproj.aux.io.PumpReader
import org.angproj.aux.io.Segment
import org.angproj.aux.util.Reifiable
public class PumpSource<T: PipeType>(
private val pump: PumpReader
): Source, PipeType {
private var _open: Boolean = true
/**
* This function forcefully sets the limit of the segment to the returned value
* to avoid programming mistakes.
* */
public fun<reified : Reifiable> squeeze(seg: Segment): Int {
val size = seg.limit
return pump.read(seg).also {
seg.limit = it
if (it < size || it == 0) close()
}
}
override fun isOpen(): Boolean = _open
override fun close() {
_open = false
}
} | 0 | Kotlin | 0 | 0 | 7a4016cea0dbd37275d13cf9b929ed52c1d722ce | 1,130 | angelos-project-aux | MIT License |
app/src/main/java/com/theapache64/tvplayground/utils/Context.kt | anoopmaddasseri | 316,386,537 | false | null | package com.theapache64.tvplayground.utils
import android.content.Context
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.view.animation.ScaleAnimation
import android.widget.Toast
import com.theapache64.tvplayground.R
fun Context?.toast(text: String) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}
fun View.runScaleAnimation(lister: (() -> Unit)? = null) {
// run scale animation and make it bigger
val scaleInAnim =
AnimationUtils.loadAnimation(context, R.anim.scale_in) as ScaleAnimation
startAnimation(scaleInAnim)
scaleInAnim.fillAfter = true
scaleInAnim.setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationStart(p0: Animation?) {
}
override fun onAnimationEnd(p0: Animation?) {
lister?.invoke()
}
override fun onAnimationRepeat(p0: Animation?) {
}
})
}
| 0 | Kotlin | 0 | 0 | 66a18e264cbc35d3ea5aacc93d6c062a09b7fdf9 | 979 | TVProgramBarPlayGround | Apache License 2.0 |
slideholder/src/main/java/zhan/library/slide/SlideAnimatorListener.kt | ruzhan123 | 62,323,379 | false | null | package zhan.library.slide
import android.animation.Animator
abstract class SlideAnimatorListener : Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator) {
}
override fun onAnimationEnd(animation: Animator) {
}
override fun onAnimationCancel(animation: Animator) {
}
override fun onAnimationRepeat(animation: Animator) {
}
abstract fun onSlideAnimationStart(animation: Animator, currentStatus: Int)
abstract fun onSlideAnimationEnd(animation: Animator, currentStatus: Int)
}
| 0 | Kotlin | 27 | 169 | a0e4361dfb17d32b15c42cc32dd20f5f8ebe4300 | 552 | RecyclerViewItemAnimation | Apache License 2.0 |
src/main/kotlin/pl/wendigo/chrome/api/domstorage/Types.kt | wendigo | 83,794,841 | false | null | package pl.wendigo.chrome.api.domstorage
/**
* DOM Storage identifier.
*
* @link [DOMStorage#StorageId](https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage#type-StorageId) type documentation.
*/
data class StorageId(
/**
* Security origin for the storage.
*/
val securityOrigin: String,
/**
* Whether the storage is local storage (not session storage).
*/
val isLocalStorage: Boolean
)
/**
* DOM Storage item.
*
* @link [DOMStorage#Item](https://chromedevtools.github.io/devtools-protocol/tot/DOMStorage#type-Item) type documentation.
*/
typealias Item = List<String>
| 3 | Kotlin | 11 | 76 | 29b51e37ed509938e986d1ada8cc2b0c8461cb73 | 643 | chrome-reactive-kotlin | Apache License 2.0 |
library/core/src/main/kotlin/jp/co/ksrogers/animationswitchingbottomnavigation/AnimationSwitchingBottomNavigationSelectedButton.kt | ks-rogers | 190,620,920 | false | {"Kotlin": 51742} | package jp.co.ksrogers.animationswitchingbottomnavigation
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.annotation.IdRes
import androidx.annotation.RestrictTo
import androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP
/**
* A layout for indicating selected menu in [AnimationSwitchingBottomNavigationLayout].
* This layout contains just single ImageView.
*
* If you want to customize yourself instead of this layout, you can use
* [AnimationSwitchingBottomNavigationSelectedItemLayout].
*/
@RestrictTo(LIBRARY_GROUP)
class AnimationSwitchingBottomNavigationSelectedButton @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : FrameLayout(context, attrs) {
private val buttonView = ImageView(context, attrs)
private var ovalDrawable: Drawable? = null
private var buttonColor: ColorStateList? = null
@IdRes
private var menuViewId: Int = 0
init {
attrs?.let {
val a = context.obtainStyledAttributes(
it,
R.styleable.AnimationSwitchingBottomNavigationSelectedButton
)
buttonColor =
a.getColorStateList(R.styleable.AnimationSwitchingBottomNavigationSelectedButton_buttonColor)
menuViewId =
a.getResourceId(R.styleable.AnimationSwitchingBottomNavigationSelectedButton_menuViewId, 0)
a.recycle()
}
ovalDrawable = resources.getDrawable(
R.drawable.animation_switching_bottom_navigation_selected_background,
null
).apply {
setTintList(buttonColor)
}
buttonView.apply {
background = ovalDrawable
}.also {
addView(it)
}
}
override fun setBackgroundTintList(tint: ColorStateList?) {
ovalDrawable?.setTintList(tint)
}
/**
* Tinting button's background with [ColorStateList].
*
* @param tint Tinting background drawable with this [ColorStateList]. Or set null to clear tinting.
*/
fun setOvalTintList(tint: ColorStateList?) {
ovalDrawable?.setTintList(tint)
}
} | 0 | Kotlin | 1 | 21 | c64972ebb3d05a87276f1ba62d639f8c8a6fbe01 | 2,139 | AnimationSwitchingBottomNavigationView | MIT License |
projects/src/main/java/org/odk/collect/projects/InMemProjectsRepository.kt | getodk | 40,213,809 | false | null | package org.samarthya.collect.projects
import org.samarthya.collect.shared.strings.UUIDGenerator
import java.util.function.Supplier
class InMemProjectsRepository(
private val uuidGenerator: UUIDGenerator = UUIDGenerator(),
private val clock: Supplier<Long> = Supplier { System.currentTimeMillis() }
) : ProjectsRepository {
val projects = mutableListOf<Project.Saved>()
val timestamps = mutableListOf<Pair<String, Long>>()
override fun get(uuid: String) = projects.find { it.uuid == uuid }
override fun getAll() = timestamps.sortedBy { it.second }.map {
projects.first { p -> p.uuid == it.first }
}
override fun save(project: Project): Project.Saved {
when (project) {
is Project.New -> {
val projectToSave = Project.Saved(uuidGenerator.generateUUID(), project)
projects.add(projectToSave)
timestamps.add(Pair(projectToSave.uuid, clock.get()))
return projectToSave
}
is Project.Saved -> {
val projectIndex = projects.indexOf(get(project.uuid))
if (projectIndex == -1) {
projects.add(project)
timestamps.add(Pair(project.uuid, clock.get()))
} else {
projects[projectIndex] = project
}
return project
}
}
}
override fun delete(uuid: String) {
projects.removeIf { it.uuid == uuid }
timestamps.removeIf { it.first == uuid }
}
override fun deleteAll() {
projects.clear()
timestamps.clear()
}
}
| 8 | null | 15 | 717 | 63050fdd265c42f3c340f0ada5cdff3c52a883bc | 1,659 | collect | Apache License 2.0 |
data/src/main/java/com/lyscraft/data/mappers/MovieListEntityMapper.kt | brahman10 | 843,088,920 | false | {"Kotlin": 47388} | package com.lyscraft.data.mappers
import com.lyscraft.base.BaseMapper
import com.lyscraft.data.entities.MovieListEntity
import com.lyscraft.domain.contents.MovieListContent
import javax.inject.Inject
/**
* Created by <NAME> on 14/08/24.
*/
class MovieListEntityMapper @Inject constructor() : BaseMapper<MovieListEntity, MovieListContent> {
override fun mapData(entity: MovieListEntity): MovieListContent {
return entity.let {
MovieListContent(
it.backdropPath,
it.id,
it.title,
it.originalTitle,
it.overview,
it.posterPath,
it.mediaType,
it.adult,
it.originalLanguage,
it.genreIds,
it.popularity,
it.releaseDate,
it.video,
it.voteAverage,
it.voteCount
)
}
}
override fun reverseMapData(content: MovieListContent): MovieListEntity {
return content.let {
MovieListEntity(
it.backdropPath,
it.id,
it.title,
it.originalTitle,
it.overview,
it.posterPath,
it.mediaType,
it.adult,
it.originalLanguage,
it.genreIds,
it.popularity,
it.releaseDate,
it.video,
it.voteAverage,
it.voteCount
)
}
}
} | 0 | Kotlin | 0 | 0 | fdfbc5a48a48933d667f97aefba8348f11bf56d8 | 1,566 | MovieAppCompose | MIT License |
src/main/kotlin/Plane.kt | StrahinjaLukic | 741,612,137 | false | {"Kotlin": 14267} | package src.main.kotlin
import src.main.kotlin.geometry.CartesianProduct
import src.main.kotlin.geometry.PlaneProjection
import src.main.kotlin.geometry.VectorNorm
class Plane(
val planePoint: CartesianVector, planeNormal: CartesianVector
) : Surface {
val normal = planeNormal / VectorNorm()(planeNormal)
override fun surfaceNormal(point: CartesianVector): CartesianVector {
val distance = PlaneProjection.pointToPlaneAbs(point, this)
require(distance < 1e-6) { "Point is not on the plane. It is $distance away" }
return normal
}
override fun intersectionPoint(ray: Ray): CartesianVector? {
val delta: CartesianVector = planePoint - ray.point
val perpendicularDistance: Float = CartesianProduct()(normal, delta)
if (perpendicularDistance == 0f) return ray.point
val perpendicularDisplacement: CartesianVector = normal * perpendicularDistance
val perpendicularProjection: Float = CartesianProduct()(perpendicularDisplacement, ray.direction)
if (perpendicularProjection == 0f) return null
return ray.point + ray.direction / perpendicularProjection
}
}
| 0 | Kotlin | 0 | 0 | 8fd3025f22d095a6e87e4c9325d67dd839552cc0 | 1,162 | LinearOptics | MIT License |
src/test/enhetstester/kotlin/no/nav/familie/ba/sak/kjerne/eøs/util/TilkjentYtelseDsl.kt | navikt | 224,639,942 | false | null | package no.nav.familie.ba.sak.kjerne.eøs.util
import no.nav.familie.ba.sak.common.lagInitiellTilkjentYtelse
import no.nav.familie.ba.sak.kjerne.beregning.domene.AndelTilkjentYtelse
import no.nav.familie.ba.sak.kjerne.beregning.domene.TilkjentYtelse
import no.nav.familie.ba.sak.kjerne.beregning.domene.YtelseType
import no.nav.familie.ba.sak.kjerne.grunnlag.personopplysninger.Person
import no.nav.familie.ba.sak.kjerne.tidslinje.tidspunkt.Måned
import no.nav.familie.ba.sak.kjerne.tidslinje.tidspunkt.Tidspunkt
import no.nav.familie.ba.sak.kjerne.tidslinje.tidspunkt.tilYearMonth
import java.math.BigDecimal
import java.time.YearMonth
/**
* Enkel DSL for å bygge TilkjentYtelse. Eksempel på bruk er:
*
* val tilkjentYtelse = lagInitiellTilkjentYtelse(behandling) der
* (søker har 1054 i UTVIDET_BARNETRYGD fom jun(2018) tom jul(2024)) og
* (søker har 660 i SMÅBARNSTILLEGG fom aug(2018) tom des(2019)) og
* (søker har 660 i SMÅBARNSTILLEGG fom jul(2020) tom mai(2023)) og
* (barn1 har 1054 i ORDINÆR_BARNETRYGD fom aug(2019) tom jul(2022)) og
* (barn1 har 1054 i ORDINÆR_BARNETRYGD fom aug(2022) tom jul(2024)) og
* (barn2 har 1054 i ORDINÆR_BARNETRYGD fom jul(2020) tom mai(2038))
*
* Utenlandsk beløp som gir differanseberegning kan introduseres med <og> eller <minus>, f.eks:
* (barn1 har 1054 og 756 i ORDINÆR_BARNETRYGD fom aug(2019) tom jul(2022))
* (barn1 har 1054 minus 756 i ORDINÆR_BARNETRYGD fom aug(2019) tom jul(2022))
*/
infix fun TilkjentYtelse.der(andelTilkjentYtelse: AndelTilkjentYtelse): TilkjentYtelse {
this.andelerTilkjentYtelse.add(
andelTilkjentYtelse.copy(
tilkjentYtelse = this,
behandlingId = this.behandling.id,
),
)
return this
}
infix fun TilkjentYtelse.og(andelTilkjentYtelse: AndelTilkjentYtelse) = this.der(andelTilkjentYtelse)
infix fun Person.har(sats: Int) = AndelTilkjentYtelse(
aktør = this.aktør,
sats = sats,
kalkulertUtbetalingsbeløp = sats,
behandlingId = 0,
tilkjentYtelse = lagInitiellTilkjentYtelse(),
stønadFom = YearMonth.now(),
stønadTom = YearMonth.now(),
type = YtelseType.ORDINÆR_BARNETRYGD,
prosent = BigDecimal.valueOf(100),
nasjonaltPeriodebeløp = sats,
)
infix fun AndelTilkjentYtelse.fom(tidspunkt: Tidspunkt<Måned>) = this.copy(stønadFom = tidspunkt.tilYearMonth())
infix fun AndelTilkjentYtelse.tom(tidspunkt: Tidspunkt<Måned>) = this.copy(stønadTom = tidspunkt.tilYearMonth())
infix fun AndelTilkjentYtelse.i(ytelseType: YtelseType) = this.copy(type = ytelseType)
infix fun AndelTilkjentYtelse.og(utenlandskBeløp: Int) = this.copy(
differanseberegnetPeriodebeløp = sats - utenlandskBeløp,
kalkulertUtbetalingsbeløp = maxOf(sats - utenlandskBeløp, 0),
)
infix fun AndelTilkjentYtelse.minus(utenlandskBeløp: Int) = this.og(utenlandskBeløp)
| 9 | Kotlin | 1 | 9 | d5878744bfebd9c358cd0154ab2e0515e238d44b | 2,854 | familie-ba-sak | MIT License |
web-jsbridge-interface/src/main/java/com/radiuswallet/uniweb/jsbridge/UiThreadJsBridgeDispatcher.kt | z-chu | 507,885,693 | false | {"Kotlin": 235647, "HTML": 35730, "Java": 2730} | package com.radiuswallet.uniweb.jsbridge
import android.os.Handler
import android.os.Looper
import timber.log.Timber
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.locks.ReentrantLock
abstract class UiThreadJsBridgeDispatcher : JsBridgeDispatcher {
private val handler: Handler = Handler(Looper.getMainLooper())
final override fun dispatchWebCall(string: String): Boolean {
val allow = AtomicBoolean(false)
waitUntilAllow(allow, string)
return allow.get()
}
abstract fun dispatchWebCallOnUiThread(string: String): Boolean
private fun waitUntilAllow(allow: AtomicBoolean, args: String) {
val lock = ReentrantLock()
val allowFinishedCond = lock.newCondition()
val allowFinished = AtomicBoolean()
handler.post {
try {
lock.lock()
allow.set(dispatchWebCallOnUiThread(args))
allowFinished.set(true)
allowFinishedCond.signal()
} catch (e: Exception) {
Timber.tag(TAG_WEB_LOG).e(e)
} finally {
lock.unlock()
}
}
try {
lock.lock()
for (i in 0..10) {
if (!allowFinished.get()) {
allowFinishedCond.await(200, TimeUnit.MILLISECONDS)
} else {
break
}
}
} catch (e: Exception) {
Timber.tag(TAG_WEB_LOG).e(e)
} finally {
lock.unlock()
}
}
} | 0 | Kotlin | 0 | 0 | ff68a80e02e19cecb8bf76243932639635df9fb5 | 1,613 | UniWeb | Apache License 2.0 |
nft-order/api/src/main/kotlin/com/rarible/protocol/nftorder/api/service/CollectionApiService.kt | NFTDroppr | 418,665,809 | true | {"Kotlin": 2329156, "Scala": 37343, "Shell": 6001, "HTML": 547} | package com.rarible.protocol.nftorder.api.service
import com.rarible.protocol.dto.NftCollectionDto
import com.rarible.protocol.dto.NftCollectionsDto
import com.rarible.protocol.dto.NftTokenIdDto
import com.rarible.protocol.nft.api.client.NftCollectionControllerApi
import kotlinx.coroutines.reactive.awaitFirst
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
/**
* Complete proxy for NftCollectionController
*/
@Component
class CollectionApiService(
private val nftCollectionControllerApi: NftCollectionControllerApi
) {
private val logger = LoggerFactory.getLogger(CollectionApiService::class.java)
suspend fun generateTokenId(collection: String, minter: String): NftTokenIdDto {
logger.debug("Generating Collection token id: collection=[{}], minter=[{}]", collection, minter)
return nftCollectionControllerApi.generateNftTokenId(collection, minter).awaitFirst()
}
suspend fun getCollectionById(collection: String): NftCollectionDto {
logger.debug("Get Collection by id: collection=[{}]", collection)
return nftCollectionControllerApi.getNftCollectionById(collection).awaitFirst()
}
suspend fun searchAllCollections(continuation: String?, size: Int?): NftCollectionsDto {
logger.debug("Search all Collections with params: continuation={}, size={}", continuation, size)
return nftCollectionControllerApi.searchNftAllCollections(continuation, size).awaitFirst()
}
suspend fun searchCollectionsByOwner(owner: String, continuation: String?, size: Int?): NftCollectionsDto {
logger.debug(
"Search all Collections with params: owner=[{}], continuation={}, size={}",
owner, continuation, size
)
return nftCollectionControllerApi.searchNftCollectionsByOwner(owner, continuation, size).awaitFirst()
}
} | 0 | Kotlin | 0 | 1 | b1efdaceab8be95429befe80ce1092fab3004d18 | 1,872 | ethereum-indexer | MIT License |
app/src/androidTest/java/com/banno/android/gordontest/ParameterizedTest.kt | TurpIF | 283,850,274 | true | {"Kotlin": 92947} | package com.banno.android.gordontest
import org.junit.Assert
import org.junit.Assume
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@RunWith(Parameterized::class)
class ParameterizedTest(private val parameter: Any) {
companion object {
@JvmStatic
@Parameterized.Parameters
fun parameters(): Iterable<Array<Any>> {
return listOf(
arrayOf(1 as Any),
arrayOf("arg" as Any)
)
}
}
@Test fun parameterizedA() = Assert.assertEquals(1, 1)
@Test fun parameterizedB() = Assume.assumeTrue(1 == parameter)
@Test fun parameterizedC() = Assert.assertTrue(1 == parameter)
@Ignore
@Test
fun parameterizedD() = Assert.assertEquals(1, 1)
}
| 0 | Kotlin | 0 | 0 | 069798c3655bb05bc1e0c9c4c4a4fbb1f9a4f9e2 | 817 | Gordon | Apache License 2.0 |
domain/src/main/java/com/me/domain/quote/usecase/QuoteUseCase.kt | MohamedHatemAbdu | 275,196,930 | false | null | package com.me.domain.quote.usecase
import com.me.domain.quote.entity.QuoteEntity
import com.me.domain.quote.repository.IQuoteRepository
import io.reactivex.Completable
import io.reactivex.Single
class QuoteUseCase constructor(
private val quoteRepository: IQuoteRepository
) {
fun getRandomQuote(refresh: Boolean): Single<QuoteEntity> =
quoteRepository.getQuote(refresh)
fun clearAllQuotes(): Completable =
quoteRepository.clearAllQuotes()
}
| 0 | Kotlin | 0 | 0 | b875c147a1a7ee0591f3e1d0610f78379d9a5473 | 482 | random-quote | Apache License 2.0 |
app/src/main/java/com/example/facedetection/ui/generalPhotosScreen/GeneralPhotoScreenViewModel.kt | alekseytimoshchenko | 174,006,243 | false | null | package com.example.facedetection.ui.generalPhotosScreen
import android.app.Application
import android.arch.lifecycle.*
import com.example.facedetection.App
import com.example.facedetection.R
import com.example.facedetection.data.local.model.IImageFactory
import com.example.facedetection.data.local.model.IImageObj
import com.example.facedetection.data.repo.general_photo_screen.IGeneralRepo
import com.example.facedetection.ui.base.IBaseViewModel
import com.example.facedetection.ui.base.LoadingState
import com.example.facedetection.utils.Constants
import com.example.facedetection.utils.IImageProcessor
import com.example.facedetection.utils.LiveEvent
import io.reactivex.Scheduler
import io.reactivex.Single
import io.reactivex.disposables.CompositeDisposable
import timber.log.Timber
import java.util.*
import java.util.concurrent.TimeUnit
class GeneralPhotoScreenViewModel(
app: Application,
private val imageProcessor: IImageProcessor,
private val repo: IGeneralRepo,
private val WORKER_SCHEDULER: Scheduler,
private val imageFactory: IImageFactory
) : AndroidViewModel(app), IBaseViewModel, LifecycleObserver {
private val screenContent = MutableLiveData<List<IImageObj>>()
private val noResultContentVisibility = MutableLiveData<Boolean>()
private val contentContainerVisibility = MutableLiveData<Boolean>()
private val checkPermission = LiveEvent<Boolean>()
private val progress = LiveEvent<LoadingState>()
private val showToast = LiveEvent<String>()
private val imageRequestUpdates = LiveEvent<UUID>()
override fun setProgressState(state: LoadingState) {
progress.postValue(state)
}
override fun getProgressState(): LiveData<LoadingState> = progress
private val disposable: CompositeDisposable = CompositeDisposable()
init {
checkPermissions()
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate() {
}
private fun checkPermissions() {
checkPermission.postValue(true)
}
fun requestContent() {
disposable.add(
getImageObjsList()
.doOnSubscribe { setProgressState(LoadingState.LOADING) }
.doOnError { setProgressState(LoadingState.ERROR) }
.doFinally { setProgressState(LoadingState.SUCCESS) }
.subscribeOn(WORKER_SCHEDULER)
.subscribe(
{
if (it.isEmpty()) {
setContentContainerVisibility(false)
setNoResultContainerVisibility(true)
doShowToast(getApplication<App>().getString(R.string.empty_folder))
} else {
setNoResultContainerVisibility(false)
setContentContainerVisibility(true)
setContent(it)
doShowToast(
String.format(
"%s %s",
getApplication<App>().getString(R.string.photo_num),
it.size
)
)
}
},
{ Timber.e(it) }
)
)
}
private fun getImageObjsList(): Single<MutableList<IImageObj>> {
return repo.allPhotos()
.map { it.toList() }
.toObservable()
.flatMapIterable { it }
.filter { it.name.contains(Constants.JPG) || it.name.contains(Constants.PNG) }
.map { it.absolutePath }
.map { imageFactory.create(it, IImageObj.NOT_DETECTED) }
.toList()
}
fun showToast() = showToast
private fun doShowToast(message: String) {
showToast.postValue(message)
}
private fun setContent(content: List<IImageObj>) {
screenContent.postValue(content)
}
fun screenContent(): LiveData<List<IImageObj>> = screenContent
override fun onCleared() {
super.onCleared()
if (!disposable.isDisposed) {
disposable.dispose()
}
}
fun doOnTryToLoadContentClick() {
checkPermissions()
}
fun noResultContainerVisibility(): LiveData<Boolean> = noResultContentVisibility
private fun setNoResultContainerVisibility(state: Boolean) {
noResultContentVisibility.postValue(state)
}
fun contentContainerVisibility(): LiveData<Boolean> = contentContainerVisibility
private fun setContentContainerVisibility(state: Boolean) {
contentContainerVisibility.postValue(state)
}
fun doOnDetectFacesClick() {
disposable.add(
imageProcessor.startFaceDetectProcess()
//Just to show loading process
.delay(1000, TimeUnit.MILLISECONDS)
.doOnSubscribe { repo.nukeAllImages() }
.doOnSubscribe { setProgressState(LoadingState.LOADING) }
.doOnError { setProgressState(LoadingState.ERROR) }
.subscribeOn(WORKER_SCHEDULER)
.subscribe(
{ imageWorkerRequestUpdate(it) },
{ Timber.e(it) }
)
)
}
fun permissionDenied() {
setContentContainerVisibility(false)
setNoResultContainerVisibility(true)
}
private fun imageWorkerRequestUpdate(id: UUID) {
imageRequestUpdates.postValue(id)
}
fun subscribeToImageRequestUpdates(): LiveData<UUID> = imageRequestUpdates
fun checkPermission(): LiveData<Boolean> = checkPermission
} | 0 | Kotlin | 0 | 0 | c1408b57d261715f81c76f5ac22c09472eb8a529 | 5,673 | FaceDetection | Do What The F*ck You Want To Public License |
lib-common/src/commonMain/kotlin/com/cren90/kmm/common/events/Event.kt | cren90 | 498,965,485 | false | {"Kotlin": 7806} | package com.cren90.kmm.common.events
import kotlinx.datetime.Clock
class Event(val value: Any) {
var isConsumed = false
private set
fun consume(): Any {
isConsumed = true
return value
}
val postedAt: Long = Clock.System.now().epochSeconds
} | 0 | Kotlin | 0 | 0 | 5b4f7bc7fcdb8b4e64d0053c733624776aed25d5 | 286 | kmm-libs | Apache License 2.0 |
ktvn/src/test/kotlin/com/github/benpollarduk/ktvn/io/tracking/identifier/StepIdentifierTrackerSerializerTest.kt | benpollarduk | 710,310,174 | false | null | package com.github.benpollarduk.ktvn.io.tracking.identifier
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import java.io.File
class StepIdentifierTrackerSerializerTest {
@Test
fun `given toFile when temp file then file exists and has content`() {
// Given
val stepIdentifierTracker = StepIdentifierTracker(mutableListOf("0.0.1"))
val tempFile = File.createTempFile("test", ".json")
tempFile.deleteOnExit()
// When
StepIdentifierTrackerSerializer.toFile(stepIdentifierTracker, tempFile.absolutePath)
// Then
Assertions.assertTrue(tempFile.exists())
Assertions.assertTrue(tempFile.readBytes().isNotEmpty())
}
@Test
fun `given fromFile when temp file with valid contents then result is true`() {
// Given
val stepIdentifierTracker = StepIdentifierTracker(mutableListOf("0.0.1"))
val tempFile = File.createTempFile("test", ".json")
tempFile.deleteOnExit()
// When
StepIdentifierTrackerSerializer.toFile(stepIdentifierTracker, tempFile.absolutePath)
val result = StepIdentifierTrackerSerializer.fromFile(tempFile.absolutePath)
// Then
Assertions.assertTrue(result.result)
}
}
| 2 | null | 0 | 9 | 4326fc7c0bcba099a57d21382407e090dc625bd9 | 1,274 | ktvn | MIT License |
weatherloclib/src/main/java/com/weatherloc/weatherloclib_jkp/open/models/model_for_future/FutureWeatherData.kt | Lilimester | 547,747,268 | false | null | package com.weatherloc.weatherloclib_jkp.open.models.model_for_future
import android.os.Parcel
import android.os.Parcelable
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize
import kotlinx.parcelize.RawValue
@Parcelize
data class FutureWeatherData(
@SerializedName("city")
@Expose
var city: City? = null,
@SerializedName("cod")
@Expose
var cod: String? = null,
@SerializedName("message")
@Expose
var message: Double? = null,
@SerializedName("cnt")
@Expose
var cnt: Integer? = null,
@SerializedName("list")
@Expose
var list: MutableList<IndividualDayData>? = null
) : Parcelable | 0 | Kotlin | 0 | 0 | 262fb583ad2bf5c196e387aa6fd959ba2a28993a | 716 | WeatherLoc | Apache License 2.0 |
dynabuffers-java/src/test/kotlin/dynabuffers/usecase/Schema04Test.kt | leftshiftone | 211,060,714 | false | {"Python": 167058, "Kotlin": 122239, "JavaScript": 58785, "ANTLR": 1629, "TypeScript": 1099} | package dynabuffers.usecase
import dynabuffers.AbstractDynabuffersTest
import dynabuffers.Dynabuffers
import org.junit.jupiter.api.Test
class Schema04Test : AbstractDynabuffersTest() {
@Test
fun testParse() {
val engine = Dynabuffers.parse(Schema04Test::class.java.getResourceAsStream("/schema04.dbs"))
val output = mapOf("m1" to mapOf("s" to "test", ":type" to 1), "m2" to mapOf("t" to "hello world!", ":type" to 0))
assertMap(engine, mapOf("m1" to mapOf("s" to "test"), "m2" to mapOf("t" to "hello world!")), output)
}
}
| 9 | Python | 1 | 4 | d7e26ebf07ca1d13fbb527027350fe65b071dd11 | 564 | dynabuffers | Apache License 2.0 |
architecture/src/main/java/me/robbin/mvvmscaffold/ext/viewmodel/BaseViewModelExt.kt | modestoma114 | 276,022,829 | false | null | package me.robbin.mvvmscaffold.ext.viewmodel
/**
*
* Create by Robbin at 2020/7/19
*/ | 1 | null | 1 | 4 | ca1cef7d8700eb59fd14ffe4e02df7f74e4ac705 | 89 | MVVMScaffold | Apache License 2.0 |
transaction/src/test/java/com/payroc/transaction/TransactionUnitTest.kt | Oliver-Zimmerman | 534,613,528 | false | null | @file:OptIn(ExperimentalCoroutinesApi::class)
package com.payroc.transaction
import com.payroc.transaction.data.model.Card
import com.payroc.transaction.testhelpers.extensions.CoroutinesTestExtension
import com.payroc.transaction.testhelpers.extensions.InstantExecutorExtension
import com.payroc.transaction.testhelpers.extensions.getOrAwaitValue
import io.mockk.MockKAnnotations
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.Assert.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.Mockito
import org.mockito.Mockito.spy
import org.mockito.Spy
@ExtendWith(InstantExecutorExtension::class, CoroutinesTestExtension::class)
class TransactionUnitTest {
private val testDispatcher = TestCoroutineDispatcher()
@Spy
private lateinit var transaction: Transaction
@Spy
private lateinit var payrocClient: PayrocClient
@BeforeEach
fun setUp() {
MockKAnnotations.init(this, true, true, true)
Dispatchers.setMain(testDispatcher)
payrocClient = spy(PayrocClient("5140001", ""))
transaction = spy(Transaction(1.00, "5140001", "", payrocClient))
}
@Test
fun `provideCard with invalid API key adjusts transaction state to Error`() =
runTest(testDispatcher) {
val mockCard = Mockito.mock(Card::class.java)
transaction.provideCard(mockCard)
assertEquals(
payrocClient.getStateResponse().getOrAwaitValue(),
TransactionState.ERROR
)
}
} | 0 | Kotlin | 0 | 0 | ac1583b619c74b435419eaac43ab785aef2e01b4 | 1,793 | payroc | Apache License 2.0 |
app/src/main/java/com/lucianbc/receiptscan/domain/receipts/ReceiptsRepository.kt | lucianbc | 183,749,890 | false | null | package com.lucianbc.receiptscan.domain.receipts
import com.lucianbc.receiptscan.domain.model.Category
import io.reactivex.Flowable
import java.util.*
interface ReceiptsRepository {
fun listReceipts(): Flowable<List<ReceiptListItem>>
fun getReceipt(receiptId: ReceiptId): Flowable<Receipt>
fun getAvailableCurrencies(): Flowable<List<Currency>>
fun getAvailableMonths(currency: Currency): Flowable<List<Date>>
fun getAllSpendings(currency: Currency, month: Date): Flowable<List<SpendingGroup>>
fun getTransactions(currency: Currency, month: Date, category: Category): Flowable<List<ReceiptListItem>>
fun getAllTransactions(currency: Currency, month: Date): Flowable<List<ReceiptListItem>>
} | 13 | null | 1 | 2 | 05950c87f2eda6f53f886e340459aa13cdbdd621 | 720 | ReceiptScan | Apache License 2.0 |
app/src/main/java/com/perol/asdpl/pixivez/adapters/TrendingTagAdapter.kt | code871 | 214,927,561 | true | {"Java": 873909, "Kotlin": 421220} | package com.perol.asdpl.pixivez.adapters
import android.widget.ImageView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.perol.asdpl.pixivez.R
import com.perol.asdpl.pixivez.responses.TrendingtagResponse
import com.perol.asdpl.pixivez.services.GlideApp
/**
* Created by asdpl on 2018/2/20.
*/
class TrendingTagAdapter(layoutResId: Int, data: List<TrendingtagResponse.TrendTagsBean>?) : BaseQuickAdapter<TrendingtagResponse.TrendTagsBean, BaseViewHolder>(layoutResId, data) {
override fun convert(helper: BaseViewHolder, item: TrendingtagResponse.TrendTagsBean) {
helper.setText(R.id.textview_tag, item.tag)
val imageView = helper.itemView.findViewById<ImageView>(R.id.imageview_trendingtag)
GlideApp.with(imageView.context).load(item.illust.image_urls.square_medium).placeholder(R.mipmap.ic_noimage).skipMemoryCache(true).into(imageView)
}
}
| 0 | null | 0 | 0 | c4401cd0b503c6edf82e037478fb2c603bbeebfb | 952 | Pix-EzViewer | MIT License |
product/web3modal/src/main/kotlin/com/walletconnect/web3/modal/utils/Image.kt | WalletConnect | 435,951,419 | false | {"Kotlin": 2502705, "Java": 4366, "Shell": 1892} | package com.walletconnect.web3.modal.utils
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.ColorMatrix
import coil.request.ImageRequest
import com.walletconnect.android.BuildConfig
import com.walletconnect.android.internal.common.model.ProjectId
import com.walletconnect.android.internal.common.wcKoinApp
internal fun ImageRequest.Builder.imageHeaders() = apply {
addHeader("x-project-id", wcKoinApp.koin.get<ProjectId>().value)
addHeader("x-sdk-version", BuildConfig.SDK_VERSION)
addHeader("x-sdk-type", "w3m")
}
internal val grayColorFilter = ColorFilter.colorMatrix(ColorMatrix().apply { setToSaturation(0f) })
| 78 | Kotlin | 71 | 199 | e373c535d7cefb2f932368c79622ac05763b411a | 665 | WalletConnectKotlinV2 | Apache License 2.0 |
core/src/main/kotlin/materialui/components/zoom/zoom.kt | nikanorov | 275,884,338 | true | {"Kotlin": 473607} | package materialui.components.zoom
import materialui.Zoom
import materialui.reacttransiton.RTransitionProps
import materialui.styles.muitheme.MuiTheme
import react.RBuilder
import react.RProps
external interface ZoomProps : RTransitionProps, RProps {
var style: Any?
var theme: MuiTheme?
}
fun RBuilder.zoom(block: ZoomElementBuilder.() -> Unit)
= child(ZoomElementBuilder(Zoom).apply(block).create())
| 0 | Kotlin | 0 | 1 | e4ece75415d9d844fbaa202ffc91f04c8415b4a4 | 417 | kotlin-material-ui | MIT License |
src/main/kotlin/bia/model/expressions/logicalExpressions.kt | cubuspl42 | 451,099,116 | false | null | package bia.model.expressions
import bia.interpreter.DynamicScope
import bia.model.BooleanType
import bia.model.BooleanValue
import bia.model.NumberType
import bia.model.Type
import bia.model.Value
import bia.model.asBooleanValue
import bia.model.asNumberValue
import bia.parser.StaticScope
import bia.type_checker.TypeCheckError
data class LessThenExpression(
val left: Expression,
val right: Expression,
) : Expression {
override fun determineTypeDirectly(context: TypeDeterminationContext): Type =
determineTypeDirectlyForLogicalBinaryExpression(
expression = this,
context = context,
left = left,
right = right,
errorMessage = { l, r -> "Tried compare (<) expressions of type $l and $r" },
)
override fun evaluate(scope: DynamicScope): Value =
evaluateNumberLogicalExpression(
scope = scope,
left = left,
right = right,
) { a, b -> a < b }
}
data class LessThenExpressionB(
val left: ExpressionB,
val right: ExpressionB,
) : ExpressionB {
override fun build(scope: StaticScope) = LessThenExpression(
left = left.build(scope = scope),
right = right.build(scope = scope),
)
}
data class GreaterThenExpression(
val left: Expression,
val right: Expression,
) : Expression {
override fun determineTypeDirectly(context: TypeDeterminationContext): Type =
determineTypeDirectlyForLogicalBinaryExpression(
expression = this,
context = context,
left = left,
right = right,
errorMessage = { l, r -> "Tried compare (>) expressions of type $l and $r" },
)
override fun evaluate(scope: DynamicScope): Value =
evaluateNumberLogicalExpression(
scope = scope,
left = left,
right = right,
) { a, b -> a > b }
}
data class GreaterThenExpressionB(
val left: ExpressionB,
val right: ExpressionB,
) : ExpressionB {
override fun build(scope: StaticScope) = GreaterThenExpression(
left = left.build(scope = scope),
right = right.build(scope = scope),
)
}
data class OrExpression(
val left: Expression,
val right: Expression,
) : Expression {
override fun determineTypeDirectly(context: TypeDeterminationContext): Type =
determineTypeDirectlyForLogicalBinaryExpression(
expression = this,
context = context,
left = left,
right = right,
errorMessage = { l, r -> "Tried to perform logical operation (or) on expressions of type $l and $r" },
)
override fun evaluate(scope: DynamicScope): Value =
evaluateLogicalBinaryExpression(
scope = scope,
left = left,
right = right,
) { a, b -> a || b }
}
data class OrExpressionB(
val left: ExpressionB,
val right: ExpressionB,
) : ExpressionB {
override fun build(scope: StaticScope) = OrExpression(
left = left.build(scope = scope),
right = right.build(scope = scope),
)
}
data class AndExpression(
val left: Expression,
val right: Expression,
) : Expression {
override fun determineTypeDirectly(context: TypeDeterminationContext): Type =
determineTypeDirectlyForLogicalBinaryExpression(
expression = this,
context = context,
left = left,
right = right,
errorMessage = { l, r -> "Tried to perform logical operation (and) on expressions of type $l and $r" },
)
override fun evaluate(scope: DynamicScope): Value =
evaluateLogicalBinaryExpression(
scope = scope,
left = left,
right = right,
) { a, b -> a && b }
}
data class AndExpressionB(
val left: ExpressionB,
val right: ExpressionB,
) : ExpressionB {
override fun build(scope: StaticScope) = AndExpression(
left = left.build(scope = scope),
right = right.build(scope = scope),
)
}
data class NotExpression(
val negated: Expression,
) : Expression {
override fun determineTypeDirectly(context: TypeDeterminationContext): Type {
val extendedContext = context.withVisited(expression = this)
val negatedType = negated.determineType(context = extendedContext)
return if (negatedType !is BooleanType) {
throw TypeCheckError("Tried to perform logical operation (not) on expression of type ${negatedType.toPrettyString()}")
} else BooleanType
}
override fun evaluate(scope: DynamicScope): Value {
val negatedBoolean = asLogicalValue(value = negated.evaluate(scope = scope))
return BooleanValue(
value = !negatedBoolean.value,
)
}
}
data class NotExpressionB(
val negated: ExpressionB,
) : ExpressionB {
override fun build(scope: StaticScope) = NotExpression(
negated = negated.build(scope = scope),
)
}
data class EqualsExpression(
val left: Expression,
val right: Expression,
) : Expression {
override fun determineTypeDirectly(context: TypeDeterminationContext): Type {
val extendedContext = context.withVisited(expression = this)
val leftType = left.determineType(context = extendedContext)
val rightType = right.determineType(context = extendedContext)
return if (leftType != rightType) {
throw TypeCheckError("Tried to compare expressions of type ${leftType.toPrettyString()} and ${rightType.toPrettyString()}")
} else BooleanType
}
override fun evaluate(scope: DynamicScope): Value {
val leftValue = left.evaluate(scope = scope)
val rightValue = right.evaluate(scope = scope)
return BooleanValue(
value = leftValue.value == rightValue.value,
)
}
}
data class EqualsExpressionB(
val left: ExpressionB,
val right: ExpressionB,
) : ExpressionB {
override fun build(scope: StaticScope) = EqualsExpression(
left = left.build(scope = scope),
right = right.build(scope = scope),
)
}
private fun evaluateNumberLogicalExpression(
scope: DynamicScope,
left: Expression,
right: Expression,
calculate: (left: Double, right: Double) -> Boolean,
): BooleanValue {
val leftNumber = left.evaluate(scope = scope).asNumberValue()
val rightNumber = right.evaluate(scope = scope).asNumberValue()
return BooleanValue(
value = calculate(leftNumber.value, rightNumber.value),
)
}
private fun determineTypeDirectlyForLogicalBinaryExpression(
expression: Expression,
context: TypeDeterminationContext,
left: Expression,
right: Expression,
errorMessage: (leftType: String, rightType: String) -> String,
): Type {
val extendedContext = context.withVisited(expression = expression)
val leftType = left.determineType(context = extendedContext)
val rightType = right.determineType(context = extendedContext)
return if (leftType !is BooleanType || rightType !is BooleanType) {
throw TypeCheckError(
message = errorMessage(
leftType.toPrettyString(),
rightType.toPrettyString(),
),
)
} else NumberType
}
private fun evaluateLogicalBinaryExpression(
scope: DynamicScope,
left: Expression,
right: Expression,
calculate: (left: Boolean, right: Boolean) -> Boolean,
): BooleanValue {
val leftBoolean = asLogicalValue(value = left.evaluate(scope = scope))
val rightBoolean = asLogicalValue(value = right.evaluate(scope = scope))
return BooleanValue(
value = calculate(leftBoolean.value, rightBoolean.value),
)
}
private fun asLogicalValue(value: Value) = value.asBooleanValue(
message = "Cannot perform logical operations on non-boolean",
)
| 0 | Kotlin | 0 | 4 | 16fef1cc3eba846601f626bcd74b4e8d8407862d | 7,877 | bia | Apache License 2.0 |
Unit-2-Building-App-UI/Kotlin-Fundamentals/Practice-Kotlin-Fundamentals/Mobile-notifications.kt | MayankKrSohanda | 733,267,531 | false | {"Kotlin": 97965} | fun main() {
val morningNotification = 51
val eveningNotification = 135
printNotificationSummary(morningNotification)
printNotificationSummary(eveningNotification)
}
fun printNotificationSummary(numberOfMessages: Int) {
if(numberOfMessages < 100) {
println("You have 51 notifications.")
} else {
println("Your phone is blowing up! You have 99+ notifications.")
}
} | 0 | Kotlin | 0 | 0 | b541a3b75ba467d8f843e8a521ae728948ba6848 | 415 | Android-Basics-With-Compose | MIT License |
app/src/main/java/com/agnibh/chatapp/MessageAdapter.kt | Aritram26 | 724,964,746 | false | {"Kotlin": 12323} | package com.agnibh.chatapp
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.google.firebase.auth.FirebaseAuth
class MessageAdapter(val context: Context, val messageList: ArrayList<Message>):
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
val ITEM_RECEIVE = 1;
val ITEM_SENT = 2;
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
if (viewType==1){
val view: View = LayoutInflater.from(context).inflate(R.layout.receive,parent,false)
return ReceiveViewHolder(view)
} else {
val view: View = LayoutInflater.from(context).inflate(R.layout.sent,parent,false)
return SentViewHolder(view)
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val currentMessage = messageList[position]
if (holder.javaClass == SentViewHolder::class.java){
val viewHolder = holder as SentViewHolder
holder.sentMessage.text = currentMessage.message
}else {
// do dtuff for receive view holder
val viewHolder = holder as ReceiveViewHolder
holder.receiveMessage.text= currentMessage.message
}
}
override fun getItemViewType(position: Int): Int {
val currentMessage = messageList[position]
if (FirebaseAuth.getInstance().currentUser.uid.equals(currentMessage.senderId)) {
return ITEM_SENT
} else {
return ITEM_RECEIVE
}
}
override fun getItemCount(): Int {
return messageList.size
}
class SentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
val sentMessage = itemView.findViewById<TextView>(R.id.txt_sent_message)
}
class ReceiveViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){
val receiveMessage = itemView.findViewById<TextView>(R.id.txt_receive_message)
}
} | 0 | Kotlin | 0 | 0 | b9d08f533a3f604b386973741e75bc90bfb432bc | 2,159 | ChatApp | MIT License |
app/src/main/java/be/hogent/faith/faith/emotionCapture/enterEventDetails/SaveEventDialog.kt | hydrolythe | 353,694,404 | false | null | package be.hogent.faith.faith.emotionCapture.enterEventDetails
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.Observer
import be.hogent.faith.R
import be.hogent.faith.databinding.DialogSaveEventBinding
import be.hogent.faith.faith.UserViewModel
import be.hogent.faith.faith.di.KoinModules
import org.koin.android.ext.android.getKoin
import org.koin.android.viewmodel.ext.android.sharedViewModel
class SaveEventDialog : DialogFragment() {
private lateinit var saveEventBinding: DialogSaveEventBinding
private val eventDetailsViewModel: EventViewModel by sharedViewModel()
private val userViewModel: UserViewModel = getKoin().getScope(KoinModules.USER_SCOPE_ID).get()
companion object {
fun newInstance(): SaveEventDialog {
return SaveEventDialog()
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return Dialog(requireActivity(), R.style.Dialog_NearlyFullScreen).apply {
setStyle(STYLE_NO_TITLE, 0)
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
saveEventBinding =
DataBindingUtil.inflate(inflater, R.layout.dialog_save_event, container, false)
saveEventBinding.eventViewModel = eventDetailsViewModel
saveEventBinding.userViewModel = userViewModel
saveEventBinding.lifecycleOwner = this@SaveEventDialog
return saveEventBinding.root
}
override fun onStart() {
super.onStart()
startListeners()
}
private fun startListeners() {
eventDetailsViewModel.dateButtonClicked.observe(this, Observer {
EventDateDialog.newInstance().show(requireActivity().supportFragmentManager, null)
})
// when a user starts typing error message will disappear
saveEventBinding.txtSaveEventTitle.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(p0: Editable?) {}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
userViewModel.clearErrorMessage()
}
})
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
userViewModel.clearErrorMessage()
}
} | 0 | Kotlin | 0 | 0 | 14c6aec4b3c0a42bc73a7f779964d166fffeea20 | 2,726 | FAITHAndroid | The Unlicense |
app/src/main/java/uz/algorithmgateway/tezkorakfa/presenter/measurer/ui/MeasurerActivity.kt | JahongirmirzoDv | 507,823,972 | false | null | package uz.algorithmgateway.tezkorakfa.presenter.measurer.ui
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import uz.algorithmgateway.tezkorakfa.base.MyApplication
import uz.algorithmgateway.tezkorakfa.databinding.ActivityMeasurerBinding
import uz.algorithmgateway.tezkorakfa.presenter.measurer.viewmodel.DbViewmodel
import uz.algorithmgateway.tezkorakfa.presenter.ui.utils.SharedPref
import javax.inject.Inject
import kotlin.coroutines.CoroutineContext
class MeasurerActivity : AppCompatActivity(), CoroutineScope{
private lateinit var binding: ActivityMeasurerBinding
private var back = false
private val sharedPref by lazy { SharedPref(this) }
@Inject
lateinit var dbViewmodel: DbViewmodel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
MyApplication.appComponent.measure(this)
binding = ActivityMeasurerBinding.inflate(layoutInflater)
setContentView(binding.root)
}
override val coroutineContext: CoroutineContext
get() = Job()
// override fun onBackPressed() {
// if (back) {
// super.onBackPressed()
// finishAffinity()
// }
// val handler = Handler(Looper.getMainLooper())
// this.back = true
// Toast.makeText(this, "Chiqish uchun ikki marta bosing", Toast.LENGTH_SHORT).show()
// handler.postDelayed({
// back = false
// }, 2000)
// }
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.clear()
}
} | 0 | Kotlin | 0 | 1 | b81e2b43038070c2acf7694f08dd37c6d7aaafb0 | 1,688 | TezkorAkfa | Creative Commons Zero v1.0 Universal |
content/src/main/kotlin/com/sangsiklog/exception/StatusExceptionInterceptor.kt | SangsikLog | 825,352,399 | false | {"Kotlin": 115434, "Dockerfile": 3751} | package com.sangsiklog.exception
import com.fasterxml.jackson.databind.ObjectMapper
import com.sangsiklog.core.api.exception.ErrorType
import com.sangsiklog.core.api.exception.GrpcCustomException
import io.grpc.*
class StatusExceptionInterceptor: ServerInterceptor {
private val objectMapper = ObjectMapper()
override fun <ReqT : Any?, RespT : Any?> interceptCall(
call: ServerCall<ReqT, RespT>,
headers: Metadata,
next: ServerCallHandler<ReqT, RespT>
): ServerCall.Listener<ReqT> {
val serverCall =
object : ForwardingServerCall.SimpleForwardingServerCall<ReqT, RespT>(call) {
override fun close(status: Status, trailers: Metadata) {
if (status.isOk || status.cause == null) {
super.close(status, trailers)
} else {
val errorStatus: ErrorStatus
val newStatus: Status
when (val throwable = status.cause) {
is GrpcCustomException -> {
errorStatus = ErrorStatus(throwable.errorType, throwable.toString())
newStatus = Status.INTERNAL.withDescription(
objectMapper.writeValueAsString(errorStatus)
)
}
else -> {
errorStatus = ErrorStatus(ErrorType.UNKNOWN, throwable.toString())
newStatus = Status.UNKNOWN.withDescription(
objectMapper.writeValueAsString(errorStatus)
)
}
}
super.close(newStatus, trailers)
}
}
}
return next.startCall(serverCall, headers)
}
} | 3 | Kotlin | 0 | 0 | 4dcabf8c38c3796fd5f516b8dbe4fd1d72a45f88 | 1,952 | sangsiklog-api | MIT License |
code/jvm/src/main/kotlin/pt/isel/leic/ptgest/repository/TraineeRepo.kt | PTGest | 761,908,487 | false | {"Kotlin": 405169, "Vue": 247495, "TypeScript": 79316, "PLpgSQL": 18596, "CSS": 1471, "HTML": 368, "Shell": 274} | package pt.isel.leic.ptgest.repository
import pt.isel.leic.ptgest.domain.trainee.model.TraineeDetails
import java.util.*
interface TraineeRepo {
fun getTraineeDetails(traineeId: UUID): TraineeDetails?
fun isTraineeAssignedToTrainer(traineeId: UUID, trainerId: UUID): Boolean
}
| 0 | Kotlin | 0 | 6 | b94fedfe747862fbc7190e6aced5b3e84833590f | 289 | PTGest | MIT License |
biz/detail/src/main/kotlin/io/goooler/demoapp/detail/model/RepoDetailModel.kt | Goooler | 188,988,687 | false | null | package io.goooler.demoapp.detail.model
data class RepoDetailModel(
val fullName: String = "",
val description: String = "",
val license: String = "",
val starsCount: Int = 0,
val forksCount: Int = 0,
val openIssuesCount: Int = 0
)
| 6 | null | 7 | 70 | 7f47125cc66743aac154671a4e18699acec77fd2 | 245 | DemoApp | Apache License 2.0 |
sdk/src/main/kotlin/org/arnhold/sdk/tools/rdfParsing/RdfResourceProvider.kt | larnhold | 695,175,294 | false | {"Kotlin": 179546, "Jupyter Notebook": 62908, "Java": 11111} | package org.arnhold.sdk.tools.rdfParsing
import org.apache.jena.rdf.model.Model
import org.apache.jena.rdf.model.Property
import org.apache.jena.rdf.model.Resource
abstract class RdfResourceProvider {
companion object {
const val PREFIX = "https://w3id.org/dcso/ns/core#"
}
fun toResource(model: Model,
name:String,
dataProperties: List<DataPropertyDefinition>,
objectProperties: List<ObjectPropertyDefinition>,
resourceProperties: List<ResourcePropertyDefinition>?
): Resource {
val subject = model.createResource(String.format("%s%s", PREFIX, name))
dataProperties.forEach { addDataProperties(subject, it.predicate, it.values) }
objectProperties.forEach { addObjectProperties(model, subject, it.predicate, it.objects, it.rootObjName, it.objName) }
resourceProperties?.forEach { addResourceProperties(subject, it.predicate, it.objects) }
return subject
}
fun toResource(model: Model,
name:String,
dataProperties: List<DataPropertyDefinition>,
objectProperties: List<ObjectPropertyDefinition>,
): Resource {
return toResource(model, name, dataProperties, objectProperties, listOf())
}
abstract fun toResource(model: Model, name: String): Resource
private fun addDataProperties(subj: Resource, verb: Property, objects: List<String?>?) {
objects?.let {
objects.forEach { addDataProperty(subj, verb, it) }
}
}
private fun addObjectProperties(model: Model, subj: Resource, verb: Property, objects: List<RdfResourceProvider?>?, rootObjName: String, name: String) {
objects?.let {
objects.forEachIndexed { index, obj -> addObjectProperty(model, subj, verb, obj, rootObjName + "_" + name + "_" + index) }
}
}
private fun addResourceProperties(subj: Resource, verb: Property, objects: List<Resource?>?) {
objects?.let {
objects.forEach { obj -> addResourceAsProperty(subj, verb, obj) }
}
}
private fun addDataProperty(subj: Resource, verb: Property, obj: String?) {
obj?.let {
subj.addProperty(verb, it)
}
}
private fun addObjectProperty(model: Model, subj: Resource, verb: Property, obj: RdfResourceProvider?, name: String) {
obj?.let {
subj.addProperty(verb, obj.toResource(model, name))
}
}
private fun addResourceAsProperty(subj: Resource, verb: Property, obj: Resource?) {
obj?.let {
subj.addProperty(verb, obj)
}
}
} | 0 | Kotlin | 0 | 2 | 8551cab14415f90af8a91e6325814e9c0dd6e6a9 | 2,667 | maDMP-Assesment | MIT License |
kotlin/src/androidTest/java/app/rive/runtime/kotlin/core/RiveStateMachineStateResolutionTest.kt | rive-app | 299,578,948 | false | {"Kotlin": 371044, "C++": 141646, "Shell": 13238, "CMake": 5518, "Makefile": 2286, "Java": 1207} | package app.rive.runtime.kotlin.core
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.internal.runner.junit4.statement.UiThreadStatement
import app.rive.runtime.kotlin.RiveAnimationView
import app.rive.runtime.kotlin.test.R
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class RiveStateMachineStateResolutionTest {
private val testUtils = TestUtils()
private val appContext = testUtils.context
private lateinit var mockView: RiveAnimationView
/*
State Machine overview:
Inputs:
choice - number = default 3
jump - trigger
Map:
entry -> choice 1 -> jump 1
-> choice 2 -> jump 2
-> choice 3 -> choice 3 part 2
*/
@Before
fun init() {
mockView = TestUtils.MockNoopRiveAnimationView(appContext)
}
@Test
fun autoPlayTriggersStateResolution() {
UiThreadStatement.runOnUiThread {
val observer = TestUtils.Observer()
mockView.registerListener(observer)
mockView.setRiveResource(
R.raw.state_machine_state_resolution,
stateMachineName = "StateResolution",
autoplay = true
)
assertEquals(1, observer.states.size)
}
}
@Test
fun disablingAutoplaySuppressesStateResolution() {
UiThreadStatement.runOnUiThread {
val observer = TestUtils.Observer()
mockView.registerListener(observer)
mockView.setRiveResource(
R.raw.state_machine_state_resolution,
stateMachineName = "StateResolution",
autoplay = false
)
assertEquals(0, observer.states.size)
}
}
@Test
fun explicitPlayTriggersStateResolution() {
UiThreadStatement.runOnUiThread {
val observer = TestUtils.Observer()
mockView.registerListener(observer)
mockView.setRiveResource(
R.raw.state_machine_state_resolution,
stateMachineName = "StateResolution",
autoplay = false
)
mockView.play("StateResolution", isStateMachine = true)
assertEquals(1, observer.states.size)
assertEquals("StateResolution", observer.states[0].stateMachineName)
assertEquals("Choice 3 part 2", observer.states[0].stateName)
}
}
@Test
fun explicitPlayCanSuppressTriggeringStateResolution() {
UiThreadStatement.runOnUiThread {
val observer = TestUtils.Observer()
mockView.registerListener(observer)
mockView.setRiveResource(
R.raw.state_machine_state_resolution,
stateMachineName = "StateResolution",
autoplay = false
)
mockView.play(
"StateResolution",
isStateMachine = true,
settleInitialState = false
)
assertEquals(0, observer.states.size)
}
}
@Test
fun canAlterInitialStateBeforePlay() {
UiThreadStatement.runOnUiThread {
val observer = TestUtils.Observer()
mockView.registerListener(observer)
mockView.setRiveResource(
R.raw.state_machine_state_resolution,
stateMachineName = "StateResolution",
autoplay = false
)
mockView.setNumberState("StateResolution", "Choice", 1f)
mockView.play(
"StateResolution",
isStateMachine = true,
)
assertEquals(1, observer.states.size)
assertEquals("StateResolution", observer.states[0].stateMachineName)
assertEquals("Choice 1", observer.states[0].stateName)
}
}
@Test
fun getUnknownStateNameWhenAnimationIsMissing() {
// This test will crash the tester when it does not work
UiThreadStatement.runOnUiThread {
val observer = TestUtils.Observer()
mockView.registerListener(observer)
mockView.setRiveResource(
R.raw.empty_animation_state,
autoplay = false
)
mockView.play(
"State Machine 1",
isStateMachine = true,
)
assertEquals(1, observer.states.size)
assertEquals("Unknown", observer.states[0].stateName)
}
}
@Test
fun triggerDoesNothingWithoutStateResolution() {
UiThreadStatement.runOnUiThread {
val observer = TestUtils.Observer()
mockView.registerListener(observer)
mockView.setRiveResource(
R.raw.state_machine_state_resolution,
stateMachineName = "StateResolution",
autoplay = false
)
mockView.setNumberState("StateResolution", "Choice", 2f)
mockView.play(
"StateResolution",
isStateMachine = true,
settleInitialState = false
)
mockView.fireState("StateResolution", "Jump")
assert(mockView.artboardRenderer != null)
// trigger is registered, but it wouldn't be picked up until we evaluate the state next.
mockView.artboardRenderer!!.advance(0f)
assertEquals("StateResolution", observer.states[0].stateMachineName)
assertEquals("Choice 2", observer.states[0].stateName)
}
}
@Test
fun triggerFiresWithWithStateResolution() {
UiThreadStatement.runOnUiThread {
val observer = TestUtils.Observer()
mockView.registerListener(observer)
mockView.setRiveResource(
R.raw.state_machine_state_resolution,
stateMachineName = "StateResolution",
autoplay = false
)
mockView.setNumberState("StateResolution", "Choice", 2f)
mockView.play(
"StateResolution",
isStateMachine = true,
settleInitialState = true
)
mockView.fireState("StateResolution", "Jump")
assert(mockView.artboardRenderer != null)
// trigger is registered, but it wont be picked up until we evaluate the state next.
mockView.artboardRenderer!!.advance(0f)
assertEquals(2, observer.states.size)
assertEquals("StateResolution", observer.states[0].stateMachineName)
assertEquals("Choice 2", observer.states[0].stateName)
assertEquals("StateResolution", observer.states[1].stateMachineName)
assertEquals("Jump 2", observer.states[1].stateName)
}
}
} | 24 | Kotlin | 27 | 287 | b3b1802b7e219285471eaa39ab57da2e559dd366 | 6,854 | rive-android | MIT License |
buildSrc/src/main/kotlin/dokka.kt | NextFaze | 90,596,780 | false | null | import org.gradle.api.Project
import org.gradle.jvm.tasks.Jar
import org.gradle.kotlin.dsl.*
import org.jetbrains.dokka.DokkaConfiguration
import org.jetbrains.dokka.gradle.DokkaTask
import org.jetbrains.dokka.gradle.LinkMapping
import java.net.URL
@Suppress("unused")
fun Project.configureDokka() {
when {
isAndroid -> apply { plugin("org.jetbrains.dokka-android") }
else -> apply { plugin("org.jetbrains.dokka") }
}
task<DokkaTask> {
externalDocumentationLink {
url = URL("https://nextfaze.github.io/dev-fun/")
}
dokkaFatJar = Dependency.dokkaFatJar
}
val dokkaJavadoc = task<DokkaTask>("dokkaJavadoc") {
enabled = !isPublishToMavenLocal
includes = listOf("Module.md")
linkMapping {
dir = "src/main/java"
url = "https://github.com/NextFaze/dev-fun/tree/master/${project.name}/src/main/java"
suffix = "#L"
}
outputFormat = "javadoc"
outputDirectory = "$buildDir/dokkaJavadoc"
externalDocumentationLink {
url = URL("https://nextfaze.github.io/dev-fun/")
}
dokkaFatJar = Dependency.dokkaFatJar
sourceDirs = mainSourceFiles.filter { it.isDirectory }
}
task<Jar>("javadocJar") {
enabled = !isPublishToMavenLocal
group = "publishing"
classifier = "javadoc"
dependsOn(dokkaJavadoc)
from(dokkaJavadoc.outputDirectory)
addArtifact("archives", this, this)
}
}
private fun DokkaTask.externalDocumentationLink(body: DokkaConfiguration.ExternalDocumentationLink.Builder.() -> Unit) =
externalDocumentationLinks.add(DokkaConfiguration.ExternalDocumentationLink.Builder().apply(body).build())
private fun DokkaTask.linkMapping(body: LinkMapping.() -> Unit) = linkMappings.add(LinkMapping().apply(body))
| 5 | null | 4 | 51 | cbf83014e478426750a2785b1e4e6a22d6964698 | 1,860 | dev-fun | Apache License 2.0 |
test/integ/KotlinDelegateProperty.kt | facebook | 54,664,770 | false | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import kotlin.reflect.KProperty
class Delegate1 {
operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
return "$thisRef, '${property.name}'"
}
operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
println("$value '${property.name}' $thisRef")
}
}
class Example {
var p: String by Delegate1()
}
| 58 | C++ | 603 | 5,497 | a33b8b8ee998d093b6efee1289184e8176565652 | 546 | redex | MIT License |
performance/src/main/java/io/github/caoshen/androidadvance/performance/memory/MemoryMeasure.kt | caoshen | 290,115,293 | false | null | package io.github.caoshen.androidadvance.performance.memory
import android.app.ActivityManager
import android.content.Context
import android.util.Log
const val M = 1024 * 1024
const val TAG = "XMemory"
/**
* https://juejin.cn/post/7098257692828893220
* Android 内存基础知识
*/
//E/XMemory: Dalvik MaxMemory:256M
//E/XMemory: Dalvik MemoryClass:256
//E/XMemory: Dalvik LargeMemoryClass:512
//E/XMemory: system total memory:7157M
//E/XMemory: system available memory:2544M
//E/XMemory: system whether low memory status:false
//E/XMemory: system low memory threshold:216M
fun getMaxMemoryInfo(appContext: Context) {
val runtime = Runtime.getRuntime()
val maxMemory = runtime.maxMemory()
Log.e(TAG, "Dalvik MaxMemory:${maxMemory / M}M")
val activityManager = appContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
// 系统为每个app分配的内存,调用了 dalvik.vm.heapsize
Log.e(TAG, "Dalvik MemoryClass:${activityManager.memoryClass}")
// 系统为每个app分配的最大内存,超过就导致OOM
Log.e(TAG, "Dalvik LargeMemoryClass:${activityManager.largeMemoryClass}")
val info = ActivityManager.MemoryInfo()
activityManager.getMemoryInfo(info)
Log.e(TAG, "system total memory:${info.totalMem / M}M")
Log.e(TAG, "system available memory:${info.availMem / M}M")
Log.e(TAG, "system whether low memory status:${info.lowMemory}")
Log.e(TAG, "system low memory threshold:${info.threshold / M}M")
} | 0 | Kotlin | 0 | 2 | b128cdd72dd81ef2bc3f3510f808f198196ef889 | 1,416 | AndroidAdvance | MIT License |
btsdk/src/main/java/com/danny/bt/util/BtConnectUtils.kt | dannycx | 310,445,112 | false | {"Kotlin": 90927, "Java": 34893, "AIDL": 319} | package com.danny.bt.util
import android.bluetooth.BluetoothDevice
import android.text.TextUtils
/**
*
*
* @author danny
* @since 2022/2/17
*/
object BtConnectUtils {
/**
* 是否有效的连接设备
*/
fun isValidDevice(device: BluetoothDevice?) = when(device) {
null -> false
else -> !TextUtils.isEmpty(device.address)
}
} | 0 | Kotlin | 0 | 0 | 5fbfd4a5db1849d67817364b73f9c9e9b16a2e72 | 353 | XTools | Apache License 2.0 |
task/src/main/kotlin/xyz/chener/zp/task/service/TaskInfoService.kt | Chener-03 | 598,518,767 | false | {"Java": 972423, "Kotlin": 92123, "Dockerfile": 2811, "Shell": 893, "Batchfile": 692} | package xyz.chener.zp.task.service
import com.baomidou.mybatisplus.extension.service.IService
import com.github.pagehelper.PageInfo
import org.springframework.web.bind.annotation.ModelAttribute
import org.springframework.web.bind.annotation.RequestBody
import xyz.chener.zp.common.entity.vo.PageParams
import xyz.chener.zp.task.entity.TaskInfo
import xyz.chener.zp.task.entity.TaskInfoVo
interface TaskInfoService : IService<TaskInfo> {
fun getTaskLists(taskInfo: TaskInfoVo, pageParams: PageParams, username:String): PageInfo<TaskInfoVo>
fun saveTaskInfo(taskInfo:TaskInfoVo):Boolean
}
| 1 | null | 1 | 1 | b5f14080d0ae0e9e3a121bb785698b9ae6d34ec7 | 599 | zp-ms1 | MIT License |
agp-7.1.0-alpha01/tools/base/build-system/gradle-core/src/test/java/com/android/build/gradle/internal/transforms/testdata/OuterClass.kt | jomof | 502,039,754 | true | {"Markdown": 63, "Java Properties": 56, "Shell": 31, "Batchfile": 12, "Proguard": 30, "CMake": 10, "Kotlin": 3443, "C++": 594, "Java": 4446, "HTML": 34, "Makefile": 14, "RenderScript": 22, "C": 30, "JavaScript": 2, "CSS": 3, "INI": 11, "Filterscript": 11, "Prolog": 1, "GLSL": 1, "Gradle Kotlin DSL": 5, "Python": 12, "Dockerfile": 2} | package com.android.build.gradle.internal.transforms.testdata
class OuterClass {
class InnerClass {}
} | 1 | null | 1 | 0 | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | 106 | CppBuildCacheWorkInProgress | Apache License 2.0 |
room/compiler-xprocessing/src/main/java/androidx/room/processing/XTypeElement.kt | asfalcone | 282,249,038 | true | {"Java Properties": 20, "Shell": 46, "INI": 2, "Text": 8353, "Gradle": 419, "Markdown": 43, "Ignore List": 35, "XML": 9579, "Java": 4529, "HTML": 17, "Kotlin": 3542, "Python": 28, "JSON": 38, "Proguard": 37, "Protocol Buffer": 7, "Batchfile": 6, "AIDL": 30, "ANTLR": 1, "YAML": 4, "SVG": 1, "JavaScript": 1, "Ant Build System": 5, "CSS": 1, "JSON with Comments": 1, "desktop": 1, "Gradle Kotlin DSL": 2, "CMake": 1, "C++": 2} | /*
* 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 androidx.room.processing
import com.squareup.javapoet.ClassName
interface XTypeElement : XElement {
val qualifiedName: String
val type: XDeclaredType
val superType: XType?
val className: ClassName
fun isInterface(): Boolean
fun isKotlinObject(): Boolean
/**
* All fields, including private supers.
* Room only ever reads fields this way.
*/
fun getAllFieldsIncludingPrivateSupers(): List<XVariableElement>
// only in kotlin
fun findPrimaryConstructor(): XExecutableElement?
/**
* methods declared in this type
* includes all instance/static methods in this
*/
fun getDeclaredMethods(): List<XExecutableElement>
/**
* Methods declared in this type and its parents
* includes all instance/static methods in this
* includes all instance/static methods in parent CLASS if they are accessible from this (e.g. not
* private).
* does not include static methods in parent interfaces
*/
fun getAllMethods(): List<XExecutableElement>
/**
* Instance methods declared in this and supers
* include non private instance methods
* also includes non-private instance methods from supers
*/
fun getAllNonPrivateInstanceMethods(): List<XExecutableElement>
fun getConstructors(): List<XExecutableElement>
}
| 0 | null | 0 | 0 | c508f71545f2ea0e11a167f4db1b86c811e1885a | 1,985 | androidx-1 | Apache License 2.0 |
app/src/main/java/com/abh80/smartedge/aod_edgelighting/ScreenService.kt | atifkhandeveloper | 667,512,969 | false | {"Java": 338472, "Kotlin": 82072, "JavaScript": 3143} | package com.abh80.smartedge.aod_edgelighting
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.content.IntentFilter
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.BatteryManager
import android.os.Build
import android.os.IBinder
import androidx.core.app.NotificationCompat
import com.abh80.smartedge.R
class ScreenService : Service() {
// private lateinit var mScreenReceiver: ScreenReceiver
var mNotifyManager: NotificationManager? = null
var mBuilder: NotificationCompat.Builder? = null
var notificationChannel: NotificationChannel? = null
var NOTIFICATION_CHANNEL_ID = "1"
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onCreate() {
val IconLg = BitmapFactory.decodeResource(resources, R.drawable.ic_launcher_foreground)
mNotifyManager =
applicationContext.getSystemService(NOTIFICATION_SERVICE) as NotificationManager
mBuilder = NotificationCompat.Builder(this)
mBuilder!!.setContentTitle("Clock Service")
.setContentText("Always On Display is running .")
.setTicker("Always running...")
.setSmallIcon(R.drawable.ic_launcher_background)
.setLargeIcon(IconLg)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.setPriority(Notification.PRIORITY_HIGH)
.setVibrate(longArrayOf(1000))
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setOngoing(true)
.setOnlyAlertOnce(true)
.setAutoCancel(false)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationChannel = NotificationChannel(
NOTIFICATION_CHANNEL_ID,
"My Notifications",
NotificationManager.IMPORTANCE_HIGH
)
// Configure the notification channel.
notificationChannel!!.description = "Channel description"
notificationChannel!!.enableLights(true)
notificationChannel!!.lightColor = Color.BLUE
notificationChannel!!.vibrationPattern = longArrayOf(1000)
notificationChannel!!.enableVibration(true)
notificationChannel!!.lockscreenVisibility = Notification.VISIBILITY_PUBLIC
mNotifyManager!!.createNotificationChannel(notificationChannel!!)
mBuilder!!.setChannelId(NOTIFICATION_CHANNEL_ID)
startForeground(1, mBuilder!!.build())
} else {
mBuilder!!.setChannelId(NOTIFICATION_CHANNEL_ID)
mNotifyManager!!.notify(1, mBuilder!!.build())
}
registerScreenStatusReceiver()
}
override fun onDestroy() {
unregisterScreenStatusReceiver()
if (Build.VERSION.SDK_INT >= 26) {
stopForeground(true)
} else {
mNotifyManager!!.cancel(1)
}
}
private fun registerScreenStatusReceiver() {
// mScreenReceiver = ScreenReceiver()
val filter = IntentFilter()
filter.addAction(Intent.ACTION_SCREEN_OFF)
filter.addAction(Intent.ACTION_SCREEN_ON)
filter.addAction(BatteryManager.EXTRA_LEVEL)
// registerReceiver(mScreenReceiver, filter)
}
private fun unregisterScreenStatusReceiver() {
try {
// unregisterReceiver(mScreenReceiver)
} catch (e: IllegalArgumentException) {
e.message
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
return START_STICKY
}
} | 1 | null | 1 | 1 | 72c7444e199c20984c86e64144b926299c583717 | 3,704 | Smart-Edge-Ads | MIT License |
app/src/main/java/aosp/toolkit/perseus/WelcomeActivity.kt | 1552980358 | 154,339,117 | false | null | package aosp.toolkit.perseus
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Paint
import android.os.Bundle
import android.provider.MediaStore
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.view.LayoutInflater
import android.view.View
import android.view.View.*
import android.view.ViewGroup
import aosp.toolkit.perseus.base.BaseIndex.versionIndex
import aosp.toolkit.perseus.base.BaseManager
import aosp.toolkit.perseus.base.BaseOperation.Companion.ShortToast
import aosp.toolkit.perseus.base.ViewPagerAdapter
import aosp.toolkit.perseus.services.ImportOfflinePackageService
import kotlinx.android.synthetic.main.activity_welcome.*
import kotlinx.android.synthetic.main.fragment_importofflinepackage.*
import kotlinx.android.synthetic.main.fragment_license.*
import kotlinx.android.synthetic.main.fragment_ready.*
import kotlinx.android.synthetic.main.fragment_welcome.*
import java.lang.Exception
/*
* OsToolkit - Kotlin
*
* Date : 31/12/2018
*
* By : 1552980358
*
*/
/*
* Modify
*
* 9/1/2019
*
* Re-write
* 25 Mar 2019
*
*/
class WelcomeActivity : AppCompatActivity() {
private lateinit var t: Thread
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_welcome)
BaseManager.getInstance().welcomeActivity = this
val option =
(SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or SYSTEM_UI_FLAG_LAYOUT_STABLE)
window.decorView.systemUiVisibility = option
val tabList = listOf(
getString(R.string.welcome_tab_welcome),
getString(R.string.welcome_tab_license),
getString(R.string.welcome_tab_offline),
getString(R.string.welcome_tab_ready)
)
val fragmentList = listOf(
WelcomeFragment(), LicenseFragment(), ImportOfflinePackageFragment(), ReadyFragment()
)
viewPager.adapter = ViewPagerAdapter(supportFragmentManager, fragmentList, tabList)
tabLayout.setupWithViewPager(viewPager)
t = Thread {
val colors = listOf(
ContextCompat.getColor(this, R.color.red),
ContextCompat.getColor(this, R.color.orange),
ContextCompat.getColor(this, R.color.yellow),
ContextCompat.getColor(this, R.color.green),
ContextCompat.getColor(this, R.color.cyan),
ContextCompat.getColor(this, R.color.blue),
ContextCompat.getColor(this, R.color.purple)
)
var i = 0
while (true) {
if (i != 6) {
runOnUiThread { root.setBackgroundColor(colors[i]) }
i++
} else {
runOnUiThread { root.setBackgroundColor(colors[0]) }
i = 1
}
try {
Thread.sleep(500)
} catch (e: Exception) {
//
}
}
}
t.start()
}
private fun checkPermission0() {
if (ActivityCompat.checkSelfPermission(
this, android.Manifest.permission.READ_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED
) {
startService(
Intent(this, ImportOfflinePackageService::class.java).putExtra(
"download", true
)
)
} else {
ActivityCompat.requestPermissions(
this, arrayOf(
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
), 0
)
}
}
private fun checkPermission1() {
if (ActivityCompat.checkSelfPermission(
this, android.Manifest.permission.READ_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE
) == PackageManager.PERMISSION_GRANTED
) {
startActivityForResult(
Intent(Intent.ACTION_GET_CONTENT).setType("*/*").addCategory(Intent.CATEGORY_OPENABLE),
0
)
} else {
ActivityCompat.requestPermissions(
this, arrayOf(
android.Manifest.permission.READ_EXTERNAL_STORAGE,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
), 0
)
}
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<out String>, grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
0 -> checkPermission0()
1 -> checkPermission1()
else -> return
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
val url = data!!.data
val cursor = contentResolver.query(
url!!, arrayOf(MediaStore.Images.Media.DATA), null, null, null
)
cursor!!.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))
startService(
Intent(this, ImportOfflinePackageService::class.java).putExtra(
"download", false
).putExtra(
"zipLocation",
cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA))
)
)
cursor.close()
} else {
// 取消操作
ShortToast(this, R.string.cancelled)
}
}
override fun finish() {
try {
t.interrupt()
} catch (e: Exception) {
//
}
super.finish()
}
class WelcomeFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_welcome, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val array = resources.getStringArray(R.array.version)
version.text = array[versionIndex]
version.paint.flags = Paint.UNDERLINE_TEXT_FLAG
author.paint.flags = Paint.UNDERLINE_TEXT_FLAG
}
}
class LicenseFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_license, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
webView.loadUrl("https://raw.githubusercontent.com/1552980358/aosp.toolkit.perseus/master/LICENSE")
}
}
class ImportOfflinePackageFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_importofflinepackage, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
radioGroup.setOnCheckedChangeListener { _, checkedId ->
when (checkedId) {
R.id.rb_2 -> {
BaseManager.getInstance().welcomeActivity.checkPermission0()
}
R.id.rb_3 -> {
BaseManager.getInstance().welcomeActivity.checkPermission1()
}
R.id.rb_4 -> {
AlertDialog.Builder(context!!).setTitle(R.string.welcome_offline_5)
.setPositiveButton(R.string.ok) { _, _ -> }
.setView(R.layout.dialog_rb_4).setCancelable(false).show()
}
}
}
}
}
class ReadyFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_ready, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
root_S.setOnClickListener {
context!!.getSharedPreferences("launch", Context.MODE_PRIVATE).edit()
.putBoolean("welcome", true).apply()
startActivity(Intent(context!!, MainActivity::class.java))
}
}
}
} | 0 | Kotlin | 0 | 3 | c595c8d731e9aab8d2bb64a0185ae9a93775e4f2 | 9,552 | aosp.toolkit.perseus | Apache License 2.0 |
app/src/main/java/com/wkx/gank/ui/home/viewmodel/HomeViewModel.kt | 731701622 | 200,007,112 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "Java": 2, "XML": 49, "Kotlin": 34, "JSON": 1} | package com.wkx.gank.ui.home.viewmodel
import androidx.lifecycle.MutableLiveData
import com.google.gson.Gson
import com.wkx.common.base.BaseViewModel
import com.wkx.common.utils.ApiCodeException
import com.wkx.common.utils.Code
import com.wkx.common.utils.Status
import com.wkx.gank.api.gankService
import com.wkx.gank.entity.Gank
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import org.json.JSONArray
import org.json.JSONObject
class HomeViewModel : BaseViewModel() {
val todayLiveData by lazy { MutableLiveData<List<Gank>>().also { getToday() } }
fun refresh() = getToday()
private fun getToday() {
launch {
statusLiveData.postValue(Status(Code.ING))
val list = withContext(Dispatchers.IO) {
val responseBody = withTimeout(timeoutMillis) {
return@withTimeout gankService.getToday()
}
val result = responseBody.string()
return@withContext parsenJson(result)
}
if (list.isNotEmpty()) {
statusLiveData.postValue(Status(Code.SUCCESS))
todayLiveData.postValue(list)
} else {
statusLiveData.postValue(Status(Code.EMPTY))
}
}
}
private fun parsenJson(result: String): List<Gank> {
val jsonObject = JSONObject(result)
val error: Boolean = jsonObject.optBoolean("error", true)
if (error) {
throw ApiCodeException("服务器返回异常")
} else {
val categoryArrays: JSONArray = jsonObject.optJSONArray("category")
val resultJsonObject = jsonObject.optJSONObject("results")
val list = ArrayList<Gank>()
for (i in 0 until categoryArrays.length()) {
val category = categoryArrays[i].toString()
val resultJsonArray: JSONArray = resultJsonObject.optJSONArray(category)
for (j in 0 until resultJsonArray.length()) {
val data = Gson().fromJson<Gank>(resultJsonArray[j].toString(), Gank::class.java)
list.add(data)
}
}
return list
}
}
} | 1 | null | 1 | 1 | e190100ff17f98329f152e76a00b9a7302cf7d72 | 2,256 | myGank | Apache License 2.0 |
src/test/kotlin/com/atlassian/performance/tools/virtualusers/lib/docker/DockerNetwork.kt | atlassian | 172,478,035 | false | {"Gradle Kotlin DSL": 2, "CODEOWNERS": 1, "Markdown": 4, "INI": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 1, "Text": 1, "XML": 1, "Dockerfile": 1, "Kotlin": 80, "Java": 1, "YAML": 1} | package com.atlassian.performance.tools.virtualusers.lib.docker
import com.github.dockerjava.api.DockerClient
import com.github.dockerjava.api.command.CreateNetworkCmd
import com.github.dockerjava.api.command.CreateNetworkResponse
class DockerNetwork(
private val docker: DockerClient,
val response: CreateNetworkResponse
) : AutoCloseable {
override fun close() {
docker.removeNetworkCmd(response.id).exec()
}
}
fun CreateNetworkCmd.execAsResource(
docker: DockerClient
): DockerNetwork = DockerNetwork(docker, exec()) | 1 | null | 1 | 1 | c1e8d65595c1482bd9b51a5fb980a30d5a4b3f60 | 550 | virtual-users | Apache License 2.0 |
ajooba_app/android/app/src/main/kotlin/com/harponline/ajooba/ajooba_app/MainActivity.kt | Noorhasan9784 | 373,514,297 | false | {"Text": 7, "Ignore List": 4, "Markdown": 3, "YAML": 1, "Dart": 7, "JSON": 106, "JAR Manifest": 1, "Java": 1, "XML": 110, "Makefile": 1, "Java Properties": 2, "SQL": 1, "Checksums": 1, "Gradle": 3, "INI": 1, "Kotlin": 1, "HTML": 1, "OpenStep Property List": 4, "Objective-C": 1, "Swift": 1} | package com.harponline.ajooba.ajooba_app
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 1 | null | 1 | 1 | d2baa6e4d9f81a657286815f0a186aeb0e002597 | 137 | ajooba_app | Apache License 2.0 |
camunda-delegator/src/main/kotlin/ru/tinkoff/top/camunda/delegator/delegates/resolvers/DelegateExecutionAnn.kt | TinkoffCreditSystems | 401,398,304 | false | {"Gradle Kotlin DSL": 10, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 1, "Markdown": 3, "JSON": 5, "TOML": 1, "Kotlin": 122, "YAML": 5, "Java": 2, "XML": 2} | package ru.tinkoff.top.camunda.delegator.delegates.resolvers
@Target(AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.ANNOTATION_CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class DelegateExecutionAnn
| 0 | Kotlin | 8 | 32 | d918c6e9f08f09b822e2658d2b64772bef83a6e1 | 217 | camunda-delegator-lib | Apache License 2.0 |
mobile/src/main/java/com/cm/media/entity/Entity.kt | zhangwenxue | 157,227,854 | false | {"Java": 1368464, "Kotlin": 17634} | package com.cm.media.entity
data class Entity<T>(val code: Int, var message: String, val data: T) | 0 | Java | 1 | 2 | bf6facc4047e52af024d75e06cea4fd432d1dc4d | 98 | CMMedia | Apache License 2.0 |
xmlserializable/src/javaSharedMain/kotlin/nl/adaptivity/xml/_XmlReader.kt | pdvrieze | 143,553,364 | false | null | /*
* Copyright (c) 2023.
*
* This file is part of xmlutil.
*
* This file is licenced to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You should have received a copy of the license with the source distribution.
* Alternatively, 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.
*/
@file:JvmMultifileClass
@file:JvmName("XmlReaderUtil")
package nl.adaptivity.xml
import nl.adaptivity.xmlutil.XmlReader
import nl.adaptivity.xmlutil.xmlserializable.deSerialize as newDeSerialize
/**
* Inline function to deserialize a type based upon `@[XmlDeserializer]` annotation.
*/
@Deprecated("Moved to nl.adaptivity.xmlutil", ReplaceWith("deserialize()", "nl.adaptivity.xmlutil.deSerialize"))
public inline fun <reified T : Any> XmlReader.deSerialize(): T {
return newDeSerialize()
}
/**
* Deserialize a type with `@[XmlDeserializer]` annotation.
*/
@Deprecated("Moved to nl.adaptivity.xmlutil", ReplaceWith(
"deSerialize(type)",
"nl.adaptivity.xmlutil.deSerialize"
)
)
public fun <T> XmlReader.deSerialize(type: Class<T>): T {
return newDeSerialize(type)
}
| 35 | null | 31 | 378 | c4053519a8b6c90af9e1683a5fe0e9e2b2c0db79 | 1,598 | xmlutil | Apache License 2.0 |
Module2/src/main/java/com/xiaojinzi/component2/view/Test1Fragment.kt | zack098711 | 258,397,327 | true | {"Java": 752183, "Kotlin": 3729, "HTML": 1781} | package com.xiaojinzi.component2.view
import android.support.v4.app.Fragment
import com.xiaojinzi.component.anno.FragmentAnno
@FragmentAnno(value = ["component2.test1Fragment"])
class Test1Fragment : Fragment()
| 0 | null | 0 | 1 | ae31d4014b0b4b8eb5fa5b250297c00d203f4dce | 215 | Component | Apache License 2.0 |
idea/testData/editor/optimizeImports/common/IteratorFunction.kt | damenez | 176,209,431 | true | {"Markdown": 56, "Gradle": 497, "Gradle Kotlin DSL": 215, "Java Properties": 12, "Shell": 11, "Ignore List": 10, "Batchfile": 9, "Git Attributes": 1, "Protocol Buffer": 12, "Java": 5238, "Kotlin": 43905, "Proguard": 7, "XML": 1594, "Text": 9172, "JavaScript": 239, "JAR Manifest": 2, "Roff": 209, "Roff Manpage": 34, "INI": 95, "AsciiDoc": 1, "SVG": 30, "HTML": 462, "Groovy": 31, "JSON": 17, "JFlex": 3, "Maven POM": 94, "CSS": 1, "Ant Build System": 50, "C": 1, "ANTLR": 1, "Scala": 1} | import test1.MyClass
import test1.iterator
fun foo() {
val s = MyClass()
for (i in s) {}
}
| 0 | Kotlin | 0 | 2 | 9a2178d96bd736c67ba914b0f595e42d1bba374d | 100 | kotlin | Apache License 2.0 |
model_android/src/main/java/com/wynne/android/AllowTaskReparentingActivity.kt | tony-xxw | 122,974,025 | false | null | package com.wynne.android
import com.wynne.knowledge.base.base.BaseActivity
class AllowTaskReparentingActivity : BaseActivity() {
override fun initView() {
}
override val layoutId: Int = R.layout.actiivty_allow_task
} | 1 | null | 1 | 7 | 4c8595c84086a11f1abba8538c2de8c86f17212d | 234 | KnowledgeTree | Apache License 2.0 |
app/src/main/java/com/main/maybe/miplayer/model/FolderBean.kt | luciferldy | 37,312,180 | false | null | package com.main.maybe.miplayer.model
data class FolderBean(var id: String = "") | 3 | Java | 10 | 15 | 3e109274305815a009ebb8b2974fcd042ca4e609 | 81 | miplayer | Apache License 2.0 |
android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/storereview/StoreReviewPackage.kt | derekstavis | 184,342,737 | true | {"Objective-C": 20602533, "Java": 13690880, "C++": 11626391, "Kotlin": 5359352, "TypeScript": 4619500, "Objective-C++": 4368983, "Swift": 1078083, "JavaScript": 1013246, "Starlark": 712574, "Ruby": 519774, "C": 282818, "Makefile": 193716, "Shell": 54009, "Assembly": 46734, "HTML": 36667, "CMake": 26275, "CSS": 1306, "Batchfile": 89} | package abi42_0_0.expo.modules.storereview
import android.content.Context
import abi42_0_0.org.unimodules.core.BasePackage
class StoreReviewPackage : BasePackage() {
override fun createExportedModules(context: Context) = listOf(StoreReviewModule(context))
}
| 1 | Objective-C | 1 | 2 | e377f0cd22db5cd7feb8e80348cd7064db5429b1 | 262 | expo | MIT License |
android/src/main/java/com/idenfyreactnative/IdenfyReactNativeModule.kt | idenfy | 311,149,721 | false | null | package com.idenfyreactnative
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReadableMap
import com.idenfyreactnative.di.DIProvider
import com.idenfyreactnative.domain.IdenfyReactNativeCallbacksUseCase
import com.idenfyreactnative.domain.IdenfySdkActivityEventListener
import com.idenfyreactnative.domain.utils.GetSdkDataFromConfig
import com.idenfy.idenfySdk.CoreSdkInitialization.IdenfyController
import com.idenfy.idenfySdk.api.initialization.IdenfySettingsV2.IdenfyBuilderV2
import com.idenfy.idenfySdk.faceauthentication.api.FaceAuthenticationInitialization
import com.idenfy.idenfySdk.faceauthentication.domain.models.FaceAuthenticationType
class IdenfyReactNativeModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
private val diProvider = DIProvider()
private val idenfyReactNativeCallbacksUseCase: IdenfyReactNativeCallbacksUseCase
private val idenfySdkActivityEventListener: IdenfySdkActivityEventListener
init {
idenfyReactNativeCallbacksUseCase = diProvider.idenfyReactNativeCallbacksUseCase
idenfySdkActivityEventListener = diProvider.idenfySdkActivityEventListener
reactContext.addActivityEventListener(idenfySdkActivityEventListener)
}
override fun getName(): String {
return "IdenfyReactNative"
}
// Example method
// See https://reactnative.dev/docs/native-modules-android
@ReactMethod
fun multiply(a: Int, b: Int, promise: Promise) {
promise.resolve(a * b)
}
@ReactMethod
fun start(config: ReadableMap, promise: Promise) {
idenfyReactNativeCallbacksUseCase.setCallbacksReceiver(promise)
val currentActivity = currentActivity
if (currentActivity == null) {
idenfyReactNativeCallbacksUseCase.getCallbackReceiver()?.reject("error", Exception("Android activity does not exist"))
idenfyReactNativeCallbacksUseCase.resetPromise()
return
}
try {
val authToken = GetSdkDataFromConfig.getSdkTokenFromConfig(config)
val idenfySettingsV2 = IdenfyBuilderV2()
.withAuthToken(authToken)
.build()
IdenfyController.getInstance().initializeIdenfySDKV2WithManual(currentActivity,
IdenfyController.IDENFY_REQUEST_CODE,
idenfySettingsV2)
}
//Unexpected exceptions
catch (e: Throwable) {
e.printStackTrace()
idenfyReactNativeCallbacksUseCase.getCallbackReceiver()?.reject("error", Exception("Unexpected error. Verify that config is structured correctly."))
idenfyReactNativeCallbacksUseCase.resetPromise()
return
}
}
@ReactMethod
fun startFaceReAuth(config: ReadableMap, promise: Promise) {
idenfyReactNativeCallbacksUseCase.setCallbacksReceiver(promise)
val currentActivity = currentActivity
if (currentActivity == null) {
idenfyReactNativeCallbacksUseCase.getCallbackReceiver()?.reject("error", Exception("Android activity does not exist"))
idenfyReactNativeCallbacksUseCase.resetPromise()
return
}
try {
val authToken = GetSdkDataFromConfig.getSdkTokenFromConfig(config)
val faceReauthenticationInitialization = FaceAuthenticationInitialization(authToken, false)
IdenfyController.getInstance().initializeFaceAuthenticationSDKV2(currentActivity, IdenfyController.IDENFY_REQUEST_CODE, faceReauthenticationInitialization)
}
//Unexpected exceptions
catch (e: Throwable) {
e.printStackTrace()
idenfyReactNativeCallbacksUseCase.getCallbackReceiver()?.reject("error", Exception("Unexpected error. Verify that config is structured correctly."))
idenfyReactNativeCallbacksUseCase.resetPromise()
return
}
}
}
| 1 | Java | 3 | 5 | 97ed0eac83f906f53dd8aa11ed7721e101221232 | 4,830 | ReactNativeSDK | MIT License |
app/src/main/java/com/binarybricks/coiny/components/AboutCoinModule.kt | miladhamzelo | 122,965,084 | false | null | package com.binarybricks.coiny.components
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.binarybricks.coiny.R
import kotlinx.android.synthetic.main.coin_about_module.view.*
/**
* Created by <NAME>
*
* Simple class that wraps all logic related to showing about us section
*/
class AboutCoinModule {
fun init(layoutInflater: LayoutInflater, parent: ViewGroup?): View {
return layoutInflater.inflate(R.layout.coin_about_module, parent, false)
}
fun showAboutCoinText(inflatedView: View, coinText: String) {
inflatedView.tvAboutCoin.text = coinText
}
data class AboutCoinModuleData(val aboutcoin: String)
} | 1 | Kotlin | 11 | 0 | d5010965f14ebd365df3ab98a574cc2526f9e5ca | 702 | Coiny | Apache License 2.0 |
app/src/main/java/com/binarybricks/coiny/components/AboutCoinModule.kt | miladhamzelo | 122,965,084 | false | null | package com.binarybricks.coiny.components
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.binarybricks.coiny.R
import kotlinx.android.synthetic.main.coin_about_module.view.*
/**
* Created by <NAME>
*
* Simple class that wraps all logic related to showing about us section
*/
class AboutCoinModule {
fun init(layoutInflater: LayoutInflater, parent: ViewGroup?): View {
return layoutInflater.inflate(R.layout.coin_about_module, parent, false)
}
fun showAboutCoinText(inflatedView: View, coinText: String) {
inflatedView.tvAboutCoin.text = coinText
}
data class AboutCoinModuleData(val aboutcoin: String)
} | 1 | Kotlin | 11 | 0 | d5010965f14ebd365df3ab98a574cc2526f9e5ca | 702 | Coiny | Apache License 2.0 |
Modules/RoomDbCode/compose-application/app/src/main/java/com/istudio/code/domain/di/applevel/CoreModule.kt | devrath | 375,211,931 | false | {"Kotlin": 166821} | package com.istudio.code.domain.di.applevel
import android.content.Context
import androidx.room.Room
import com.google.gson.Gson
import com.istudio.code.domain.database.AppDatabase
import com.istudio.code.domain.database.AppDatabase.Companion.DATABASE_NAME
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object CoreModule {
@Singleton
@Provides
fun provideGson(): Gson {
return Gson()
}
@Provides
@Singleton
fun provideAppDatabase(@ApplicationContext appContext: Context): AppDatabase {
return Room.databaseBuilder(
appContext, AppDatabase::class.java, DATABASE_NAME
).allowMainThreadQueries().build()
}
} | 0 | Kotlin | 0 | 3 | 1324fe4d351f1fb1ba990f699a4baf64bfea57c7 | 886 | DroidDbStorage | Apache License 2.0 |
app/src/main/java/com/hazz/aipick/ui/activity/CategryDescActivity.kt | backin | 286,701,113 | true | {"Java Properties": 2, "YAML": 3, "Gradle": 6, "Shell": 1, "Batchfile": 1, "Text": 1, "Ignore List": 4, "XML": 213, "Proguard": 2, "Java": 144, "Kotlin": 155, "JSON": 1} | package com.hazz.aipick.ui.activity
import android.annotation.SuppressLint
import android.graphics.Color
import android.support.v7.widget.Toolbar
import com.hazz.aipick.R
import com.hazz.aipick.base.BaseActivity
import com.hazz.aipick.utils.ToolBarCustom
import kotlinx.android.synthetic.main.activity_categry_desc.*
class CategryDescActivity : BaseActivity() {
override fun initData() {
}
override fun layoutId(): Int = R.layout.activity_categry_desc
@SuppressLint("SetTextI18n")
override fun initView() {
ToolBarCustom.newBuilder(mToolbar as Toolbar)
.setLeftIcon(R.mipmap.back_white)
.setTitle(getString(R.string.categry_desc))
.setTitleColor(resources.getColor(R.color.color_white))
.setToolBarBg(Color.parseColor("#1E2742"))
.setOnLeftIconClickListener { view -> finish() }
}
override fun start() {
}
}
| 0 | null | 0 | 0 | 14dc6cd6d28f186d68f423e3985f2258f8ecc90c | 939 | Aipick | Apache License 2.0 |
korge-core/src/korlibs/image/style/CSS.kt | korlibs | 80,095,683 | false | {"WebAssembly": 14293935, "Kotlin": 9728800, "C": 77092, "C++": 20878, "TypeScript": 12397, "HTML": 6043, "Python": 4296, "Swift": 1371, "JavaScript": 328, "Shell": 254, "CMake": 202, "CSS": 66, "Batchfile": 41} | @file:OptIn(KorimExperimental::class)
package korlibs.image.style
import korlibs.datastructure.*
import korlibs.image.annotation.*
import korlibs.image.color.*
import korlibs.io.lang.*
import korlibs.io.util.*
import korlibs.math.geom.*
import korlibs.math.interpolation.*
import korlibs.time.*
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.collections.set
import kotlin.native.concurrent.*
@KorimExperimental
class CSS(val allRules: List<IRuleSet>, unit: Unit = Unit) {
constructor(cssList: List<CSS>) : this(cssList.flatMap { it.allRules })
val animationsById = allRules.filterIsInstance<KeyFrames>().associateBy { it.id.str }
val rules = allRules.filterIsInstance<RuleSet>()
val rulesForIds = rules.filter { it.selector is IdSelector }.associateBy { (it.selector as IdSelector).id }
val rulesForClassNames = rules.filter { it.selector is ClassSelector }.associateBy { (it.selector as ClassSelector).className }
override fun toString(): String = "CSS(rules = ${rules.size}, animations = ${animationsById.size})"
interface Selector {
val str: String
}
data class IdSelector(val token: Token) : Selector {
override val str: String get() = token.str
val id: String = str.substr(1)
}
data class ClassSelector(val token: Token) : Selector {
override val str: String get() = token.str
val className: String = str.substr(1)
}
data class UnknownSelector(val token: Token) : Selector {
override val str: String get() = token.str
}
data class Expression(val expr: List<Token>) : Extra by Extra.Mixin() {
val exprStr = this.expr.joinToString(" ") { it.str }
}
data class Declaration(val property: String, val expr: Expression?) {
}
interface IRuleSet
data class Declarations(val declarations: List<Declaration>) : Extra by Extra.Mixin() {
val declarationsMap = declarations.associate { it.property.lowercase() to it.expr }
operator fun get(prop: String): Expression? = declarationsMap[prop]
}
data class RuleSet(val selector: Selector, val declarations: Declarations) : IRuleSet {
}
data class KeyFrame constructor(val ratio: Ratio, val declarations: Declarations) {
operator fun get(key: String): Expression? = declarations.declarationsMap[key]
val easing: Easing = this["animation-timing-function"]?.easing ?: Easing.LINEAR
companion object {
val DUMMY = KeyFrame(Ratio.ZERO, Declarations(emptyList()))
}
}
data class InterpolationResult(var ratio: Double = 0.0, var k0: KeyFrame = KeyFrame.DUMMY, var k1: KeyFrame = KeyFrame.DUMMY) {
val properties get() = k0.declarations.declarations.map { it.property }
}
data class Animation(val name: String, val duration: TimeSpan, val delay: TimeSpan = 0.seconds, val iterationCount: NumberOfTimes = NumberOfTimes.INFINITE, val direction: Boolean = true, val easing: Easing = Easing.LINEAR)
data class KeyFrames(val id: Token, val partialKeyFrames: List<KeyFrame>) : IRuleSet {
val propertyNames = partialKeyFrames.flatMap { it.declarations.declarations.map { it.property } }.distinct()
val fullKeyFrames = FastArrayList<KeyFrame>()
init {
@Suppress("USELESS_CAST") val currentMap = propertyNames.associateWith { null as Expression? }.toMutableMap()
for (frame in partialKeyFrames) {
for ((key, value) in frame.declarations.declarationsMap) {
currentMap[key] = value
}
fullKeyFrames.add(KeyFrame(frame.ratio, Declarations(currentMap.map { Declaration(it.key, it.value) })))
}
}
fun getAt(ratio: Float, out: InterpolationResult = InterpolationResult()): InterpolationResult = getAt(ratio.toRatio(), out)
fun getAt(ratio: Double, out: InterpolationResult = InterpolationResult()): InterpolationResult = getAt(ratio.toRatio(), out)
// @TODO: Optimize: bisect
fun getAt(ratio: Ratio, out: InterpolationResult = InterpolationResult()): InterpolationResult {
val firstFrameIndex = fullKeyFrames.indexOfFirst { it.ratio >= ratio }
if (firstFrameIndex >= 0) {
val firstFrame = fullKeyFrames[firstFrameIndex]
out.k0 = when (firstFrame.ratio) {
ratio -> firstFrame
else -> fullKeyFrames.getOrNull(firstFrameIndex - 1) ?: firstFrame
}
out.k1 = firstFrame
out.ratio = when {
out.k0.ratio == out.k1.ratio -> 0.0
else -> {
val easing = out.k0.easing
//val easing = Easing.LINEAR
easing(ratio.convertRange(out.k0.ratio, out.k1.ratio, Ratio.ZERO, Ratio.ONE).toDouble())
}
}
} else {
out.k0 = KeyFrame.DUMMY
out.k1 = KeyFrame.DUMMY
out.ratio = 0.0
}
return out
}
companion object {
fun selectorToRatio(selector: Selector): Ratio {
val str = selector.str
if (str == "from") return Ratio.ZERO
if (str == "to") return Ratio.ONE
if (!str.endsWith("%")) error("Invalid keyframe selector $selector")
return CSS.parseRatio(str)
}
fun ruleSetToKeyFrame(rules: List<IRuleSet>): List<KeyFrame> {
return rules.filterIsInstance<RuleSet>().map { KeyFrame(selectorToRatio(it.selector), it.declarations) }
}
}
}
companion object {
fun parseCSS(str: String): CSS {
return CSSReader(tokenize(str.reader()).reader()).parseCSS()
}
data class Token(val str: String)
fun tokenize(str: String): List<Token> = tokenize(str.reader())
fun tokenize(ss: StrReader): List<Token> {
val out = arrayListOf<Token>()
val buffer = StringBuilder()
fun flush() {
if (buffer.isEmpty()) return
out.add(Token(buffer.toString()))
buffer.clear()
}
while (ss.hasMore) {
val c = ss.read()
when (c) {
' ', '\t', '\n', '\r' -> {
flush()
}
'/' -> {
// Comment
if (ss.peekChar() == '*') {
flush()
ss.skip()
ss.readUntil { ss.matchLit("*/") != null }
//ss.skip(2)
} else {
flush()
out.add(Token("$c"))
}
}
',', ':', ';', '(', '[', ')', ']', '{', '}' -> {
flush()
out.add(Token("$c"))
}
'-' -> {
if (buffer.isNotEmpty() && buffer.toString().toDoubleOrNull() != null) {
flush()
buffer.append(c)
} else {
buffer.append(c)
}
}
else -> {
buffer.append(c)
}
}
}
flush()
return out
}
fun parseAnimation(str: List<Token>) {
}
fun parseNumberDropSuffix(str: String): Double? {
return str.trimEnd { it != '.' && it !in '0'..'9' }.toDoubleOrNull()
}
fun parseTime(str: String): TimeSpan? {
if (str.endsWith("ms")) return str.removeSuffix("ms").toDoubleOrNull()?.milliseconds
if (str.endsWith("s")) return str.removeSuffix("s").toDoubleOrNull()?.seconds
return parseNumberDropSuffix(str)?.milliseconds
}
fun parseAngle(str: String): Angle? {
if (str.endsWith("deg")) return str.removeSuffix("deg").toDoubleOrNull()?.degrees
if (str.endsWith("rad")) return str.removeSuffix("rad").toDoubleOrNull()?.radians
return parseNumberDropSuffix(str)?.degrees
}
fun parseUnit(str: String): Double? {
// @TODO: We should propagate metrics to compute units like %, pt, em, vw, vh...
if (str.endsWith("%")) return str.removeSuffix("%").toDoubleOrNull()?.div(100.0)
if (str.endsWith("px")) return str.removeSuffix("px").toDoubleOrNull()
if (str.endsWith("pt")) return str.removeSuffix("pt").toDoubleOrNull()
return parseNumberDropSuffix(str)?.toDouble()
//return str.toDoubleOrNull()
}
fun readParenthesisValuesIgnoringCommas(tr: ListReader<String>): List<String> {
val args = arrayListOf<String>()
tr.expect("(")
while (true) {
if (tr.peek() == ")") {
tr.read()
break
}
if (tr.peek() == ",") {
tr.read()
continue
}
args += tr.read()
}
return args
}
fun parseTransform(str: String): Matrix {
val tokens = tokenize(str).map { it.str.lowercase() }
val tr = ListReader(tokens)
var out = Matrix()
//println("Not implemented: parseTransform: $str: $tokens")
while (tr.hasMore) {
val id = tr.read().lowercase()
val args = arrayListOf<String>()
if (tr.peek() == "(") {
args += readParenthesisValuesIgnoringCommas(tr)
}
val doubleArgs = args.map { parseUnit(it) ?: 0.0 }
fun double(index: Int) = doubleArgs.getOrElse(index) { 0.0 }
when (id) {
"translate3d" -> {
println("Warning. CSS. translate3d not implemented")
//out.pretranslate(double(0), double(1), double(2))
out = out.pretranslated(double(0), double(1))
}
"translatey" -> out = out.pretranslated(0.0, double(0))
"translatex" -> out = out.pretranslated(double(0), 0.0)
"translatez" -> {
println("Warning. CSS. translatez not implemented")
out = out.pretranslated(0.0, 0.0)
}
"translate" -> out = out.pretranslated(double(0), double(1))
"scale" -> out = out.prescaled(double(0), if (doubleArgs.size >= 2) double(1) else double(0))
"matrix" -> out = out.premultiplied(Matrix(double(0), double(1), double(2), double(3), double(4), double(5)))
"rotate" -> {
if (doubleArgs.size >= 3) out = out.pretranslated(double(1), double(2))
val angle = parseAngle(args[0]) ?: 0.degrees
//println("angle=$angle, double=${double(0)}")
out = out.prerotated(angle)
if (doubleArgs.size >= 3) out = out.pretranslated(-double(1), -double(2))
}
else -> invalidOp("Unsupported transform $id : $args : $doubleArgs ($str)")
}
//println("ID: $id, args=$args")
}
return out
}
fun parseRatio(str: String, default: Ratio = Ratio.ZERO): Ratio {
if (str.endsWith("%")) return Ratio((parseNumberDropSuffix(str) ?: 0.0) / 100.0)
return when (str.lowercase()) {
"from" -> Ratio.ZERO
"to" -> Ratio.ONE
else -> Ratio(parseNumberDropSuffix(str) ?: default.toDouble())
}
}
fun parseColor(str: String): RGBA {
return Colors[str, Colors.FUCHSIA]
}
fun parseEasing(str: String): Easing {
fun parseEasing(tr: ListReader<String>): Easing {
return when (tr.read()) {
"ease" -> Easing.cubic(0.25, 0.1, 0.25, 1.0)
"linear" -> Easing.cubic(0.0, 0.0, 1.0, 1.0)
"ease-in" -> Easing.cubic(0.42, 0.0, 1.0, 1.0)
"ease-out" -> Easing.cubic(0.0, 0.0, 0.58, 1.0)
"ease-in-out" -> Easing.cubic(0.42, 0.0, 0.58, 1.0)
"cubic-bezier" -> {
val doubleArgs = readParenthesisValuesIgnoringCommas(tr).map { parseUnit(it) ?: 0.0 }
Easing.cubic(doubleArgs[0], doubleArgs[1], doubleArgs[2], doubleArgs[3])
}
"jump-start", "start" -> Easing.EASE_CLAMP_START
"jump-end", "end" -> Easing.EASE_CLAMP_END
"step-start" -> Easing { 1f } //Easing.steps(1, Easing.EASE_CLAMP_START)
"step-end" -> Easing { 0f } //Easing.steps(1, Easing.EASE_CLAMP_END)
else -> TODO("${tr.peek(-1)}")
}
}
return parseEasing(tokenize(str).map { it.str.lowercase() }.reader())
}
fun parseSizeAsDouble(size: String): Double {
return size.filter { it !in 'a'..'z' && it !in 'A'..'Z' }.toDoubleOrNull() ?: 16.0
}
fun parseAnimation(str: String): CSS.Animation {
val tokens = tokenize(str).reader()
val id = tokens.read().str
val duration = parseTime(tokens.read().str) ?: 1.seconds
return Animation(id, duration)
}
}
}
class CSSReader(val tokens: ListReader<CSS.Companion.Token>) {
fun parseCSS(): CSS {
return CSS(parseRulesets())
}
fun parseRulesets(): List<CSS.IRuleSet> {
val out = arrayListOf<CSS.IRuleSet>()
while (tokens.hasMore) {
out += parseRuleset()
}
return out
}
fun selectorFromToken(token: CSS.Companion.Token): CSS.Selector {
if (token.str.startsWith("#")) return CSS.IdSelector(token)
if (token.str.startsWith(".")) return CSS.ClassSelector(token)
return CSS.UnknownSelector(token)
}
fun parseRuleset(): List<CSS.IRuleSet> {
val token = tokens.peek()
when {
token.str.startsWith("@") -> {
tokens.read()
// at rule
when (token.str) {
"@keyframes", "@-webkit-keyframes" -> {
val keyframesName = tokens.read()
val sets = arrayListOf<CSS.KeyFrame>()
tokens.expect(CSS.Companion.Token("{"))
while (tokens.peek() != CSS.Companion.Token("}")) {
val frame = CSS.KeyFrames.ruleSetToKeyFrame(parseRuleset())
if (frame != null) sets += frame
}
tokens.expect(CSS.Companion.Token("}"))
return listOf(CSS.KeyFrames(keyframesName, sets.sortedBy { it.ratio }))
}
else -> {
TODO("Unknown at rule: '${token}'")
}
}
}
// Plain selector
else -> {
val selectors = arrayListOf<CSS.Selector>()
while (tokens.hasMore) {
val token = tokens.read()
selectors += selectorFromToken(token)
if (tokens.peek().str == ",") {
tokens.skip()
continue
}
if (tokens.peek().str == "{") {
break
}
}
val decls = arrayListOf<CSS.Declaration>()
tokens.expect(CSS.Companion.Token("{"))
while (tokens.peek() != CSS.Companion.Token("}")) {
decls += parseDeclaration()
}
tokens.expect(CSS.Companion.Token("}"))
val declsd = CSS.Declarations(decls)
return selectors.map { CSS.RuleSet(it, declsd) }
}
}
}
fun parseDeclaration(): CSS.Declaration {
val property = tokens.read().str.removePrefix("-webkit-")
tokens.expect(CSS.Companion.Token(":"))
val expression = parseExpression()
return CSS.Declaration(property, expression)
}
fun parseExpression(): CSS.Expression {
val out = arrayListOf<CSS.Companion.Token>()
while (true) {
val token = tokens.read()
if (token.str == ";") {
break
}
if (token.str == "}") {
tokens.skip(-1)
break
}
out.add(token)
}
return CSS.Expression(out)
}
}
val CSS.Expression.color: RGBA by extraPropertyThis { CSS.parseColor(exprStr) }
val CSS.Expression.ratio: Ratio by extraPropertyThis { CSS.parseRatio(exprStr) }
val CSS.Expression.matrix: Matrix by extraPropertyThis { CSS.parseTransform(exprStr) }
val CSS.Expression.transform: MatrixTransform by extraPropertyThis { matrix.immutable.decompose() }
val CSS.Expression.easing: Easing by extraPropertyThis { CSS.parseEasing(exprStr) }
val CSS.Declarations.animation: CSS.Animation? by extraPropertyThis {
this["animation"]?.let { CSS.parseAnimation(it.exprStr) }
}
fun CSS.InterpolationResult.getColor(key: String, default: RGBA = Colors.TRANSPARENT): RGBA =
this.ratio.toRatio().interpolate(k0[key]?.color ?: default, k1[key]?.color ?: default)
fun CSS.InterpolationResult.getRatio(key: String, default: Ratio = Ratio.ZERO): Ratio =
this.ratio.toRatio().interpolate(k0[key]?.ratio ?: default, k1[key]?.ratio ?: default)
fun CSS.InterpolationResult.getMatrix(key: String, default: Matrix = Matrix()): Matrix =
this.ratio.toRatio().interpolate(k0[key]?.matrix?.takeIf { it.isNotNIL } ?: default, k1[key]?.matrix ?: default)
fun CSS.InterpolationResult.getTransform(key: String, default: MatrixTransform = MatrixTransform.IDENTITY): MatrixTransform =
this.ratio.toRatio().interpolate(k0[key]?.transform ?: default, k1[key]?.transform ?: default)
fun CSS.InterpolationResult.getEasing(key: String, default: Easing = Easing.LINEAR): Easing =
k0[key]?.easing ?: default
| 444 | WebAssembly | 121 | 2,207 | dc3d2080c6b956d4c06f4bfa90a6c831dbaa983a | 18,707 | korge | Apache License 2.0 |
plugin/src/test/java/unit/perl/parser/PerlHighlightingLexerTest.kt | Camelcade | 33,823,684 | false | {"Java": 7166983, "Lex": 91627, "HTML": 42894, "Kotlin": 35143, "Perl": 10649, "Shell": 3180, "Dockerfile": 1882} | /*
* Copyright 2015-2024 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 unit.perl.parser
import base.PerlLightTestCase
import com.perl5.lang.perl.lexer.PerlLexer
import com.perl5.lang.perl.lexer.PerlLexingContext
import com.perl5.lang.perl.lexer.adapters.PerlMergingLexerAdapter
import org.jetbrains.annotations.NonNls
import org.junit.Test
import java.lang.reflect.Modifier
class PerlHighlightingLexerTest : PerlLightTestCase() {
val lexerStates = PerlLexer::class.java.declaredFields
.filter { Modifier.isStatic(it.modifiers) && it.type == Int::class.java && it.canAccess(null) }
.associate { it.getInt(null) to it.name }
override fun getBaseDataPath(): @NonNls String? = "unit/perl/lexer"
@Test
fun testHeredocInRegexp() {
doTestLexer();
}
@Test
fun testHeredocInRegexpSublexed() {
doTestLexer("heredocInRegexp", true);
}
private fun doTestLexer(sourceName: String? = null, forceSubLexing: Boolean = false) {
val testFileText = loadFileContent("${sourceName ?: getTestName(true)}${realDataFileExtension}")
val lexer = PerlMergingLexerAdapter(PerlLexingContext.create(project).withEnforcedSublexing(forceSubLexing));
lexer.start(testFileText)
val sb = StringBuilder()
while (lexer.tokenType != null) {
sb.append("[").append(lexer.tokenType).append("] ").append(lexer.tokenStart).append("-").append(lexer.tokenEnd).append(" ")
.append(lexerStates[lexer.state] ?: lexer.state).append("\n")
if (lexer.tokenStart <= lexer.tokenEnd) {
sb.append(protectSpaces(testFileText.substring(lexer.tokenStart, lexer.tokenEnd))).append("\n")
} else {
sb.append("************** BAD TOKEN RANGE *************").append("\n")
}
lexer.advance()
}
assertSameLinesWithFile(getTestResultsFilePath(), sb.toString())
}
} | 955 | Java | 76 | 408 | 8263348890eefa7acba3b2be6ebd9e81ddc1658e | 2,348 | Perl5-IDEA | Apache License 2.0 |
src/main/kotlin/derivean/upgrade/u2020_11_16/storage/entities/KingdomAttributeEntity.kt | marek-hanzal | 259,577,282 | false | null | package derivean.upgrade.u2020_11_16.storage.entities
import derivean.upgrade.u2020_11_16.storage.tables.KingdomAttributeTable
import leight.storage.EntityUUID
import org.jetbrains.exposed.dao.UUIDEntity
import org.jetbrains.exposed.dao.UUIDEntityClass
class KingdomAttributeEntity(id: EntityUUID) : UUIDEntity(id) {
companion object : UUIDEntityClass<KingdomAttributeEntity>(KingdomAttributeTable)
var kingdom by KingdomEntity referencedOn KingdomAttributeTable.kingdom
var attribute by AttributeEntity referencedOn KingdomAttributeTable.attribute
}
| 112 | Kotlin | 0 | 1 | 7a485228438c5fb9a61b1862e8164f5e87361e4a | 557 | DeRivean | Apache License 2.0 |
jsonparser/src/main/java/tomatobean/jsonparser/ParserUtils.kt | gtomato | 113,842,358 | false | null | package tomatobean.jsonparser
import kotlin.reflect.KClass
import kotlin.reflect.KProperty1
import kotlin.reflect.full.isSubclassOf
import kotlin.reflect.jvm.javaField
@Target (AnnotationTarget.FIELD)
@Retention (AnnotationRetention.RUNTIME)
annotation class JsonFormat(val JsonName: String = "",
val Serializable: Boolean = true,
val Deserializable: Boolean = true)
/**
* Extension function to serialize Kotlin object to json String with default config
*/
fun Any.toJson(): String {
return JsonFormatter().toJson(this)
}
/**
* Extension function to deserialize json String to Kotlin object with default config
*
* @param [kClass] The Kotlin class of target Kotlin type [T]
*
* @return [T] The instance of target Kotlin class output
*/
inline fun <reified T: Any> String.parseJson(kClass: KClass<T>): T? {
return JsonFormatter().parseJson(this, kClass)
}
/**
* Extension function to deserialize json String to Collection or Map of Kotlin object with default config
*
* @param [typeToken] The [TypeToken] instance with [Collection] [C] which have target Kotlin type [T] as member
*
* @return [T] The output instance of collection or map with target Kotlin class[T]
*/
fun <T: Any> String.parseJson(typeToken: TypeToken<T>): T? {
return JsonFormatter().parseJson(this, typeToken)
}
/**
* Internal function to get JsonName annotation @see[JsonFormat]
*/
internal fun KProperty1<*, *>.getJsonName(): String? {
val schema = (this.javaField?.annotations?.find { it is JsonFormat } as? JsonFormat)
if (schema != null && schema.JsonName.isNotEmpty()) {
return schema.JsonName
} else {
return null
}
}
/**
* Internal function to get Deserializable annotation @see[JsonFormat]
*/
internal fun KProperty1<*, *>.isDeserializable(): Boolean {
val schema = (this.javaField?.annotations?.find { it is JsonFormat } as? JsonFormat)
if (schema != null) {
return schema.Deserializable
} else {
return true
}
}
/**
* Internal function to get Serializable annotation @see[JsonFormat]
*/
internal fun KProperty1<*, *>.isSerializable(): Boolean {
val schema = (this.javaField?.annotations?.find { it is JsonFormat } as? JsonFormat)
if (schema != null) {
return schema.Serializable
} else {
return true
}
}
| 0 | Kotlin | 0 | 5 | c6fe3eb34b22512c3144f46a7b31ccb7b5399ce9 | 2,376 | Kotlin-JsonParser | MIT License |
examples/redisson/src/test/kotlin/io/bluetape4k/examples/redisson/coroutines/collections/SortedSetExamples.kt | debop | 625,161,599 | false | {"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82} | package io.bluetape4k.examples.redisson.coroutines.collections
import io.bluetape4k.examples.redisson.coroutines.AbstractRedissonCoroutineTest
import io.bluetape4k.junit5.coroutines.runSuspendWithIO
import io.bluetape4k.logging.KLogging
import io.bluetape4k.redis.redisson.coroutines.coAwait
import org.amshove.kluent.shouldBeEqualTo
import org.amshove.kluent.shouldBeTrue
import org.junit.jupiter.api.Test
import org.redisson.api.RSortedSet
/**
* Sorted set examples
*
* 참고: [SortedSet](https://github.com/redisson/redisson/wiki/7.-distributed-collections/#74-sortedset)
*/
class SortedSetExamples: AbstractRedissonCoroutineTest() {
companion object: KLogging()
private fun getSortedSet(): RSortedSet<Int> =
redisson.getSortedSet<Int>(randomName()).apply {
add(1)
add(2)
add(3)
}
@Test
fun `RSortedSet example`() = runSuspendWithIO {
val sset = getSortedSet()
sset.first() shouldBeEqualTo 1
sset.last() shouldBeEqualTo 3
sset.remove(1).shouldBeTrue()
sset.deleteAsync().coAwait()
}
}
| 0 | Kotlin | 0 | 1 | ce3da5b6bddadd29271303840d334b71db7766d2 | 1,109 | bluetape4k | MIT License |
app/src/main/java/com/kishan/employeetracker/ui/LaunchActivity.kt | KishanPRao | 308,958,648 | false | null | package com.kishan.employeetracker.ui
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.kishan.employeetracker.R
import com.kishan.employeetracker.data.DataStorage
import kotlinx.android.synthetic.main.activity_launch.*
import kotlinx.android.synthetic.main.fragment_base_launch.*
import kotlinx.android.synthetic.main.fragment_notice_launch.*
import org.joda.time.LocalDate
/**
* Created by <NAME> on 05/04/18.
*/
class LaunchActivity : AppCompatActivity() {
companion object {
private val TAG = LaunchActivity::class.java.simpleName
const val SLIDE_COUNT = 3
const val START_SLIDE = 0
const val RESIGN_SLIDE = 1
const val NOTICE_SLIDE = 2
}
private lateinit var dataStorage: DataStorage
private fun stop() {
// Wait for shared preferences to store the data.
Handler(Looper.getMainLooper()).postDelayed({
finish()
val intent = Intent(applicationContext, MainActivity::class.java)
startActivity(intent)
}, 50)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_launch)
dataStorage = DataStorage(applicationContext)
if (dataStorage.isInitialized()) {
stop()
return
}
// TODO: Until Skip, or last pager has been reached, not init!!
val viewPager = viewPager
val adapter = LaunchAdapter(supportFragmentManager, SLIDE_COUNT, {
Log.d(TAG, "onCreate, date => $it")
// if (it == null || viewPager.currentItem == (SLIDE_COUNT - 1)) {
if (it == null) {
Log.d(TAG, "onCreate, done")
stop()
} else {
if (viewPager.currentItem == START_SLIDE) {
dataStorage.putStartDate(it)
} else {
dataStorage.putResignDate(it)
}
viewPager.currentItem++
}
}, {
if (viewPager.currentItem == (SLIDE_COUNT - 1)) {
dataStorage.putNoticePeriod(it)
Log.d(TAG, "onCreate, done")
stop()
}
})
viewPager.adapter = adapter
}
class LaunchAdapter(
fm: FragmentManager,
private var numOfItems: Int,
private var dateCallback: (LocalDate?) -> Unit,
private var noticePeriodCallback: (Int) -> Unit
) : FragmentStatePagerAdapter(fm) {
override fun getCount() = numOfItems
private var resignFragment = ResignationLaunchFragment()
private var startFragment = StartDateLaunchFragment()
private var noticePeriodFragment = NoticePeriodLaunchFragment()
override fun getItem(position: Int): Fragment? {
return when (position) {
START_SLIDE -> {
startFragment.callback = dateCallback
startFragment
}
RESIGN_SLIDE -> {
resignFragment.callback = dateCallback
resignFragment
}
NOTICE_SLIDE -> {
noticePeriodFragment.callback = noticePeriodCallback
noticePeriodFragment
}
else -> {
Log.w(TAG, "Bad fragment")
null
}
}
}
}
class NoticePeriodLaunchFragment : Fragment() {
lateinit var callback: (Int) -> Unit
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_notice_launch, null, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// FIXME: Enter through keyboard, press back button!
numberPicker.minValue = 0
numberPicker.maxValue = 180
launch_notice_next.setOnClickListener {
callback.invoke(numberPicker.value)
}
}
}
class StartDateLaunchFragment : BaseLaunchFragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// datePicker.maxDate = System.currentTimeMillis()
launch_desc.text = resources.getString(R.string.launch_worked_desc)
launch_skip.visibility = View.GONE
}
}
class ResignationLaunchFragment : BaseLaunchFragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// datePicker.minDate = System.currentTimeMillis()
launch_desc.text = resources.getString(R.string.launch_resign_desc)
}
}
open class BaseLaunchFragment : Fragment() {
lateinit var callback: (LocalDate?) -> Unit
var date: LocalDate? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_base_launch, null, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
launch_next.setOnClickListener {
val day = datePicker.dayOfMonth
val month = datePicker.month + 1
val year = datePicker.year
date = LocalDate(year, month, day)
callback.invoke(date)
}
launch_skip.setOnClickListener {
callback.invoke(null)
}
}
}
} | 0 | Kotlin | 0 | 1 | f0a1fb4897af66bb3f01f83bd26b179b187155d4 | 5,079 | EmployeeTracker | MIT License |
app/src/main/java/com/dongyang/android/youdongknowme/ui/adapter/CafeteriaAdapter.kt | TeamDMU | 470,044,500 | false | {"Kotlin": 170393} | package com.dongyang.android.youdongknowme.ui.adapter
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.dongyang.android.youdongknowme.databinding.ItemCafeteriaMenuBinding
class CafeteriaAdapter : RecyclerView.Adapter<CafeteriaAdapter.ViewHolder>() {
init {
setHasStableIds(true)
}
private var menu = arrayListOf<String>()
inner class ViewHolder(private val binding: ItemCafeteriaMenuBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind(item: String) {
binding.menu = item
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
ItemCafeteriaMenuBinding.inflate(
LayoutInflater.from(parent.context), parent, false
)
)
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(menu[position])
}
@SuppressLint("NotifyDataSetChanged")
fun submitList(item: List<String>) {
menu.clear()
menu.addAll(item)
notifyDataSetChanged()
}
override fun getItemCount(): Int = menu.size
} | 2 | Kotlin | 0 | 9 | f12fc3a29dfab42add2116a7984146aeef250e4f | 1,345 | DMU-Android | Apache License 2.0 |
buildSrc/src/main/kotlin/DependencyHandlerExt.kt | profahad | 735,893,717 | false | {"Kotlin": 22730} | import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.dsl.DependencyHandler
fun DependencyHandler.implementation(dependency: String) {
add("implementation", dependency)
}
fun DependencyHandler.implementation(dependency: Dependency) {
add("implementation", dependency)
}
fun DependencyHandler.test(dependency: String) {
add("test", dependency)
}
fun DependencyHandler.androidTest(dependency: String) {
add("androidTest", dependency)
}
fun DependencyHandler.testImplementation(dependency: String) {
add("testImplementation", dependency)
}
fun DependencyHandler.testRuntimeOnly(dependency: String) {
add("testRuntimeOnly", dependency)
}
fun DependencyHandler.androidTestImplementation(dependency: String) {
add("androidTestImplementation", dependency)
}
fun DependencyHandler.debugImplementation(dependency: String) {
add("debugImplementation", dependency)
}
fun DependencyHandler.kapt(dependency: String) {
add("kapt", dependency)
} | 0 | Kotlin | 0 | 0 | 8a5e416b0d43745b1cf6542c3d316456e6ab8fe4 | 996 | super-app-xi | MIT License |
data/src/main/java/es/fnmtrcm/ceres/certificadoDigitalFNMT/data/local/model/RemoteConfigMenuModel.kt | CodeNationDev | 757,931,525 | false | {"Kotlin": 1417005, "C": 485745, "C++": 480977, "CMake": 283671, "Java": 166491} | package es.fnmtrcm.ceres.certificadoDigitalFNMT.data.local.model
import androidx.annotation.Keep
import com.google.gson.annotations.SerializedName
@Keep
data class RemoteConfigMenuModel(
@SerializedName("myCertificates") val myCertificates: Boolean,
@SerializedName("citizenFolder") val citizenFolder: Boolean,
@SerializedName("certificateImport") val certificateImport: Boolean,
@SerializedName("docsSign") val docsSign: Boolean,
@SerializedName("faqs") val faqs: Boolean,
@SerializedName("techService") val techService: Boolean,
@SerializedName("accessibilityDeclaration") val accessibilityDeclaration: Boolean,
@SerializedName("language") val language: Boolean,
@SerializedName("dnieViewer") val dnieViewer: Boolean
)
| 0 | Kotlin | 0 | 0 | 9c5d7b9355c406992ff9126d4bd01d49d4778048 | 759 | FabricK | MIT License |
solver/src/main/kotlin/pl/ipebk/solver/Card.kt | bskierys | 122,885,643 | false | null | package pl.ipebk.solver
/**
* Creates card with given feature variants. Feature ids are incrementing and starts with 0
* If you like to add custom features. Please use default [Card] constructor.
*
* @param featureVariants list of variants for default features
*/
class Card(vararg featureVariants: Int) {
val features = ArrayList<Feature>()
init {
var featureId = 0
featureVariants.forEach {
features.add(Feature(featureId, it))
featureId++
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Card
val common = features.intersect(this.features)
return common.size == this.features.size
}
override fun hashCode(): Int {
return features.hashCode()
}
override fun toString(): String {
return "Card(features=$features)"
}
} | 0 | Kotlin | 0 | 0 | 337fadb7a279b586ea5d46c48291f3e32bc0cf64 | 887 | DailySetSolver | Apache License 2.0 |
src/main/kotlin/io/kanro/idea/plugin/protobuf/lang/file/LibraryProtobufFileResolver.kt | chenyingchao | 356,158,388 | true | {"Kotlin": 153893, "Lex": 6288, "Java": 730} | package io.kanro.idea.plugin.protobuf.lang.file
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.vfs.VirtualFile
class LibraryProtobufFileResolver : FileResolver {
override fun findFile(path: String, project: Project): Iterable<VirtualFile> {
return ProjectRootManager.getInstance(project).orderEntries().allSourceRoots.mapNotNull {
it.findFileByRelativePath(path)?.takeIf { it.exists() }
}
}
override fun findFile(path: String, module: Module): Iterable<VirtualFile> {
return ModuleRootManager.getInstance(module).orderEntries()
.withoutModuleSourceEntries().allSourceRoots.mapNotNull {
it.findFileByRelativePath(path)?.takeIf { it.exists() }
}
}
}
class ModuleSourceProtobufFileResolver : FileResolver {
override fun findFile(path: String, project: Project): Iterable<VirtualFile> {
return listOf()
}
override fun findFile(path: String, module: Module): Iterable<VirtualFile> {
return ModuleRootManager.getInstance(module).sourceRoots.mapNotNull {
it.findFileByRelativePath(path)?.takeIf { it.exists() }
}
}
}
| 0 | null | 0 | 0 | 6258f1d20f3f99cbcf0a169335f1a2ad4011f3df | 1,331 | intellij-protobuf-plugin | Apache License 2.0 |
script/src/main/kotlin/script/command/Empty.kts | runetopic | 448,110,155 | false | null | package script.command
import xlitekt.game.content.command.CommandListener
import xlitekt.shared.insert
/**
* @author <NAME>
*/
insert<CommandListener>().command("empty").use { inventory.empty() }
| 0 | Kotlin | 3 | 8 | c896a2957470769a212961ba3e4331f04fc785df | 201 | xlitekt | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.