path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/kotlin/io/github/lapis256/block/Blocks.kt
Lapis256
681,085,511
false
null
package io.github.lapis256.block import io.github.lapis256.CardboardBoxMod import net.minecraft.util.registry.Registry object Blocks { val CARDBOARD_BOX = CardboardBoxBlock() object Ids { val CARDBOARD_BOX = CardboardBoxMod.id("cardboard_box") } fun init() { Registry.register(Registry.BLOCK, Ids.CARDBOARD_BOX, CARDBOARD_BOX) } }
0
Kotlin
0
0
de4018e9a00aa58095a4742c51e48db8cd7d0d94
371
cardboard-box-mod
MIT License
components/data-analyzer/src/test/kotlin/test/goodboards/app/analyzer/AnalyzerWorkerTest.kt
CSCI-5828-Foundations-Sftware-Engr
614,026,505
false
null
package test.goodboards.app.analyzer import com.goodboards.app.analyzer.* import com.goodboards.db.DBInterface import com.goodboards.db.News import com.goodboards.redis.RedisInterface import io.mockk.every import io.mockk.mockk import io.mockk.mockkObject import io.mockk.verify import org.junit.Test import kotlin.test.assertEquals class AnalyzerWorkerTest{ // test if the news has not been included in db @Test fun testSetDoubleApostrophe(){ val mockedInput = "I'm" assertEquals("I''m", AnalyzerWorkerHelper.setDoubleApostrophe(mockedInput)) } @Test fun testNewsNotIncludedinDB(){ // mock the news unit that will be added val newsUnits = listOf<String>( """{ "gameID": "Fake gameId", "title": "Fake title", "description": "Fake description", "url": "Fake URL" }""".trimIndent() ) mockkObject(Wrapper) val mockedRedisInterface: RedisInterface = mockk(relaxed = true) val mockedDBInterface: DBInterface = mockk(relaxed = true) val mockedNewsResponse: List<News> = listOf() every { Wrapper.getRedisInterface() } returns mockedRedisInterface every { Wrapper.getRandomUUID()} returns "FakeUUID1" every { Wrapper.getDBInterface() } returns mockedDBInterface every { mockedRedisInterface.getFromList("news:collect-analyze", 10)} returns newsUnits every { mockedDBInterface.getNewsBasedOnTitle("Fake title") } returns mockedNewsResponse val newsItem = NewsUnit("Fake gameId", "Fake title", "Fake description", "Fake URL") every { mockedDBInterface.addNews(newsItem.title, newsItem.description, newsItem.url, newsItem.gameID, "FakeUUID1") } returns Unit val task = AnalyzerTask("Analyzer Task test") val worker = AnalyzerWorker() worker.execute(task) verify { mockedDBInterface.addNews(newsItem.title, newsItem.description, newsItem.url, newsItem.gameID, "FakeUUID1") } } @Test fun testNewsAlreadyinDB(){ val newsUnits = listOf<String>("""{ "gameID": "Fake gameId", "title": "Fake title", "description": "Fake description", "url": "Fake URL" }""") mockkObject(Wrapper) val mockedRedisInterface: RedisInterface = mockk(relaxed = true) val mockedDBInterface: DBInterface = mockk(relaxed = true) val mockedNewsResponse: List<News> = listOf(News("Fake id","Fake gameid", "Fake title reply", "Fake description reply", "Fake URL reply")) every { Wrapper.getRedisInterface() } returns mockedRedisInterface every { Wrapper.getRandomUUID()} returns "FakeUUID1" every { Wrapper.getDBInterface() } returns mockedDBInterface every { mockedRedisInterface.getFromList("news:collect-analyze", 10)} returns newsUnits every { mockedDBInterface.getNewsBasedOnTitle("Fake title") } returns mockedNewsResponse val task = AnalyzerTask("Analyzer Task test") val worker = AnalyzerWorker() worker.execute(task) } }
38
Kotlin
1
2
7b6f00de4f9bd906f1e2d12a414228bd67edbf58
3,162
slackers
Apache License 2.0
shared/src/androidMain/kotlin/com/architect/kmpessentials/permissions/services/PermissionsTransformer.kt
TheArchitect123
801,452,364
false
null
package com.architect.kmpessentials.permissions.services import android.Manifest import android.os.Build import com.architect.kmpessentials.permissions.Permission internal object PermissionsTransformer { fun getPermissionFromEnum(permission: Permission): String { return when (permission) { Permission.Sms -> Manifest.permission.SEND_SMS Permission.Microphone -> Manifest.permission.RECORD_AUDIO Permission.Camera -> Manifest.permission.CAMERA Permission.Location -> Manifest.permission.ACCESS_FINE_LOCATION Permission.CoarseLocation -> Manifest.permission.ACCESS_COARSE_LOCATION Permission.PushNotifications -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { Manifest.permission.POST_NOTIFICATIONS } else { "" } Permission.ExternalStorage -> Manifest.permission.READ_EXTERNAL_STORAGE Permission.Biometrics -> "android.permission.USE_CREDENTIALS" Permission.Contacts -> Manifest.permission.READ_CONTACTS Permission.Vibrator -> Manifest.permission.VIBRATE else -> "" } } fun getPermissionsFromEnum(permission: Permission): Array<String> { if (permission == Permission.Location) { return arrayOf( Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION ) } return arrayOf("") } }
5
null
1
96
3f1e7e14bf7e3da6b20c1d4bf2924ac4571a75b6
1,524
KmpEssentials
MIT License
app/src/main/java/kr/co/jsh/localclass/PausableDispatcher.kt
jsh-me
257,524,610
false
null
package kr.co.jsh.localclass import android.os.Handler import kotlinx.coroutines.CoroutineDispatcher import java.util.* import kotlin.coroutines.CoroutineContext class PausableDispatcher(private val handler: Handler): CoroutineDispatcher() { private val queue: Queue<Runnable> = LinkedList() private var isPaused: Boolean = false @Synchronized override fun dispatch(context: CoroutineContext, block: Runnable) { if (isPaused) { queue.add(block) } else { handler.post(block) } } @Synchronized fun pause() { isPaused = true } @Synchronized fun resume() { isPaused = false runQueue() } private fun runQueue() { queue.iterator().let { while (it.hasNext()) { val block = it.next() it.remove() handler.post(block) } } } }
2
Kotlin
20
97
d6e63521991902f44f4afb05b6fd22fb68f3d4a3
921
simple-android-editor
Apache License 2.0
app/src/main/java/kr/co/jsh/localclass/PausableDispatcher.kt
jsh-me
257,524,610
false
null
package kr.co.jsh.localclass import android.os.Handler import kotlinx.coroutines.CoroutineDispatcher import java.util.* import kotlin.coroutines.CoroutineContext class PausableDispatcher(private val handler: Handler): CoroutineDispatcher() { private val queue: Queue<Runnable> = LinkedList() private var isPaused: Boolean = false @Synchronized override fun dispatch(context: CoroutineContext, block: Runnable) { if (isPaused) { queue.add(block) } else { handler.post(block) } } @Synchronized fun pause() { isPaused = true } @Synchronized fun resume() { isPaused = false runQueue() } private fun runQueue() { queue.iterator().let { while (it.hasNext()) { val block = it.next() it.remove() handler.post(block) } } } }
2
Kotlin
20
97
d6e63521991902f44f4afb05b6fd22fb68f3d4a3
921
simple-android-editor
Apache License 2.0
core-network/src/main/java/com/google/samples/apps/nowinandroid/core/network/fake/FakeNiaNetworkDataSource.kt
tenSunFree
529,928,829
false
{"Kotlin": 705594, "Shell": 8844}
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.samples.nowinandroid_demo.core.network.fake import android.util.Log import com.samples.nowinandroid_demo.core.network.Dispatcher import com.samples.nowinandroid_demo.core.network.NiaDispatchers.IO import com.samples.nowinandroid_demo.core.network.NiaNetworkDataSource import com.samples.nowinandroid_demo.core.network.model.NetworkAuthor import com.samples.nowinandroid_demo.core.network.model.NetworkChangeList import com.samples.nowinandroid_demo.core.network.model.NetworkNewsResource import com.samples.nowinandroid_demo.core.network.model.NetworkTopic import javax.inject.Inject import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json /** * [NiaNetworkDataSource] implementation that provides static news resources to aid development */ class FakeNiaNetworkDataSource @Inject constructor( @Dispatcher(IO) private val ioDispatcher: CoroutineDispatcher, private val networkJson: Json ) : NiaNetworkDataSource { override suspend fun getTopics(ids: List<String>?): List<NetworkTopic> = withContext(ioDispatcher) { networkJson.decodeFromString(FakeDataSource.topicsData) } override suspend fun getNewsResources(): List<NetworkNewsResource> { return withContext(ioDispatcher) { Log.d("", "FakeNiaNetworkDataSource, getNewsResources") networkJson.decodeFromString(FakeDataSource.data) } } override suspend fun getAuthors(ids: List<String>?): List<NetworkAuthor> = withContext(ioDispatcher) { networkJson.decodeFromString(FakeDataSource.authors) } override suspend fun getTopicChangeList(after: Int?): List<NetworkChangeList> = getTopics().mapToChangeList(NetworkTopic::id) override suspend fun getAuthorChangeList(after: Int?): List<NetworkChangeList> = getAuthors().mapToChangeList(NetworkAuthor::id) override suspend fun getNewsResourceChangeList(after: Int?): List<NetworkChangeList> { Log.d("", "FakeNiaNetworkDataSource, getNewsResourceChangeList, after: $after") Log.d("", "FakeNiaNetworkDataSource, getNewsResourceChangeList, id: ${NetworkNewsResource::id}") return getNewsResources().mapToChangeList(NetworkNewsResource::id) } } /** * Converts a list of [T] to change list of all the items in it where [idGetter] defines the * [NetworkChangeList.id] */ private fun <T> List<T>.mapToChangeList( idGetter: (T) -> String ) = mapIndexed { index, item -> NetworkChangeList( id = idGetter(item), changeListVersion = index, isDelete = false, ) }
0
Kotlin
1
1
42d7efb81102aa3c3a9407dbc5629147d57e0c30
3,315
nowinandroid3
Apache License 2.0
app/src/main/java/com/shyber/glass/sample/apidemo/opengl/CubeRenderer.kt
OlegSharshakovShyber
730,920,772
false
{"Kotlin": 70140}
package com.shyber.glass.sample.apidemo.opengl import android.opengl.GLES20 import android.opengl.Matrix import android.os.SystemClock import com.google.android.glass.timeline.GlRenderer import java.util.concurrent.TimeUnit import javax.microedition.khronos.egl.EGLConfig /** * Renders a 3D OpenGL Cube on a [LiveCard]. */ class CubeRenderer : GlRenderer { private val mMVPMatrix: FloatArray = FloatArray(16) private val mProjectionMatrix: FloatArray = FloatArray(16) private val mViewMatrix: FloatArray = FloatArray(16) private val mRotationMatrix: FloatArray = FloatArray(16) private val mFinalMVPMatrix: FloatArray = FloatArray(16) private var mCube: Cube? = null private var mCubeRotation = 0f private var mLastUpdateMillis: Long = 0 override fun onSurfaceCreated(config: EGLConfig) { // Set the background frame color GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f) GLES20.glClearDepthf(1.0f) GLES20.glEnable(GLES20.GL_DEPTH_TEST) GLES20.glDepthFunc(GLES20.GL_LEQUAL) mCube = Cube() } override fun onSurfaceChanged(width: Int, height: Int) { val ratio = width.toFloat() / height GLES20.glViewport(0, 0, width, height) // This projection matrix is applied to object coordinates in the onDrawFrame() method. Matrix.frustumM(mProjectionMatrix, 0, -ratio, ratio, -1.0f, 1.0f, 3.0f, 7.0f) // modelView = projection x view Matrix.multiplyMM(mMVPMatrix, 0, mProjectionMatrix, 0, mViewMatrix, 0) } override fun onDrawFrame() { GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT or GLES20.GL_DEPTH_BUFFER_BIT) // Apply the rotation. Matrix.setRotateM(mRotationMatrix, 0, mCubeRotation, 1.0f, 1.0f, 1.0f) // Combine the rotation matrix with the projection and camera view Matrix.multiplyMM(mFinalMVPMatrix, 0, mMVPMatrix, 0, mRotationMatrix, 0) // Draw cube. mCube?.draw(mFinalMVPMatrix) updateCubeRotation() } /** Updates the cube rotation. */ private fun updateCubeRotation() { if (mLastUpdateMillis != 0L) { val factor = (SystemClock.elapsedRealtime() - mLastUpdateMillis) / FRAME_TIME_MILLIS mCubeRotation += CUBE_ROTATION_INCREMENT * factor } mLastUpdateMillis = SystemClock.elapsedRealtime() } companion object { /** Rotation increment per frame. */ private const val CUBE_ROTATION_INCREMENT = 0.6f /** The refresh rate, in frames per second. */ private const val REFRESH_RATE_FPS = 60 /** The duration, in milliseconds, of one frame. */ private val FRAME_TIME_MILLIS = TimeUnit.SECONDS.toMillis(1) / REFRESH_RATE_FPS.toFloat() } init { // Set the fixed camera position (View matrix). Matrix.setLookAtM( mViewMatrix, 0, 0.0f, 0.0f, -4.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f ) } }
0
Kotlin
0
0
4697aa0d155833e374785816e39a342118f247b8
3,109
gdk-apidemo-kotlin-sample
Apache License 2.0
src/main/kotlin/de/wulkanat/new_frontiers/galaxy/System.kt
wulkanat
249,787,498
false
null
package de.wulkanat.new_frontiers.galaxy import de.wulkanat.new_frontiers.extensions.kotlin.random.normalDistributedInt import de.wulkanat.new_frontiers.galaxy.GalacticPosition import de.wulkanat.new_frontiers.galaxy.Sun import kotlin.random.Random class System(val position: GalacticPosition) { private val random: Random = Random(position.hashCode()) val suns: List<Sun> init { val sunCount = random.normalDistributedInt(1..4, expectation = 1.8, variance = 0.5) suns = List(sunCount) { Sun(random.nextInt(), this) } } }
0
Kotlin
0
0
47684447c335bc717511d79bda7dac277ce106ff
576
new-frontiers-fabric
MIT License
src/main/java/io/github/binaryfoo/decoders/VisaCardVerificationResultsDecoder.kt
jamehuang2012
41,445,985
true
{"Kotlin": 148292, "Java": 137541, "Groovy": 674}
package io.github.binaryfoo.decoders /** * From Visa Contactless Payment Specification v2.1 pD-26 * Visa Integrated Circuit Card Card Specification, Version 1.4.0 pA-12 */ public class VisaCardVerificationResultsDecoder : EmvBitStringDecoder("fields/visa-cvr.txt", false)
0
Kotlin
0
0
391537fe3e5f1cd7cfcd0f76a047f563e0775f84
281
emv-bertlv
MIT License
feature/settings/src/main/kotlin/com/github/ilikeyourhat/lsaa/feature/settings/home/SettingsActivity.kt
ILikeYourHat
385,717,121
false
null
package pl.softwarealchemy.lsaa.feature.settings.home import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import org.koin.androidx.viewmodel.ext.android.viewModel internal class SettingsActivity : ComponentActivity() { private val viewModel: SettingsViewModel by viewModel() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { SettingsUi(uiListener = viewModel) } } }
12
Kotlin
2
4
3c2073e1eb9f10285c84382caf5caad455f2bb9a
529
Large-Scale-Android-App
Apache License 2.0
app/src/main/java/com/justmobiledev/developerportfolio/ItemDetailFragment.kt
justmobiledev
164,226,251
false
null
package com.justmobiledev.developerportfolio import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.justmobiledev.developerportfolio.portfolio.PortfolioContent import kotlinx.android.synthetic.main.activity_item_detail.* import kotlinx.android.synthetic.main.item_detail.view.* /** * A fragment representing a single Item detail screen. * This fragment is either contained in a [ItemListActivity] * in two-pane mode (on tablets) or a [ItemDetailActivity] * on handsets. */ class ItemDetailFragment : Fragment() { /** * The dummy content this fragment is presenting. */ private var item: PortfolioContent.DummyItem? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { if (it.containsKey(ARG_ITEM_ID)) { // Load the dummy content specified by the fragment // arguments. In a real-world scenario, use a Loader // to load content from a content provider. item = PortfolioContent.ITEM_MAP[it.getString(ARG_ITEM_ID)] } if (it.containsKey(ARG_ITEM_NAME)) { // Load the dummy content specified by the fragment // arguments. In a real-world scenario, use a Loader // to load content from a content provider. var title = it.getString(ARG_ITEM_NAME) activity?.toolbar_layout?.title = title } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { var rootView : View? if (item?.id.equals(ItemListActivity.MENU_OBJECTIVE_ID)) { rootView = inflater.inflate(R.layout.fragment_objective, container, false) } else if (item?.id.equals(ItemListActivity.MENU_EXPERIENCE_ID)) { rootView = inflater.inflate(R.layout.fragment_experience, container, false) } else if (item?.id.equals(ItemListActivity.MENU_EDUCATION_ID)) { rootView = inflater.inflate(R.layout.fragment_education, container, false) } else if (item?.id.equals(ItemListActivity.MENU_CERTIFICATES_ID)) { rootView = inflater.inflate(R.layout.fragment_certificates, container, false) } else if (item?.id.equals(ItemListActivity.MENU_ANDROID_APPS_ID)) { rootView = inflater.inflate(R.layout.fragment_android_apps, container, false) } else if (item?.id.equals(ItemListActivity.MENU_IOS_APPS_ID)) { rootView = inflater.inflate(R.layout.fragment_ios_apps, container, false) } else { rootView = inflater.inflate(R.layout.fragment_evolution_steps, container, false) } return rootView } companion object { /** * The fragment argument representing the item ID that this fragment * represents. */ const val ARG_ITEM_ID = "item_id" const val ARG_ITEM_NAME = "item_name" } }
0
Kotlin
0
2
7e6096cc33c42d6a55de7dd0dd10e6973a24aba7
3,250
android-kotlin-developer-portfolio-1
MIT License
ktest-integration/ktest-resttest/src/main/kotlin/run/smt/ktest/resttest/skeleton/FeatureSpecSkeleton.kt
saksmt
115,024,215
false
null
package run.smt.ktest.resttest.skeleton import run.smt.ktest.resttest.api.RestTestSpecSkeleton import run.smt.ktest.resttest.api.TestSpecProvider import run.smt.ktest.specs.FeatureSpec class FeatureSpecSkeleton : RestTestSpecSkeleton<FeatureSpec> { override fun FeatureSpec.execRestTest(restTestTemplate: TestSpecProvider) { restTestTemplate { annotations, name, body -> scenario(name, annotations, body) } } }
17
Kotlin
2
12
22ba03a69dcf04d95c9e3f5b1c3740ef4dcd07e5
449
ktest
MIT License
scanner/src/main/kotlin/experimental/ExperimentalScanner.kt
mkajitansnyk
437,785,555
true
{"Kotlin": 3893995, "JavaScript": 291650, "HTML": 115254, "Haskell": 30438, "CSS": 25058, "Python": 20673, "FreeMarker": 20565, "Dockerfile": 7796, "Shell": 7795, "Roff": 7585, "Scala": 6656, "Ruby": 4423, "ANTLR": 1883, "Go": 1235, "Rust": 280, "Emacs Lisp": 191}
/* * Copyright (C) 2021 HERE Europe B.V. * Copyright (C) 2021 Bosch.IO GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ package org.ossreviewtoolkit.scanner.experimental import java.time.Instant import kotlin.time.measureTimedValue import org.ossreviewtoolkit.downloader.DownloadException import org.ossreviewtoolkit.model.AccessStatistics import org.ossreviewtoolkit.model.KnownProvenance import org.ossreviewtoolkit.model.OrtIssue import org.ossreviewtoolkit.model.OrtResult import org.ossreviewtoolkit.model.Package import org.ossreviewtoolkit.model.PackageType import org.ossreviewtoolkit.model.Provenance import org.ossreviewtoolkit.model.ScanRecord import org.ossreviewtoolkit.model.ScanResult import org.ossreviewtoolkit.model.ScanSummary import org.ossreviewtoolkit.model.ScannerRun import org.ossreviewtoolkit.model.Severity import org.ossreviewtoolkit.model.config.DownloaderConfiguration import org.ossreviewtoolkit.model.config.ScannerConfiguration import org.ossreviewtoolkit.model.config.ScannerOptions import org.ossreviewtoolkit.utils.common.collectMessagesAsString import org.ossreviewtoolkit.utils.core.Environment import org.ossreviewtoolkit.utils.core.log class ExperimentalScanner( val scannerConfig: ScannerConfiguration, val downloaderConfig: DownloaderConfiguration, val provenanceDownloader: ProvenanceDownloader, val storageReaders: List<ScanStorageReader>, val storageWriters: List<ScanStorageWriter>, val packageProvenanceResolver: PackageProvenanceResolver, val nestedProvenanceResolver: NestedProvenanceResolver, val scannerWrappers: Map<PackageType, List<ScannerWrapper>> ) { init { require(scannerWrappers.isNotEmpty() && scannerWrappers.any { it.value.isNotEmpty() }) { "At least one ScannerWrapper must be provided." } } suspend fun scan(ortResult: OrtResult): OrtResult { val startTime = Instant.now() val projectScannerWrappers = scannerWrappers[PackageType.PROJECT].orEmpty() val packageScannerWrappers = scannerWrappers[PackageType.PACKAGE].orEmpty() val projectResults = if (projectScannerWrappers.isNotEmpty()) { val packages = ortResult.getProjects().mapTo(mutableSetOf()) { it.toPackage() } log.info { "Scanning ${packages.size} projects with ${projectScannerWrappers.size} scanners." } scan(packages, ScanContext(ortResult.labels, PackageType.PROJECT)) } else { log.info { "Skipping scan of projects because no project scanner is configured." } emptyMap() } val packageResults = if (packageScannerWrappers.isNotEmpty()) { val packages = ortResult.getPackages().mapTo(mutableSetOf()) { it.pkg } log.info { "Scanning ${packages.size} packages with ${packageScannerWrappers.size} scanners." } scan(packages, ScanContext(ortResult.labels, PackageType.PACKAGE)) } else { log.info { "Skipping scan of packages because no package scanner is configured." } emptyMap() } val results = projectResults + packageResults val endTime = Instant.now() val scanResults = results.entries.associateTo(sortedMapOf()) { it.key.id to it.value.merge() } val scanRecord = ScanRecord( scanResults = scanResults, storageStats = AccessStatistics() // TODO: Record access statistics. ) val filteredScannerOptions = mutableMapOf<String, ScannerOptions>() projectScannerWrappers.forEach { scannerWrapper -> scannerConfig.options?.get(scannerWrapper.name)?.let { options -> filteredScannerOptions[scannerWrapper.name] = scannerWrapper.filterSecretOptions(options) } } packageScannerWrappers.forEach { scannerWrapper -> scannerConfig.options?.get(scannerWrapper.name)?.let { options -> filteredScannerOptions[scannerWrapper.name] = scannerWrapper.filterSecretOptions(options) } } val filteredScannerConfig = scannerConfig.copy(options = filteredScannerOptions) val scannerRun = ScannerRun(startTime, endTime, Environment(), filteredScannerConfig, scanRecord) return ortResult.copy(scanner = scannerRun) } suspend fun scan(packages: Set<Package>, context: ScanContext): Map<Package, NestedProvenanceScanResult> { val scanners = scannerWrappers[context.packageType].orEmpty() if (scanners.isEmpty()) return emptyMap() log.info { "Resolving provenance for ${packages.size} packages." } // TODO: Handle issues for packages where provenance cannot be resolved. val (packageProvenances, packageProvenanceDuration) = measureTimedValue { getPackageProvenances(packages) } log.info { "Resolved provenance for ${packages.size} packages in $packageProvenanceDuration." } log.info { "Resolving nested provenances for ${packages.size} packages." } val (nestedProvenances, nestedProvenanceDuration) = measureTimedValue { getNestedProvenances(packageProvenances) } log.info { "Resolved nested provenances for ${packages.size} packages in $nestedProvenanceDuration." } val allKnownProvenances = ( packageProvenances.values.filterIsInstance<KnownProvenance>() + nestedProvenances.values.flatMap { nestedProvenance -> nestedProvenance.subRepositories.values } ).toSet() val scanResults = mutableMapOf<ScannerWrapper, MutableMap<KnownProvenance, List<ScanResult>>>() // Get stored scan results for each ScannerWrapper by provenance. log.info { "Reading stored scan results for ${packageProvenances.size} packages with ${allKnownProvenances.size} " + "provenances." } val (storedResults, readDuration) = measureTimedValue { getStoredResults(scanners, allKnownProvenances, nestedProvenances, packageProvenances) } log.info { "Read stored scan results in $readDuration:" } storedResults.entries.forEach { (scanner, results) -> log.info { "\t${scanner.name}: Results for ${results.size} of ${allKnownProvenances.size} provenances." } } scanResults += storedResults // Check which packages have incomplete scan results. val packagesWithIncompleteScanResult = getPackagesWithIncompleteResults(scanners, packages, packageProvenances, nestedProvenances, scanResults) log.info { "${packagesWithIncompleteScanResult.size} packages have incomplete scan results." } log.info { "Starting scan of missing packages if any package based scanners are configured." } // Scan packages with incomplete scan results. packagesWithIncompleteScanResult.forEach { (pkg, scanners) -> // TODO: Move to function. // TODO: Verify that there are still missing scan results for the package, previous scan of another package // from the same repository could have fixed that already. scanners.filterIsInstance<PackageBasedRemoteScannerWrapper>().forEach { scanner -> log.info { "Scanning ${pkg.id.toCoordinates()} with package based remote scanner ${scanner.name}." } // Scan whole package with remote scanner. // TODO: Use coroutines to execute scanners in parallel. val scanResult = scanner.scanPackage(pkg, context) log.info { "Scan of ${pkg.id.toCoordinates()} with package based remote scanner ${scanner.name} finished." } // Split scan results by provenance and add them to the map of scan results. val nestedProvenanceScanResult = scanResult.toNestedProvenanceScanResult(nestedProvenances.getValue(pkg)) nestedProvenanceScanResult.scanResults.forEach { (provenance, scanResultsForProvenance) -> val scanResultsForScanner = scanResults.getOrPut(scanner) { mutableMapOf() } scanResultsForScanner[provenance] = scanResultsForScanner[provenance].orEmpty() + scanResultsForProvenance if (scanner.criteria != null) { storageWriters.filterIsInstance<ProvenanceBasedScanStorageWriter>().forEach { writer -> scanResultsForProvenance.forEach { scanResult -> // TODO: Only store new scan results, for nested provenance some of them could have a // stored result already. writer.write(scanResult) } } } } } } // Check which provenances have incomplete scan results. val provenancesWithIncompleteScanResults = getProvenancesWithIncompleteScanResults(scanners, allKnownProvenances, scanResults) log.info { "${provenancesWithIncompleteScanResults.size} provenances have incomplete scan results." } log.info { "Starting scan of missing provenances if any provenance based scanners are configured." } provenancesWithIncompleteScanResults.forEach { (provenance, scanners) -> // Scan provenances with remote scanners. // TODO: Move to function. scanners.filterIsInstance<ProvenanceBasedRemoteScannerWrapper>().forEach { scanner -> log.info { "Scanning $provenance with provenance based remote scanner ${scanner.name}." } // TODO: Use coroutines to execute scanners in parallel. val scanResult = scanner.scanProvenance(provenance, context) log.info { "Scan of $provenance with provenance based remote scanner ${scanner.name} finished." } val scanResultsForScanner = scanResults.getOrPut(scanner) { mutableMapOf() } scanResultsForScanner[provenance] = scanResultsForScanner[provenance].orEmpty() + scanResult if (scanner.criteria != null) { storageWriters.filterIsInstance<ProvenanceBasedScanStorageWriter>().forEach { writer -> writer.write(scanResult) } } } // Scan provenances with local scanners. val localScanners = scanners.filterIsInstance<LocalScannerWrapper>() if (localScanners.isNotEmpty()) { val localScanResults = scanLocal(provenance, localScanners, context) localScanResults.forEach { (scanner, scanResult) -> val scanResultsForScanner = scanResults.getOrPut(scanner) { mutableMapOf() } scanResultsForScanner[provenance] = scanResultsForScanner[provenance].orEmpty() + scanResult if (scanner.criteria != null) { storageWriters.filterIsInstance<ProvenanceBasedScanStorageWriter>().forEach { writer -> writer.write(scanResult) } } } } } val nestedProvenanceScanResults = createNestedProvenanceScanResults(packages, nestedProvenances, scanResults) packagesWithIncompleteScanResult.forEach { (pkg, _) -> storageWriters.filterIsInstance<PackageBasedScanStorageWriter>().forEach { writer -> nestedProvenanceScanResults[pkg]?.let { nestedProvenanceScanResult -> val filteredScanResult = nestedProvenanceScanResult.filter { scanResult -> scanners.find { it.name == scanResult.scanner.name }?.criteria != null } if (filteredScanResult.isComplete()) { // TODO: Save only results for scanners which did not have a stored result. writer.write(pkg, filteredScanResult) } } } } return nestedProvenanceScanResults } private fun getPackageProvenances(packages: Set<Package>): Map<Package, Provenance> = packages.associateWith { pkg -> packageProvenanceResolver.resolveProvenance(pkg, downloaderConfig.sourceCodeOrigins) } private fun getNestedProvenances(packageProvenances: Map<Package, Provenance>): Map<Package, NestedProvenance> = packageProvenances.mapNotNull { (pkg, provenance) -> (provenance as? KnownProvenance)?.let { knownProvenance -> pkg to nestedProvenanceResolver.resolveNestedProvenance(knownProvenance) } }.toMap() private fun getStoredResults( scannerWrappers: List<ScannerWrapper>, provenances: Set<KnownProvenance>, nestedProvenances: Map<Package, NestedProvenance>, packageProvenances: Map<Package, Provenance> ): Map<ScannerWrapper, MutableMap<KnownProvenance, List<ScanResult>>> { return scannerWrappers.associateWith { scanner -> val scannerCriteria = scanner.criteria ?: return@associateWith mutableMapOf() val result = mutableMapOf<KnownProvenance, List<ScanResult>>() provenances.forEach { provenance -> if (result[provenance] != null) return@forEach storageReaders.forEach { reader -> @Suppress("NON_EXHAUSTIVE_WHEN_STATEMENT") when (reader) { is PackageBasedScanStorageReader -> { packageProvenances.entries.find { it.value == provenance }?.key?.let { pkg -> val nestedProvenance = nestedProvenances.getValue(pkg) reader.read(pkg, nestedProvenance, scannerCriteria).forEach { scanResult2 -> // TODO: Do not overwrite entries from other storages in result. // TODO: Map scan result to known nested provenance for package. result += scanResult2.scanResults } } } is ProvenanceBasedScanStorageReader -> { // TODO: Do not overwrite entries from other storages in result. result[provenance] = reader.read(provenance, scannerCriteria) } } } } result } } private fun getPackagesWithIncompleteResults( scannerWrappers: List<ScannerWrapper>, packages: Set<Package>, packageProvenances: Map<Package, Provenance>, nestedProvenances: Map<Package, NestedProvenance>, scanResults: Map<ScannerWrapper, Map<KnownProvenance, List<ScanResult>>>, ): Map<Package, List<ScannerWrapper>> = packages.associateWith { pkg -> scannerWrappers.filter { scanner -> val hasPackageProvenanceResult = scanResults.hasResult(scanner, packageProvenances.getValue(pkg)) val hasAllNestedProvenanceResults = nestedProvenances[pkg]?.let { nestedProvenance -> scanResults.hasResult(scanner, nestedProvenance.root) && nestedProvenance.subRepositories.all { (_, provenance) -> scanResults.hasResult(scanner, provenance) } } != false !hasPackageProvenanceResult || !hasAllNestedProvenanceResults } }.filterValues { it.isNotEmpty() } private fun getProvenancesWithIncompleteScanResults( scannerWrappers: List<ScannerWrapper>, provenances: Set<KnownProvenance>, scanResults: Map<ScannerWrapper, Map<KnownProvenance, List<ScanResult>>> ): Map<KnownProvenance, List<ScannerWrapper>> = provenances.associateWith { provenance -> scannerWrappers.filter { scanner -> !scanResults.hasResult(scanner, provenance) } }.filterValues { it.isNotEmpty() } private fun createNestedProvenanceScanResults( packages: Set<Package>, nestedProvenances: Map<Package, NestedProvenance>, scanResults: Map<ScannerWrapper, Map<KnownProvenance, List<ScanResult>>> ): Map<Package, NestedProvenanceScanResult> = packages.associateWith { pkg -> val nestedProvenance = nestedProvenances.getValue(pkg) val provenances = nestedProvenance.getProvenances() val scanResultsByProvenance = provenances.associateWith { provenance -> scanResults.values.flatMap { it[provenance].orEmpty() } } NestedProvenanceScanResult(nestedProvenance, scanResultsByProvenance) } private fun scanLocal( provenance: KnownProvenance, scanners: List<LocalScannerWrapper>, context: ScanContext ): Map<LocalScannerWrapper, ScanResult> { val downloadDir = try { provenanceDownloader.download(provenance) } catch (e: DownloadException) { val message = "Could not download provenance $provenance: ${e.collectMessagesAsString()}" log.error { message } val summary = ScanSummary( startTime = Instant.now(), endTime = Instant.now(), packageVerificationCode = "", licenseFindings = sortedSetOf(), copyrightFindings = sortedSetOf(), issues = listOf( OrtIssue( source = "Downloader", message = message, severity = Severity.ERROR ) ) ) return scanners.associateWith { scanner -> ScanResult( provenance = provenance, scanner = scanner.details, summary = summary ) } } return scanners.associateWith { scanner -> log.info { "Scanning $provenance with local scanner ${scanner.name}." } val summary = scanner.scanPath(downloadDir, context) log.info { "Scan of $provenance with local scanner ${scanner.name} finished." } ScanResult(provenance, scanner.details, summary) } } } /** * Split this [ScanResult] into separate results for each [KnownProvenance] contained in the [nestedProvenance] by * matching the paths of findings with the paths in the nested provenance. */ fun ScanResult.toNestedProvenanceScanResult(nestedProvenance: NestedProvenance): NestedProvenanceScanResult { val provenanceByPath = nestedProvenance.subRepositories.toList().toMutableList<Pair<String, KnownProvenance>>() .also { it += ("" to nestedProvenance.root) } .sortedByDescending { it.first.length } val copyrightFindingsByProvenance = summary.copyrightFindings.groupBy { copyrightFinding -> provenanceByPath.first { copyrightFinding.location.path.startsWith(it.first) }.second } val licenseFindingsByProvenance = summary.licenseFindings.groupBy { licenseFinding -> provenanceByPath.first { licenseFinding.location.path.startsWith(it.first) }.second } val provenances = nestedProvenance.getProvenances() val scanResultsByProvenance = provenances.associateWith { provenance -> // TODO: Find a solution for the incorrect packageVerificationCode and for how to associate issues to the // correct scan result. listOf( copy( summary = summary.copy( licenseFindings = licenseFindingsByProvenance[provenance].orEmpty().toSortedSet(), copyrightFindings = copyrightFindingsByProvenance[provenance].orEmpty().toSortedSet() ) ) ) } return NestedProvenanceScanResult(nestedProvenance, scanResultsByProvenance) } private fun Map<ScannerWrapper, Map<KnownProvenance, List<ScanResult>>>.hasResult( scanner: ScannerWrapper, provenance: Provenance ) = getValue(scanner)[provenance].let { it != null && it.isNotEmpty() }
63
null
0
0
0e95fcb35d058ad399001aa17122f65ee34c95e9
21,171
ort
Apache License 2.0
sample/src/main/java/com/example/webtrekk/androidsdk/SettingsExample.kt
Webtrekk
166,987,236
false
null
package com.example.webtrekk.androidsdk import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.settings_activity.button import kotlinx.android.synthetic.main.settings_activity.button2 import kotlinx.android.synthetic.main.settings_activity.button3 import kotlinx.android.synthetic.main.settings_activity.disable_anonymous import kotlinx.android.synthetic.main.settings_activity.enable_anonymous import kotlinx.android.synthetic.main.settings_activity.sw_optout import webtrekk.android.sdk.Webtrekk class SettingsExample : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.settings_activity) button.setOnClickListener { val stringIds = BuildConfig.TRACK_IDS val domain = BuildConfig.DOMEIN val elements: List<String> = stringIds.split(",") Webtrekk.getInstance().setIdsAndDomain(elements, domain) } button2.setOnClickListener { Webtrekk.getInstance().setIdsAndDomain( listOf("826582930668809"), "http://vdestellaaccount01.wt-eu02.net" ) } button3.setOnClickListener { val stringIds = BuildConfig.TRACK_IDS val domain = BuildConfig.DOMEIN var elements: MutableList<String> = stringIds.split(",").toMutableList() elements.add("826582930668809") Webtrekk.getInstance().setIdsAndDomain(elements, domain) } enable_anonymous.setOnClickListener { Webtrekk.getInstance().anonymousTracking(true, setOf("la", "cs804", "cs821"), generateNewEverId = false) } disable_anonymous.setOnClickListener { Webtrekk.getInstance().anonymousTracking(false, generateNewEverId = false) } sw_optout.isChecked=Webtrekk.getInstance().hasOptOut() sw_optout.setOnCheckedChangeListener { buttonView, isChecked -> Webtrekk.getInstance().optOut(isChecked) } } }
1
null
1
13
f493dfe7e85591e6806fa3a94c50e394eda3cb60
2,104
webtrekk-android-sdk-v5
MIT License
app/src/main/java/com/anangkur/mediku/util/CompressImageListener.kt
anangkur
236,449,731
false
null
package com.anangkur.mediku.util import java.io.File interface CompressImageListener { fun progress(isLoading: Boolean) fun success(data: File) fun error(errorMessage: String) }
2
Kotlin
1
4
4b4e184a5ea9368c0901262ce9899bad6c56fb87
191
Medi-Ku
MIT License
sample/src/main/java/com/github/terrakok/modo/sample/screens/dialogs/M3BottomSheet.kt
ikarenkov
336,628,876
false
{"Kotlin": 247285}
package com.github.terrakok.modo.sample.screens.dialogs import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ModalBottomSheet import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import com.github.terrakok.modo.DialogScreen import com.github.terrakok.modo.ExperimentalModoApi import com.github.terrakok.modo.LocalContainerScreen import com.github.terrakok.modo.ScreenKey import com.github.terrakok.modo.generateScreenKey import com.github.terrakok.modo.sample.screens.base.ButtonsScreenContent import com.github.terrakok.modo.stack.LocalStackNavigation import com.github.terrakok.modo.stack.StackScreen import com.github.terrakok.modo.stack.back import kotlinx.parcelize.Parcelize @Parcelize @OptIn(ExperimentalModoApi::class) class M3BottomSheet( private val screenIndex: Int, override val screenKey: ScreenKey = generateScreenKey() ) : DialogScreen { override fun provideDialogConfig(): DialogScreen.DialogConfig = DialogScreen.DialogConfig.Custom @OptIn(ExperimentalMaterial3Api::class) @Composable override fun Content(modifier: Modifier) { val stackScreen = LocalStackNavigation.current val sheetState = rememberModalBottomSheetState() ModalBottomSheet( onDismissRequest = { stackScreen.back() }, sheetState = sheetState, dragHandle = null ) { ButtonsScreenContent( screenIndex = screenIndex, screenName = "SampleDialog", state = rememberDialogsButtons(LocalContainerScreen.current as StackScreen, screenIndex), modifier = modifier .fillMaxSize() .align(Alignment.CenterHorizontally) // TODO: deal with A11Y and remove it from A11Y tree .clickable( enabled = false, interactionSource = remember { MutableInteractionSource() }, indication = null ) {} ) } } }
9
Kotlin
17
301
6dff8e7281e7a8a04bb19de997037192530f704a
2,489
Modo
The Unlicense
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/BrandAirtable.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.tabler.tabler.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Round import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup public val OutlineGroup.BrandAirtable: ImageVector get() { if (_brandAirtable != null) { return _brandAirtable!! } _brandAirtable = Builder(name = "BrandAirtable", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(3.0f, 10.0f) verticalLineToRelative(8.0f) lineToRelative(7.0f, -3.0f) verticalLineToRelative(-2.6f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(3.0f, 6.0f) lineToRelative(9.0f, 3.0f) lineToRelative(9.0f, -3.0f) lineToRelative(-9.0f, -3.0f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(14.0f, 12.3f) verticalLineToRelative(8.7f) lineToRelative(7.0f, -3.0f) verticalLineToRelative(-8.0f) close() } } .build() return _brandAirtable!! } private var _brandAirtable: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
2,592
compose-icon-collections
MIT License
app/src/main/java/com/example/workout/ui/stats/StatsViewModel.kt
kgit42
400,450,826
false
{"Kotlin": 197167}
package com.example.workout.ui.stats import android.app.Application import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.example.workout.db.AppDatabase import com.example.workout.db.Exercice import com.example.workout.db.Routine import com.example.workout.db.RoutineWorkoutStatsElement import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class StatsViewModel(app: Application) : AndroidViewModel(app) { //Referenz zur Datenbank val db = AppDatabase.getInstance(app.applicationContext) fun getAllRoutineWorkoutStatsElements(): LiveData<List<RoutineWorkoutStatsElement>> { return db.routineWorkoutStatsElementDao().getAll() } suspend fun createRoutineWorkoutStatsElement(routineWorkoutStatsElement: RoutineWorkoutStatsElement) { withContext(Dispatchers.IO) { db.routineWorkoutStatsElementDao().insert(routineWorkoutStatsElement) } } suspend fun deleteRoutineWorkoutStatsElement(id: Int) { return withContext(Dispatchers.IO) { db.routineWorkoutStatsElementDao().delete(id) } } }
0
Kotlin
0
0
8706e3743332189a9d2a131680673df196a28375
1,201
Workout
Apache License 2.0
Forge/src/main/kotlin/mod/master_bw3/hex_action_manifest/forge/ForgeHexActionManifest.kt
Master-Bw3
847,435,236
false
{"Kotlin": 12155, "Java": 2406}
package mod.master_bw3.hex_action_manifest.forge import dev.architectury.platform.forge.EventBuses import mod.master_bw3.hex_action_manifest.HexActionManifest import mod.master_bw3.hex_action_manifest.forge.datagen.HexActionManifestModels import mod.master_bw3.hex_action_manifest.forge.datagen.HexActionManifestRecipes import net.minecraft.data.DataProvider import net.minecraft.data.DataProvider.Factory import net.minecraft.data.PackOutput import net.minecraftforge.data.event.GatherDataEvent import net.minecraftforge.fml.common.Mod import thedarkcolour.kotlinforforge.forge.MOD_BUS /** * This is your loading entrypoint on forge, in case you need to initialize * something platform-specific. */ @Mod(HexActionManifest.MODID) class HexActionManifestForge { init { MOD_BUS.apply { EventBuses.registerModEventBus(HexActionManifest.MODID, this) addListener(ForgeHexActionManifestClient::init) addListener(::gatherData) } HexActionManifest.init() } private fun gatherData(event: GatherDataEvent) { event.apply { val efh = existingFileHelper addProvider(includeClient()) { HexActionManifestModels(it, efh) } addProvider(includeServer()) { HexActionManifestRecipes(it) } } } } fun <T : DataProvider> GatherDataEvent.addProvider(run: Boolean, factory: (PackOutput) -> T) = generator.addProvider(run, Factory { factory(it) })
0
Kotlin
0
0
af6b27af93f7688f701988850f3bb3812a3d954b
1,461
Hex-Action-Manifest
MIT License
app/src/main/java/com/example/kotlinglang/c_orientacaoObjeto/JohnBank.kt
johnnymeneses
527,025,619
false
{"Kotlin": 101138}
package c_orientacaoObjeto class JohnBank fun main() { println("Bem vindo ao JohnBank") }
0
Kotlin
0
0
81adfdad80400ece05a66d49dc7aeea7d107a68b
97
kotlin-lang
MIT License
addon/analytiks-timber/src/main/java/com/analytiks/addon/timber/TimberLocalClient.kt
aminekarimii
586,981,952
false
{"Kotlin": 42755}
package com.analytiks.addon.timber import android.content.Context import android.util.Log import com.analytiks.core.CoreAddon import com.analytiks.core.EventsExtension import com.analytiks.core.UserProfileExtension import com.analytiks.core.model.Param import com.analytiks.core.model.UserProperty import timber.log.Timber const val TAG = "TimberLocalClient" class TimberLocalClient : CoreAddon, EventsExtension, UserProfileExtension { override fun initialize(context: Context) { Timber.plant(Timber.DebugTree()) } override fun reset() { Timber.tag(TAG).log(Log.INFO, "Reset called") } override fun logEvent(name: String) { Timber.tag(TAG).log(Log.INFO, "Event: $name") } override fun logEvent(name: String, vararg properties: Param) { val logMessage = if (properties.isNotEmpty()) { val propertyStrings = properties.mapIndexed { index, param -> "${index + 1}. ${param.propertyName} : ${param.propertyValue}" }.joinToString("\n") "***** Event: $name -> props:\n$propertyStrings\n*****" } else { "***** Event: $name (No properties) *****" } Timber.tag(TAG).log(Log.INFO, logMessage) } override fun identify(userId: String) { Timber.tag(TAG).log(Log.INFO, "User has been identified by: $userId") } override fun setUserProperty(property: UserProperty) { Timber.tag(TAG).log(Log.INFO, "User property has been added: $property") } override fun setUserPropertyOnce(property: UserProperty) { Timber.tag(TAG).log(Log.INFO, "User property has been added once: $property") } }
6
Kotlin
3
40
9d56cef3241cdde48e0e109171069bda32990808
1,677
analytiks
Apache License 2.0
src/main/kotlin/github/mewgrammer/shopbuddy/security/model/Privilege.kt
Mewgrammer
503,052,371
false
{"Kotlin": 43249}
package github.mewgrammer.shopbuddy.security.model enum class Privilege() { READ, WRITE }
0
Kotlin
0
0
01f72fc46e7aaa358624b3ed8a3ab816a4982ba5
98
shopping-buddy
MIT License
app/src/main/java/com/dluvian/nozzle/ui/components/postCard/atoms/BorderedCard.kt
dluvian
645,936,540
false
{"Kotlin": 467095}
package com.dluvian.nozzle.ui.components.postCard.atoms import androidx.compose.foundation.border import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import com.dluvian.nozzle.ui.theme.spacing @Composable fun BorderedCard(modifier: Modifier = Modifier, content: @Composable () -> Unit) { Surface( modifier = modifier.border( width = spacing.tiny, color = Color.LightGray, shape = RoundedCornerShape(spacing.large) ) ) { content() } }
1
Kotlin
1
21
71dbc9c71ada3a5c79f5cd609ef0826f48625e87
677
Nozzle
MIT License
viewmodelevents/viewmodelevents-flow/src/main/kotlin/com/redmadrobot/viewmodelevents/ViewModelEvents.kt
RedMadRobot
306,830,691
false
{"Kotlin": 91019, "Shell": 4284}
package com.redmadrobot.viewmodelevents import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.* /** * ViewModel events implemented via flow to handle one-time events. * * It buffers events and emits them when you start to observe [ViewModelEvents]. * Can be used to show messages or errors to a user once. * @see Event */ public class ViewModelEvents { private val eventsFlow = MutableStateFlow<List<Event>>(emptyList()) /** Returns a flow of events. */ @OptIn(ExperimentalCoroutinesApi::class) public val flow: Flow<Event> get() = eventsFlow.flatMapConcat { consumeAll() } /** Offers the given [event] to be added to ViewModel events. */ public fun offerEvent(event: Event) { eventsFlow.update { it + event } } private fun consumeAll(): Flow<Event> = eventsFlow.getAndUpdate { emptyList() }.asFlow() }
5
Kotlin
3
29
90754335ae2733e70b69d312a06c2498a4261da2
891
gears-android
MIT License
inbox/src/androidTest/java/academy/compose/inbox/ui/EmailInboxTest.kt
roshanrai06
464,025,442
false
{"Kotlin": 789427}
/* * Copyright 2021 Compose Academy * * 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 academy.compose.inbox.ui import academy.compose.inbox.R import academy.compose.inbox.Tags.TAG_CONTENT import academy.compose.inbox.Tags.TAG_EMAIL import academy.compose.inbox.Tags.TAG_EMPTY import academy.compose.inbox.Tags.TAG_ERROR import academy.compose.inbox.Tags.TAG_PROGRESS import academy.compose.inbox.model.EmailFactory import academy.compose.inbox.model.InboxState import academy.compose.inbox.model.InboxStatus import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.test.ExperimentalTestApi import androidx.compose.ui.test.assert import androidx.compose.ui.test.assertCountEquals import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.hasTestTag import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onChildAt import androidx.compose.ui.test.onChildren import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performScrollTo import androidx.compose.ui.test.performTouchInput import androidx.compose.ui.test.swipeRight import androidx.test.platform.app.InstrumentationRegistry import org.junit.Rule import org.junit.Test @ExperimentalAnimationApi @ExperimentalMaterialApi class EmailInboxTest { @get:Rule val composeTestRule = createComposeRule() @Test fun Inbox_Title_Displayed() { val inboxState = InboxState(emails = EmailFactory.makeContentList()) composeTestRule.setContent { EmailInbox(inboxState = inboxState) { } } composeTestRule.onNodeWithText( InstrumentationRegistry.getInstrumentation().targetContext.getString( R.string.inbox_emails, inboxState.emails!!.count() ) ).assertIsDisplayed() } @Test fun Loading_State_Displayed() { composeTestRule.run { setContent { EmailInbox(inboxState = InboxState(status = InboxStatus.LOADING)) { } } onNodeWithTag(TAG_PROGRESS).assertIsDisplayed() onNodeWithTag(TAG_CONTENT).assertDoesNotExist() onNodeWithTag(TAG_ERROR).assertDoesNotExist() onNodeWithTag(TAG_EMPTY).assertDoesNotExist() } } @Test fun Empty_State_Displayed() { composeTestRule.run { setContent { EmailInbox( inboxState = InboxState(status = InboxStatus.EMPTY), handleEvent = { } ) } onNodeWithTag(TAG_PROGRESS).assertDoesNotExist() onNodeWithTag(TAG_CONTENT).assertDoesNotExist() onNodeWithTag(TAG_ERROR).assertDoesNotExist() onNodeWithTag(TAG_EMPTY).assertIsDisplayed() } } @Test fun Error_State_Displayed() { composeTestRule.run { setContent { EmailInbox( inboxState = InboxState(status = InboxStatus.ERROR), handleEvent = { } ) } onNodeWithTag(TAG_PROGRESS).assertDoesNotExist() onNodeWithTag(TAG_CONTENT).assertDoesNotExist() onNodeWithTag(TAG_ERROR).assertIsDisplayed() onNodeWithTag(TAG_EMPTY).assertDoesNotExist() } } @Test fun Content_State_Displayed() { composeTestRule.run { setContent { EmailInbox( inboxState = InboxState( status = InboxStatus.SUCCESS, emails = EmailFactory.makeContentList() ), handleEvent = { } ) } onNodeWithTag(TAG_PROGRESS).assertDoesNotExist() onNodeWithTag(TAG_CONTENT).assertIsDisplayed() onNodeWithTag(TAG_ERROR).assertDoesNotExist() onNodeWithTag(TAG_EMPTY).assertDoesNotExist() } } @Test fun Content_Displayed_After_Refresh() { val inboxState = mutableStateOf(InboxState(status = InboxStatus.EMPTY)) composeTestRule.setContent { EmailInbox(inboxState = inboxState.value) { inboxState.value = InboxState( status = InboxStatus.SUCCESS, emails = EmailFactory.makeContentList() ) } } composeTestRule.onNodeWithText( InstrumentationRegistry.getInstrumentation().targetContext .getString(R.string.label_check_again) ).performClick() composeTestRule.onNodeWithTag(TAG_CONTENT) .assertIsDisplayed() } @Test fun Empty_State_Hidden_After_Refresh() { val inboxState = mutableStateOf(InboxState(status = InboxStatus.EMPTY)) composeTestRule.setContent { EmailInbox(inboxState = inboxState.value) { inboxState.value = InboxState( status = InboxStatus.SUCCESS, emails = EmailFactory.makeContentList() ) } } composeTestRule.onNodeWithText( InstrumentationRegistry.getInstrumentation().targetContext .getString(R.string.label_check_again) ).performClick() composeTestRule.onNodeWithTag(TAG_EMPTY) .assertDoesNotExist() } @Test fun Content_Displayed_After_Retry() { val inboxState = mutableStateOf(InboxState(status = InboxStatus.ERROR)) composeTestRule.setContent { EmailInbox(inboxState = inboxState.value) { inboxState.value = InboxState( status = InboxStatus.SUCCESS, emails = EmailFactory.makeContentList() ) } } composeTestRule.onNodeWithText( InstrumentationRegistry.getInstrumentation().targetContext .getString(R.string.label_try_again) ).performClick() composeTestRule.onNodeWithTag(TAG_CONTENT) .assertIsDisplayed() } @Test fun Error_State_Hidden_After_Refresh() { val inboxState = mutableStateOf(InboxState(status = InboxStatus.ERROR)) composeTestRule.setContent { EmailInbox(inboxState = inboxState.value) { inboxState.value = InboxState( status = InboxStatus.SUCCESS, emails = EmailFactory.makeContentList() ) } } composeTestRule.onNodeWithText( InstrumentationRegistry.getInstrumentation().targetContext .getString(R.string.label_try_again) ).performClick() composeTestRule.onNodeWithTag(TAG_ERROR) .assertDoesNotExist() } @ExperimentalTestApi @Test fun Item_Dismissed_When_Swiped() { composeTestRule.setContent { Inbox() } val emails = EmailFactory.makeContentList() composeTestRule.onNodeWithTag(TAG_CONTENT) .onChildAt(0) .performTouchInput { swipeRight() } composeTestRule.onNodeWithTag(TAG_CONTENT) .onChildren() .assertCountEquals(emails.count() - 1) } @Test fun Remaining_Items_Displayed_When_Another_Dismissed() { composeTestRule.setContent { Inbox() } composeTestRule.onNodeWithTag(TAG_CONTENT) .onChildAt(0) .performTouchInput { swipeRight() } val emails = EmailFactory.makeContentList() emails.takeLast(emails.count() - 1).forEachIndexed { index, email -> composeTestRule .onNodeWithTag(TAG_CONTENT) .assertIsDisplayed() .onChildAt(index) .performScrollTo() .assert(hasTestTag(TAG_EMAIL + email.id)) } } }
0
Kotlin
0
0
5cc48810a94be4d92240d91ca7bf07a4c9344569
8,682
Compose_Acadmy
Apache License 2.0
app/src/main/java/com/drawiin/funfit/FunFitAndroidApp.kt
Drawiin
404,929,005
false
null
package com.drawiin.funfit import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class FunFitAndroidApp: Application() {}
1
Kotlin
0
0
62b6a87276bb517b43f8aa4c6e4f103aebf0e2a8
159
FunFit
MIT License
src/util/Utils.kt
scottschmitz
572,656,097
false
{"Kotlin": 169861}
import java.io.File /** * Reads lines from the given input txt file. */ fun readInput(name: String) = File("src", name) .readLines()
0
Kotlin
0
0
a1c193d47217d558bb11f934c808121f53087e36
140
advent_of_code
Apache License 2.0
app/src/main/java/com/prime/media/dialog/PlayingQueue.kt
iZakirSheikh
506,656,610
false
null
@file:Suppress("NOTHING_TO_INLINE") package com.prime.media.dialog import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.animateIntAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredSize import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.ContentAlpha import androidx.compose.material.Divider import androidx.compose.material.Icon import androidx.compose.material.LocalContentColor import androidx.compose.material.Surface import androidx.compose.material.TopAppBar import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Close import androidx.compose.material.icons.outlined.DragIndicator import androidx.compose.material.icons.outlined.Queue import androidx.compose.runtime.Composable import androidx.compose.runtime.ExperimentalComposeApi import androidx.compose.runtime.NonRestartableComposable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.draw.shadow import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.media3.common.MediaItem import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.rememberLottieComposition import com.prime.media.Material import com.prime.media.R import com.prime.media.core.ContentPadding import com.prime.media.caption2 import com.prime.media.outline import com.prime.media.core.util.key import com.primex.material2.BottomSheetDialog import com.primex.material2.Header import com.primex.material2.IconButton import com.primex.material2.Label import com.primex.material2.ListTile private const val TAG = "PlayingQueue" @OptIn(ExperimentalAnimationApi::class) @Composable fun Track( value: MediaItem, modifier: Modifier = Modifier, isPlaying: Boolean = false ) { val meta = value.mediaMetadata ListTile( centreVertically = true, modifier = modifier, // the leading image is rect in case isPlaying else circle. leading = { // change between rectangle and circle. val radius by animateIntAsState( targetValue = if (isPlaying) 15 else 40, animationSpec = tween(750) ) com.prime.media.core.compose.Image( meta.artworkUri, modifier = Modifier .padding(end = ContentPadding.medium) .shadow(5.dp, clip = true, shape = RoundedCornerShape(radius)) .border(2.dp, color = Color.White, RoundedCornerShape(radius)) .then(if (isPlaying) Modifier.height(60.dp).aspectRatio(1.5f) else Modifier.size(53.dp)) .animateContentSize(tween(750, delayMillis = 100)) ) }, text = { Label( text = meta.title.toString(), // style = Material.typography.body1, fontWeight = FontWeight.Bold, maxLines = 2 ) }, secondaryText = { Label( text = meta.subtitle.toString(), style = Material.typography.caption2 ) }, trailing = { // show drag indicator if (!isPlaying) { IconButton( onClick = { /*TODO*/ }, imageVector = Icons.Outlined.DragIndicator, contentDescription = null ) } // show playing bars. else { val composition by rememberLottieComposition( spec = LottieCompositionSpec.RawRes(R.raw.playback_indicator) ) LottieAnimation( composition = composition, iterations = Int.MAX_VALUE, modifier = Modifier .requiredSize(24.dp) .offset(x = -ContentPadding.medium) ) } } ) } @OptIn(ExperimentalFoundationApi::class) @Composable private fun Layout( resolver: PlayingQueue, onDismissRequest: () -> Unit, modifier: Modifier = Modifier, ) { val color = Material.colors.outline Column(modifier = modifier) { // top bar mimicking youtube app. TopAppBar( title = { Label(text = "Playing Queue") }, backgroundColor = Material.colors.surface, contentColor = Material.colors.onSurface, elevation = 0.dp, navigationIcon = { Icon( imageVector = Icons.Outlined.Queue, contentDescription = null, modifier = Modifier.padding(start = ContentPadding.normal) ) }, actions = { val shuffle = resolver.shuffle IconButton( onClick = { resolver.toggleShuffle() }, painter = painterResource(id = R.drawable.ic_shuffle), contentDescription = null, tint = Material.colors.onSurface.copy(if (shuffle) ContentAlpha.high else ContentAlpha.disabled), ) IconButton( onClick = onDismissRequest, imageVector = Icons.Outlined.Close, contentDescription = null ) }, // draw the capsule modifier = Modifier.drawWithContent { drawContent() // drawRoundRect(color, size = Size()) drawRoundRect( cornerRadius = CornerRadius(12f, 12f), color = color, topLeft = Offset(size.width / 2 - 12.dp.toPx(), 8.dp.toPx()), size = Size(25.dp.toPx(), 4.dp.toPx()) ) } ) Divider() val list by resolver.queue.collectAsState(initial = emptyList()) LazyColumn(contentPadding = PaddingValues(vertical = ContentPadding.medium)) { list.forEachIndexed { index, item -> // current playing track if (index == 0) { item(key = item.key) { Track( value = item, modifier = Modifier .animateItemPlacement() .padding(horizontal = ContentPadding.normal), isPlaying = true ) } return@forEachIndexed } if (index == 1) item(key = "up_next_header") { Header( text = "Up Next", modifier = Modifier .padding(ContentPadding.normal) .animateItemPlacement(), fontWeight = FontWeight.Bold, color = LocalContentColor.current ) } // other tracks. // FixMe: use key instead of mediaId item(key = item.key) { Track( value = item, modifier = Modifier .offset(y = -ContentPadding.medium) .clickable { resolver.playTrack(item.requestMetadata.mediaUri!!) } .animateItemPlacement() .padding(horizontal = ContentPadding.normal), ) } } } } } @OptIn(ExperimentalComposeApi::class, ExperimentalComposeUiApi::class) @Composable @NonRestartableComposable fun PlayingQueue( state: PlayingQueue, expanded: Boolean, onDismissRequest: () -> Unit ) { BottomSheetDialog(expanded = expanded, onDismissRequest = onDismissRequest) { Surface(shape = RoundedCornerShape(topStartPercent = 5, topEndPercent = 5)) { Layout( resolver = state, onDismissRequest ) } } }
15
Kotlin
0
31
693ab1a276c45016baac8f1075b5f3f0026714d2
9,356
Audiofy2
Apache License 2.0
mbmobilesdk/src/main/java/com/daimler/mbmobilesdk/biometric/auth/BiometricPromptAuthenticator.kt
rafalzawadzki
208,997,288
true
{"Kotlin": 1297852, "Groovy": 4489}
package com.daimler.mbmobilesdk.biometric.auth import android.os.Build import android.security.keystore.KeyGenParameterSpec import android.security.keystore.KeyProperties import android.util.Base64 import androidx.annotation.RequiresApi import androidx.biometric.BiometricPrompt import androidx.fragment.app.FragmentActivity import com.daimler.mbmobilesdk.biometric.biometricsPreconditionsError import com.daimler.mbmobilesdk.biometric.iv.IvProvider import com.daimler.mbmobilesdk.utils.postToMainThread import com.daimler.mbcommonkit.security.Crypto import com.daimler.mbcommonkit.security.Crypto.CryptoException import com.daimler.mbloggerkit.MBLoggerKit import java.io.IOException import java.nio.charset.Charset import java.security.* import java.security.cert.CertificateException import java.util.concurrent.Executors import javax.crypto.Cipher import javax.crypto.KeyGenerator import javax.crypto.NoSuchPaddingException import javax.crypto.SecretKey import javax.crypto.spec.IvParameterSpec @RequiresApi(Build.VERSION_CODES.M) internal class BiometricPromptAuthenticator( private val ivProvider: IvProvider, private val keyAlias: String ) : BiometricAuthenticator { private val keyStore: KeyStore by lazy { getAndroidKeyStore() } override fun startBiometricAuthentication( activity: FragmentActivity, dialogConfig: BiometricDialogConfig, cryptoCallback: BiometricCryptoCallback ): Boolean = startBiometricCryptoProcess(activity, dialogConfig, cryptoCallback, "", "", BiometricPurpose.AUTHENTICATE) override fun startBiometricEncryption( activity: FragmentActivity, dialogConfig: BiometricDialogConfig, cryptoCallback: BiometricCryptoCallback, tag: String, plainText: String ): Boolean = startBiometricCryptoProcess(activity, dialogConfig, cryptoCallback, tag, plainText, BiometricPurpose.ENCRYPT) override fun startBiometricDecryption( activity: FragmentActivity, dialogConfig: BiometricDialogConfig, cryptoCallback: BiometricCryptoCallback, tag: String, encryptedText: String ): Boolean = startBiometricCryptoProcess(activity, dialogConfig, cryptoCallback, tag, encryptedText, BiometricPurpose.DECRYPT) private fun startBiometricCryptoProcess( activity: FragmentActivity, config: BiometricDialogConfig, cryptoCallback: BiometricCryptoCallback, tag: String, text: String, purpose: BiometricPurpose ): Boolean { return try { if (biometricsPreconditionsError(activity) != null) return false removeFragmentIfAdded(activity) val callback = BiometricCallbackInternal(purpose, text, cryptoCallback) val cipher = initBiometricCipher(purpose, keyAlias, tag) val cryptoObject = BiometricPrompt.CryptoObject(cipher) val prompt = BiometricPrompt(activity, Executors.newSingleThreadExecutor(), callback) val info = BiometricPrompt.PromptInfo.Builder() .setTitle(config.title) .setSubtitle(config.subtitle) .setDescription(config.description) .setNegativeButtonText(config.negativeButtonText) .build() prompt.authenticate(info, cryptoObject) true } catch (e: SecurityException) { // when permission was not granted MBLoggerKit.e("Could not start fingerprint authentication.", throwable = e) false } catch (e: CryptoException) { // When any keystore operation failed; e.g. when the key was permanently invalidated // due to biometric changes on the device (new fingerprint registered/ deleted) MBLoggerKit.e("Could not start fingerprint authentication.", throwable = e) // We just delete the key here if it exists, since it won't be usable anymore. val deleted = deleteBiometricKey() MBLoggerKit.e("Key invalidated. Deleted = $deleted.") false } } override fun deleteBiometricKey(): Boolean = if (keyStore.containsAlias(keyAlias)) { keyStore.deleteEntry(keyAlias) ivProvider.deleteIvForAlias(keyAlias) true } else { false } /* This is just a workaround for now, since the helper fragment seems to be not cleared up. */ private fun removeFragmentIfAdded(activity: FragmentActivity) { activity.supportFragmentManager.apply { findFragmentByTag("FingerprintHelperFragment")?.let { beginTransaction() .remove(it) .commitNowAllowingStateLoss() } } } private fun encode(cipher: Cipher, text: String) = Base64.encodeToString(cipher.doFinal(text.toByteArray(Charset.defaultCharset())), Base64.DEFAULT) private fun decode(cipher: Cipher, encryptedText: String) = String(cipher.doFinal(Base64.decode(encryptedText.toByteArray(Charset.defaultCharset()), Base64.DEFAULT)), Charset.defaultCharset()) private fun loadFingerprintKey(alias: String): Key = if (keyStore.containsAlias(alias)) { keyStore.getKey(alias, null) } else { // safety delete remaining ivs ivProvider.deleteIvForAlias(alias) generateFingerprintKey(alias) } private fun generateFingerprintKey(alias: String): SecretKey { val parameterSpec = KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) .setBlockModes(BLOCK_MODE) .setUserAuthenticationRequired(true) .setEncryptionPaddings(ENCRYPTION_PADDING) .build() try { val keyGenerator = KeyGenerator.getInstance(ALGORITHM, ANDROID_KEYSTORE_TYPE) keyGenerator.init(parameterSpec) return keyGenerator.generateKey() } catch (e: NoSuchAlgorithmException) { throw CryptoException(e.localizedMessage, e) } catch (e: NoSuchProviderException) { throw CryptoException(e.localizedMessage, e) } catch (e: InvalidAlgorithmParameterException) { throw CryptoException(e.localizedMessage, e) } } private fun initBiometricCipher(purpose: BiometricPurpose, alias: String, tag: String): Cipher { val cipher: Cipher try { cipher = Cipher.getInstance(CIPHER_MODE) val key = loadFingerprintKey(alias) when (purpose) { BiometricPurpose.ENCRYPT -> { cipher.init(Cipher.ENCRYPT_MODE, key) ivProvider.saveIvForAlias(alias, tag, cipher.iv) } BiometricPurpose.DECRYPT -> { val currentIv = ivProvider.getIvForAlias(alias, tag) ?: throw IllegalStateException("No encryption was done using this alias yet.") cipher.init(Cipher.DECRYPT_MODE, loadFingerprintKey(alias), IvParameterSpec(currentIv)) } BiometricPurpose.AUTHENTICATE -> { cipher.init(Cipher.ENCRYPT_MODE, key) } } } catch (e: NoSuchAlgorithmException) { throw CryptoException(e.localizedMessage, e) } catch (e: NoSuchPaddingException) { throw CryptoException(e.localizedMessage, e) } catch (e: UnrecoverableKeyException) { throw CryptoException(e.localizedMessage, e) } catch (e: KeyStoreException) { throw CryptoException(e.localizedMessage, e) } catch (e: InvalidKeyException) { throw CryptoException(e.localizedMessage, e) } return cipher } private fun getAndroidKeyStore(): KeyStore { try { val androidKeyStore = KeyStore.getInstance(Crypto.ANDROID_KEY_STORE) androidKeyStore.load(null) return androidKeyStore } catch (ioe: IOException) { throw CryptoException("Failed to load AndroidKeyStore", ioe) } catch (nsa: NoSuchAlgorithmException) { throw CryptoException("Failed to load AndroidKeyStore", nsa) } catch (ce: CertificateException) { throw CryptoException("Failed to load AndroidKeyStore", ce) } catch (ke: KeyStoreException) { throw CryptoException("Failed to load AndroidKeyStore", ke) } } private inner class BiometricCallbackInternal( private val purpose: BiometricPurpose, private val text: String, private val callback: BiometricCryptoCallback ) : BiometricPrompt.AuthenticationCallback() { override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { super.onAuthenticationError(errorCode, errString) postToMainThread { callback.onAuthenticationError(errString.toString()) } } override fun onAuthenticationFailed() { super.onAuthenticationFailed() postToMainThread { callback.onAuthenticationFailed() } } override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { super.onAuthenticationSucceeded(result) postToMainThread { callback.onAuthenticationSucceeded() } result.cryptoObject?.cipher?.let { when (purpose) { BiometricPurpose.ENCRYPT -> { val encrypted = encode(it, text) postToMainThread { callback.onEncryptionSucceeded(encrypted) } } BiometricPurpose.DECRYPT -> { val decrypted = decode(it, text) postToMainThread { callback.onDecryptionSucceeded(decrypted) } } BiometricPurpose.AUTHENTICATE -> Unit } } // TODO determine if it can happen that the Cipher object is null } } private companion object { private const val ANDROID_KEYSTORE_TYPE = "AndroidKeyStore" private const val ALGORITHM = KeyProperties.KEY_ALGORITHM_AES private const val BLOCK_MODE = KeyProperties.BLOCK_MODE_CBC private const val ENCRYPTION_PADDING = KeyProperties.ENCRYPTION_PADDING_PKCS7 private const val CIPHER_MODE = "$ALGORITHM/$BLOCK_MODE/$ENCRYPTION_PADDING" } }
0
null
0
0
1a924f70fbde5d731cdfde275e724e6343ee6ebe
10,622
MBSDK-Mobile-Android
MIT License
src/main/kotlin/com/ipmus/entities/Container.kt
pinkjersey
98,462,736
false
null
package com.ipmus.entities import jetbrains.exodus.entitystore.Entity import jetbrains.exodus.entitystore.PersistentEntityId import jetbrains.exodus.entitystore.PersistentEntityStoreImpl import jetbrains.exodus.entitystore.StoreTransaction /** * This entity represents shipment types. */ data class Container(override val entityID: String, val shipmentID: String, val containerName: String, val containerType: String) : com.ipmus.entities.Entity { constructor (entity: Entity) : this( entityID = entity.toIdString(), shipmentID = entity.getLink("shipment")!!.toIdString(), containerName = entity.getProperty("containerName") as String, containerType = entity.getProperty("containerType") as String ) override fun create(txn: StoreTransaction, store: PersistentEntityStoreImpl) : String { val newContainer = txn.newEntity(type) newContainer.setProperty("containerName", containerName) newContainer.setProperty("containerType", containerType) val shipmentEntityId = PersistentEntityId.toEntityId(shipmentID, store) val shipmentEntity = txn.getEntity(shipmentEntityId) newContainer.setLink("shipment", shipmentEntity) shipmentEntity.addLink("containers", newContainer) return newContainer.toIdString() } override fun update(txn: StoreTransaction, store: PersistentEntityStoreImpl): String { val entityID = PersistentEntityId.toEntityId(this.entityID, store) val container = txn.getEntity(entityID) container.setProperty("containerType", containerType) return container.toIdString() } companion object { val type = "Container" } }
1
Kotlin
0
0
2f33129de9d8edbbe2f1cbc1c537955a83301a49
1,799
mtlshipback
MIT License
lib-base/src/main/java/dev/eliseo/lib_base/view/BaseViewModel.kt
eliseo-juan
257,232,169
false
null
package dev.eliseo.lib_base.view import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ReceiveChannel abstract class BaseViewModel<VS, VE> : ViewModel() { private val _viewState = MutableLiveData<VS>() val viewState: LiveData<VS> get() = _viewState private val _viewChannel = Channel<VE>() val viewChannel: ReceiveChannel<VE> get() = _viewChannel protected fun updateViewState(update: VS?.() -> VS) { val newState = update(_viewState.value) _viewState.value = newState } protected suspend fun sendViewEvent(viewEvent: VE) { _viewChannel.send(viewEvent) } }
0
Kotlin
0
1
8652bef6eda8762285156653cb6a0c09f309c20f
771
EliseoCV
MIT License
transforms/src/main/java/com/tencent/lucky/transforms/base/BaseFilter.kt
KaelMa
772,638,637
false
{"Kotlin": 291732, "Shell": 127}
package com.tencent.lucky.transforms.base /** * Copyright (C), 2019-2020, 腾讯科技(上海)有限公司 * FileName: BaseFilter * Author: kaelma * Date: 2020/4/13 7:17 PM * Description: 渲染filter */ interface BaseFilter { /** * init filter, must be called from gl thread */ fun init() /** * on output size changed * @param width * @param height */ fun onOutputSizeChanged(width: Int, height: Int) {} /** * draw * @param inputTexName input texture name * @return need flip */ fun draw(inputTexName: Int): Boolean /** * destroy gl resource */ fun destroy() }
0
Kotlin
0
0
a317946964d1fe5a329a84e02554e58f7acfc72d
640
Clover
MIT License
app/src/main/java/com/leonm/voiceversa/ReceiveIntentActivity.kt
Leonm99
752,048,291
false
{"Kotlin": 63096}
package com.leonm.voiceversa import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper import java.io.File import java.io.FileOutputStream import java.io.InputStream class ReceiveIntentActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) handleIntent(intent) } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) handleIntent(intent) } private fun handleIntent(intent: Intent?) { if (intent?.action == Intent.ACTION_SEND && (intent.type?.startsWith("audio/") == true || intent.type?.startsWith("video/") == true)) { val audioUri: Uri? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { intent.getParcelableExtra(Intent.EXTRA_STREAM, Uri::class.java) } else { @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_STREAM) } if (audioUri != null) { val audioFile = saveToCache(audioUri) if (audioFile != null) { Handler(Looper.getMainLooper()).postDelayed({ startFloatingService("TRANSCRIBE", audioFile.absolutePath) }, 500) } } } else if (intent?.action == Intent.ACTION_SEND && (intent.type?.startsWith("text/") == true)){ val link = intent.extras?.getString(Intent.EXTRA_TEXT) println("intent data: $link") Handler(Looper.getMainLooper()).postDelayed({ startFloatingService("DOWNLOAD", link!!) }, 500) } finish() } private fun saveToCache(uri: Uri): File? { return try { val inputStream: InputStream? = contentResolver.openInputStream(uri) val cacheDirectory: File? = cacheDir if (inputStream != null && cacheDirectory != null) { val file = File(cacheDirectory, "shared_audio_file.${getFileExtension(uri)}") inputStream.use { input -> FileOutputStream(file).use { output -> input.copyTo(output) } } file } else { null } } catch (e: Exception) { // Handle the exception in a more meaningful way, e.g. log an error message null } } private fun getFileExtension(uri: Uri): String { val resolver = contentResolver val mimeTypeMap = android.webkit.MimeTypeMap.getSingleton() return mimeTypeMap.getExtensionFromMimeType(resolver.getType(uri)) ?: "" } private fun startFloatingService( command: String = "", path: String = "" ) { val intent = Intent(this, FloatingService::class.java) if (command.isNotBlank()) { intent.putExtra(INTENT_COMMAND, command) } if (path.isNotBlank()) { intent.putExtra("PATH", path) } startForegroundService(intent) } }
0
Kotlin
0
0
4a150bd39697b34d586a8ec99fb984a0b09c7077
3,243
VoiceVersa
MIT License
edfapaygw/src/main/java/com/expresspay/sdk/model/response/creditvoid/ExpresspayCreditvoidSuccess.kt
edfapay
686,729,586
false
{"Kotlin": 420429, "Java": 48881}
/* * Property of EdfaPg (https://edfapay.com). */ package com.edfapaygw.sdk.model.response.creditvoid import androidx.annotation.NonNull import androidx.annotation.Nullable import com.edfapaygw.sdk.model.api.EdfaPgAction import com.edfapaygw.sdk.model.api.EdfaPgResult import com.edfapaygw.sdk.model.api.EdfaPgStatus import com.edfapaygw.sdk.model.response.base.result.IEdfaPgResult import com.google.gson.annotations.SerializedName import java.io.Serializable /** * The CREDITVOID success result of the [EdfaPgCreditvoidResult]. * @see EdfaPgCreditvoidResponse */ data class EdfaPgCreditvoidSuccess( @NonNull @SerializedName("action") override val action: EdfaPgAction, @NonNull @SerializedName("result") override val result: EdfaPgResult, @Nullable @SerializedName("status") override val status: EdfaPgStatus, @NonNull @SerializedName("order_id") override val orderId: String, @NonNull @SerializedName("trans_id") override val transactionId: String ) : IEdfaPgResult, Serializable
0
Kotlin
0
0
01b3bac022fb70e43823937a6038dbb2df2e13c1
1,051
edfa-pg-android-sdk-code
MIT License
src/main/kotlin/io/github/relvl/appliedequivalence/network/AbstractPacket.kt
Relvl
570,287,920
false
{"Kotlin": 40928}
package io.github.relvl.appliedequivalence.network import io.github.relvl.appliedequivalence.AppliedEquivalence import io.github.relvl.appliedequivalence.network.impl.PckInitializeClient import io.netty.buffer.Unpooled import net.fabricmc.api.EnvType import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking import net.fabricmc.fabric.api.networking.v1.PacketSender import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking import net.minecraft.client.Minecraft import net.minecraft.client.multiplayer.ClientPacketListener import net.minecraft.network.FriendlyByteBuf import net.minecraft.resources.ResourceLocation import net.minecraft.server.MinecraftServer import net.minecraft.server.level.ServerPlayer import net.minecraft.server.network.ServerGamePacketListenerImpl import kotlin.reflect.KClass abstract class AbstractPacket { protected val id = PacketLookup.of(this::class) protected var buff: FriendlyByteBuf constructor() { buff = FriendlyByteBuf(Unpooled.buffer()) buff.writeInt(id?.ordinal ?: -1) } constructor(buff: FriendlyByteBuf) { this.buff = buff } private fun prepareWrite() { val size = buff.readableBytes() buff.capacity(size) if (size > 2 * 1024 * 1024) { throw IllegalArgumentException( "Wrong packet size: $size byte(s), Class: ${this::class.simpleName}!" ) } } fun sendToServer() { prepareWrite() ClientPlayNetworking.send(CHANNEL_ID, buff) } fun sentToClient(player: ServerPlayer) { prepareWrite() ServerPlayNetworking.send(player, CHANNEL_ID, buff) } enum class PacketLookup(private val clazz: KClass<out AbstractPacket>, val constructor: (FriendlyByteBuf) -> AbstractPacket, val side: EnvType) { INIT_CLIENT(PckInitializeClient::class, { buf -> PckInitializeClient(buf) }, EnvType.SERVER); companion object { private val reverse = values().associateBy { it.clazz } fun of(id: Int) = values()[id] fun of(id: KClass<out AbstractPacket>) = reverse[id] } } companion object { val CHANNEL_ID = ResourceLocation("${AppliedEquivalence.MOD_ID}:networking") val PROTOCOL = PacketLookup.values().joinToString("_") { it.name }.hashCode() fun onServerPacket(client: Minecraft, handler: ClientPacketListener, buff: FriendlyByteBuf, responseSender: PacketSender) { val packetId = buff.readInt() val packet = PacketLookup.of(packetId) packet.constructor(buff) } fun onClientPacket(server: MinecraftServer, player: ServerPlayer, handler: ServerGamePacketListenerImpl, buff: FriendlyByteBuf, responseSender: PacketSender) { val packetId = buff.readInt() val packet = PacketLookup.of(packetId) packet.constructor(buff) } } }
0
Kotlin
0
0
f8b8d26f4c901109df0071428e25c736f488633d
2,942
applied-equivalence
MIT License
app/src/main/java/dev/olog/fortnightly/core/Article.kt
ologe
216,835,412
false
null
package dev.olog.fortnightly.core data class Article( val id: Long, val title: String, val summary: String, val section: String, val subSection: String, val url: String, val image: String )
0
Kotlin
4
14
b29f0aa845ee41b81bc01661a9ca739c6e940cda
218
fortnightly
MIT License
zeta-common/zeta-common-base/src/main/kotlin/com/zetaframework/base/controller/extra/NoPageQueryController.kt
1783cwf
786,329,278
false
{"Kotlin": 447567, "Dockerfile": 607, "Lua": 347}
package com.zetaframework.base.controller.extra import com.mybatisflex.core.query.QueryWrapper import com.zetaframework.base.controller.BaseController import com.zetaframework.log.annotation.SysLog import com.zetaframework.model.result.ApiResult import com.zetaframework.satoken.annotation.PreCheckPermission import com.zetaframework.utils.MapstructUtils import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestBody /** * 没有分页查询方法的QueryController * * @param <Id> 主键字段类型 * @param <BaseEntity> 实体 * @param <QueryParam> 分页参数 * @author gcc */ interface NoPageQueryController<Entity, QueryParam> : BaseController<Entity> { /** * 批量查询 * * @param param 批量查询参数 * @return ApiResult<List<BaseEntity>> */ @PreCheckPermission(value = ["{}:view"]) @SysLog(response = false) @PostMapping("/query") fun list( @RequestBody param: QueryParam, ): ApiResult<MutableList<Entity>> { return success(handlerBatchQuery(param)) } /** * 自定义批量查询 * * @param param 批量查询参数 * @return MutableList<BaseEntity> */ fun handlerBatchQuery(param: QueryParam): MutableList<Entity> { val entity = MapstructUtils.convert(param, getEntityClass()) // 批量查询 val list = getBaseService().list(QueryWrapper.create(entity)) // 处理批量查询数据 handlerBatchData(list) return list } /** * 处理批量查询数据 * @param list 实体列表 */ fun handlerBatchData(list: MutableList<Entity>) { } /** * 单体查询 * @param id Id 主键 * @return ApiResult<BaseEntity?> */ @PreCheckPermission(value = ["{}:view"]) @SysLog @GetMapping("/{id}") fun get( @PathVariable("id")id: Long, ): ApiResult<Entity?> { val entity = getBaseService().getById(id) // 处理单体查询数据 handlerGetData(entity) return success(entity) } /** * 处理单体查询数据 * @param entity 实体对象 */ fun handlerGetData(entity: Entity?) { } }
0
Kotlin
0
6
1a564f4c61fa361c3ee339696024cd1f88246fc8
2,185
zeta-kotlin-flex
MIT License
app/src/main/java/com/mikhailgrigorev/quickpass/PasswordAdapter.kt
grigorevmp
268,231,866
false
null
package com.mikhailgrigorev.quickpass import android.annotation.SuppressLint import android.content.Context import android.util.DisplayMetrics import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.google.android.material.chip.Chip import com.mikhailgrigorev.quickpass.databinding.PassFragmentBinding class PasswordAdapter( private val items: ArrayList<Pair<String, String>>, private val quality: ArrayList<String>, private val tags: ArrayList<String>, private val group: ArrayList<String>, private val desc: ArrayList<String>, private val useAnalyze: String?, private val cardRadius: String?, private val metrics: DisplayMetrics?, val context: Context, val clickListener: (Int) -> Unit, val longClickListener: (Int, View) -> Unit, val tagsClickListener: (String) -> Unit, ): RecyclerView.Adapter<ViewHolder>() { // Gets the number of animals in the list override fun getItemCount(): Int { return items.size } override fun getItemViewType(position: Int): Int { return position } // Inflates the item views override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = PassFragmentBinding.inflate(LayoutInflater.from(context), parent, false) return ViewHolder(binding) } // Binds each animal in the ArrayList to a view @SuppressLint("SetTextI18n", "ClickableViewAccessibility") override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.passText.text = items[position].first holder.chip.visibility = View.GONE if(items[position].second != "0"){ val chip = Chip(holder.group.context) chip.text= "2FA" chip.isClickable = false chip.textSize = 12F chip.setOnClickListener { tagsClickListener("2FA") } holder.group.addView(chip) } if(desc[position]!="") holder.passDesc.visibility = View.VISIBLE holder.passDesc.text = desc[position] if(group[position] == "#favorite"){ holder.favorite.visibility = View.VISIBLE } if(tags[position] != "") tags[position] .split("\\s".toRegex()).forEach { item -> val chip = Chip(holder.group.context) chip.text= item chip.isClickable = true chip.textSize = 12F chip.setOnClickListener { tagsClickListener(item) } holder.group.addView(chip) } when { quality[position] == "1" -> { holder.marker.setImageResource(R.drawable.circle_positive_fill) //holder.passFrag.setBackgroundResource(R.drawable.gradient_pos) } quality[position] == "2" -> { holder.marker.setImageResource(R.drawable.circle_negative_fill) //holder.passFrag.setBackgroundResource(R.drawable.gradient_neg) } quality[position] == "3" -> { holder.marker.setImageResource(R.drawable.circle_improvement_fill) //holder.passFrag.setBackgroundResource(R.drawable.gradient_med) } quality[position] == "4" -> { holder.credit.visibility = View.VISIBLE holder.marker.visibility = View.GONE } quality[position] == "5" -> { holder.creditNeg.visibility = View.VISIBLE holder.marker.visibility = View.GONE } quality[position] == "6" -> { holder.lock.visibility = View.VISIBLE holder.marker.visibility = View.GONE } } holder.clickableView.setOnClickListener { clickListener(position) } holder.clickableView.setOnLongClickListener { longClickListener(position, it) return@setOnLongClickListener (true) } if (useAnalyze != null) if (useAnalyze != "none"){ holder.marker.visibility = View.GONE holder.credit.visibility = View.GONE holder.creditNeg.visibility = View.GONE } if(cardRadius != null) if(cardRadius != "none") { holder.clickableView.radius = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, cardRadius.toFloat(), metrics ) } } } class ViewHolder(binding: PassFragmentBinding) : RecyclerView.ViewHolder(binding.root) { val passText = binding.listTitle val passDesc = binding.listDesc val chip = binding.chip // // val tags = view.tags!! val favorite = binding.favorite val clickableView = binding.clickableView val marker = binding.marker val group = binding.group val credit = binding.credit val creditNeg = binding.credit2 val lock = binding.lock }
1
Kotlin
0
5
d02277bd3b294cd8d40678d12a7ca5e81d931ec2
5,187
QuickPass-Mobile-Password-manager
MIT License
tabby-fp/src/jvmTest/kotlin/com/sksamuel/tabby/results/OnSuccessTest.kt
sksamuel
280,509,527
false
null
package com.sksamuel.tabby.results import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.booleans.shouldBeFalse import io.kotest.matchers.booleans.shouldBeTrue class OnSuccessTest : FunSpec() { init { test("onSuccessIfNotNull with non null") { val name: String? = "sam" var fired = false Result.success(name).onSuccessIfNotNull { fired = true } fired.shouldBeTrue() } test("onSuccessIfNotNull with null") { val name: String? = null var fired = false Result.success(name).onSuccessIfNotNull { fired = true } fired.shouldBeFalse() } } }
0
Kotlin
2
6
fb0a7f2a2c279acabfe7897b97093a558eaf1a5d
654
tabby
Apache License 2.0
site-new/testsuites/testsuite-kotlin/src/test/kotlin/docs/web5/build/decentralizedidentifiers/HowToReuseDidTest.kt
TBD54566975
482,770,478
false
{"JavaScript": 792696, "MDX": 566934, "Kotlin": 362598, "TypeScript": 265524, "Swift": 128240, "CSS": 101133, "Shell": 1474, "Dockerfile": 919, "Rust": 756}
package website.tbd.developer.site.docs.web5.build.decentralizedidentifiers; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Assertions.* import web5.sdk.dids.methods.dht.CreateDidDhtOptions import web5.sdk.crypto.InMemoryKeyManager // :prepend-start: exportDidKt import web5.sdk.dids.methods.jwk.DidJwk import web5.sdk.dids.methods.dht.DidDht import web5.sdk.dids.did.BearerDid // :prepend-end: /** * Tests backing the Import a DID Guide */ internal class HowToImportDidTest { @Test fun `export DID`() { val keyManager = InMemoryKeyManager() val didDht = DidDht.create(keyManager, CreateDidDhtOptions(publish = true)) val didJwk = DidJwk.create(keyManager) // :snippet-start: exportDidKt // export did:dht DID val portableDhtDid = didDht.export() // export did:jwk DID val portableJwkDid = didJwk.export() // :snippet-end: assertEquals(portableDhtDid.document.id, didDht.uri, "PortableDid DHT should be the same as DID uri") assertEquals(portableJwkDid.document.id, didJwk.uri, "PortableDid JWK should be the same as DID uri") } @Test fun `import DID`() { val keyManager = InMemoryKeyManager() val didDht = DidDht.create(keyManager, CreateDidDhtOptions(publish = true)) val didJwk = DidJwk.create(keyManager) val portableDhtDid = didDht.export() val portableJwkDid = didJwk.export() // :snippet-start: importDidKt // import did:dht DID val bearerDidDht = BearerDid.import(portableDhtDid) // import did:jwk DID val bearerDidJwk = BearerDid.import(portableJwkDid) // :snippet-end: assertEquals(portableDhtDid.document.id, bearerDidDht.uri, "PortableDid DHT should be the same as Bearer DID uri") assertEquals(portableJwkDid.document.id, bearerDidJwk.uri, "PortableDid JWK should be the same as Bearer DID uri") } }
137
JavaScript
103
50
cfc3d93cdd4b44bbe7e1f2adaede9629b86f66db
1,850
developer.tbd.website
Apache License 2.0
app/src/main/java/com/example/studenchat/conversation/domain/CreateConversationUseCase.kt
mourchidimfoumby
726,650,487
false
{"Kotlin": 86261}
package com.example.studenchat.conversation.domain import com.example.studenchat.conversation.data.Conversation import com.example.studenchat.conversation.data.ConversationRepositoryImpl import com.example.studenchat.conversation.data.UserConversationRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class CreateConversationUseCase ( private val userConversationRepository: UserConversationRepository, private val conversationRepositoryImpl: ConversationRepositoryImpl ) { suspend operator fun invoke(conversation: Conversation) { withContext(Dispatchers.IO) { userConversationRepository.createConversation(conversation) conversationRepositoryImpl.createConversation(conversation) } } }
10
Kotlin
0
0
8848e2ff856a50eb63b3c0f1654e1a03b79b49f4
782
studentchat
Apache License 2.0
src/test/kotlin/tech/simter/kotlin/serialization/serializer/javatime/iso/IsoMonthDaySerializerTest.kt
Honglang123
276,298,678
true
{"Kotlin": 84571}
package tech.simter.kotlin.serialization.serializer.javatime.iso import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonConfiguration.Companion.Stable import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import java.time.MonthDay /** * Test [IsoMonthDaySerializer] * * @author RJ */ class IsoMonthDaySerializerTest { private val json = Json(Stable.copy(encodeDefaults = false)) @Serializable data class Bean( val ps: List<@Serializable(with = IsoMonthDaySerializer::class) MonthDay>, @Serializable(with = IsoMonthDaySerializer::class) val p1: MonthDay, @Serializable(with = IsoMonthDaySerializer::class) val p2: MonthDay?, @Serializable(with = IsoMonthDaySerializer::class) val p3: MonthDay? = null ) @Test fun test() { val md = MonthDay.of(1, 31) val str = """{"ps":["01-31"],"p1":"01-31","p2":null}""" val bean = Bean(ps = listOf(md), p1 = md, p2 = null) assertThat(json.parse(Bean.serializer(), str)).isEqualTo(bean) assertThat(json.stringify(Bean.serializer(), bean)).isEqualTo(str) } }
0
null
0
0
0b03bd5691027f9586ad96e0bc0462f217e2bc66
1,155
simter-kotlin
MIT License
adoptium-models-parent/adoptium-api-v3-models/src/main/kotlin/net/adoptium/api/v3/models/DockerDownloadStats.kt
adoptium
349,432,712
false
null
package net.adoptium.api.v3.models class DockerDownloadStats( val total_downloads: Long, val downloads: Map<String, Long>, val total_daily_downloads: Long, val daily_downloads: Map<String, Long> )
19
Kotlin
17
9
ddb39b5f7a71236694fc9df44e1bf3a888ba1fbc
214
api.adoptium.net
Apache License 2.0
src/main/kotlin/me/fzzyhmstrs/amethyst_imbuement/compat/ModCompatHelper.kt
fzzyhmstrs
461,338,617
false
{"Kotlin": 1716805, "Java": 105566}
package me.fzzyhmstrs.amethyst_imbuement.compat import dev.emi.emi.api.EmiApi import me.fzzyhmstrs.amethyst_imbuement.compat.emi.EmiClientPlugin import me.fzzyhmstrs.amethyst_imbuement.compat.patchouli.PatchouliCompat import me.fzzyhmstrs.amethyst_imbuement.screen.ImbuingTableScreen import me.fzzyhmstrs.fzzy_core.coding_util.AcText import net.fabricmc.loader.api.FabricLoader import net.minecraft.client.MinecraftClient import net.minecraft.server.network.ServerPlayerEntity import net.minecraft.util.Identifier object ModCompatHelper { private val patchouliLoaded by lazy { FabricLoader.getInstance().isModLoaded("patchouli") } private val viewerHierarchy: Map<String, Int> = mapOf( "emi" to 1, "roughlyenoughitems" to 2, "jei" to 3 ) fun openBookGui(playerEntity: ServerPlayerEntity, identifier: Identifier){ if (patchouliLoaded) PatchouliCompat.openBookGui(playerEntity, identifier) } fun registerPage(){ if (patchouliLoaded) PatchouliCompat.registerPage() } fun isValidHandlerOffset(offset: Int): Boolean { return viewerHierarchy.values.contains(offset) } fun getScreenHandlerOffset(): Int{ for (chk in viewerHierarchy){ if(FabricLoader.getInstance().isModLoaded(chk.key)){ return chk.value } } return 0 } fun runHandlerViewer(offset: Int){ if (offset == 0){ val oldScreen = MinecraftClient.getInstance().currentScreen if (oldScreen is ImbuingTableScreen){ MinecraftClient.getInstance().player?.sendMessage(AcText.literal("Recipe Book currently down for maintenance")) //MinecraftClient.getInstance().setScreen(ImbuingRecipeBookScreen(oldScreen)) } } if (offset == 1){ EmiApi.displayRecipeCategory(EmiClientPlugin.IMBUING_CATEGORY) } } fun isViewerSuperseded(viewer: String): Boolean{ val ranking = viewerHierarchy[viewer]?:return true for (chk in viewerHierarchy){ if (chk.key != viewer && chk.value < ranking && FabricLoader.getInstance().isModLoaded(chk.key)) return true } return false } }
10
Kotlin
8
4
ee7b940bcbdd91f5be02c36ab582d47c5adc6897
2,274
ai
MIT License
app/src/main/java/com/ck/dev/tiptap/data/AppDatabase.kt
chandankumar22
384,897,101
false
{"Kotlin": 263479}
package com.ck.dev.tiptap.data import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.ck.dev.tiptap.data.dao.GamesDao import com.ck.dev.tiptap.data.entity.BestScores import com.ck.dev.tiptap.data.entity.Games @Database(entities = [Games::class,BestScores::class], version = 1) @TypeConverters(Converters::class) abstract class AppDatabase :RoomDatabase() { abstract fun gamesDao(): GamesDao }
0
Kotlin
0
0
2940c3253abb8acfded68ed07d883c40b87ce408
455
brain-rush-game
Apache License 2.0
src/test/kotlin/org/ionproject/integration/domain/timetable/ISELTimetableJobFormatCheckerTest.kt
i-on-project
243,606,271
false
null
package org.ionproject.integration.domain.timetable import org.ionproject.integration.infrastructure.exception.FormatCheckException import org.ionproject.integration.domain.timetable.dto.RawTimetableData import org.ionproject.integration.infrastructure.CompositeException import org.ionproject.integration.infrastructure.orThrow import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows internal class ISELTimetableJobFormatCheckerTest { private val validTimeTableJson = "[ { \"extraction_method\": \"lattice\", \"top\": 113.945274, \"left\": 53.875286, \"width\": 489.77463, \"height\": 480.44003, \"right\": 543.6499, \"bottom\": 594.3853, \"data\": [ [ { \"top\": 113.945274, \"left\": 124.572914, \"width\": 69.84507, \"height\": 15.439293, \"text\": \"Segunda\" }, { \"top\": 113.945274, \"left\": 194.41798, \"width\": 69.87288, \"height\": 15.439293, \"text\": \"Terça\" }, { \"top\": 113.945274, \"left\": 264.29086, \"width\": 69.8483, \"height\": 15.439293, \"text\": \"Quarta\" }, { \"top\": 113.945274, \"left\": 334.13916, \"width\": 69.84784, \"height\": 15.439293, \"text\": \"Quinta\" }, { \"top\": 113.945274, \"left\": 403.987, \"width\": 69.88223, \"height\": 15.439293, \"text\": \"Sexta\" }, { \"top\": 113.945274, \"left\": 473.86923, \"width\": 69.78067, \"height\": 15.439293, \"text\": \"Sábado\" } ], [ { \"top\": 129.38457, \"left\": 54.97015, \"width\": 69.60277, \"height\": 15.475281, \"text\": \"8.00 - 8.30\" }, { \"top\": 129.38457, \"left\": 124.572914, \"width\": 69.84507, \"height\": 15.475281, \"text\": \"\" }, { \"top\": 129.38457, \"left\": 194.41798, \"width\": 69.87288, \"height\": 15.475281, \"text\": \"\" }, { \"top\": 129.38457, \"left\": 264.29086, \"width\": 69.8483, \"height\": 15.475281, \"text\": \"\" }, { \"top\": 129.38457, \"left\": 334.13916, \"width\": 69.84784, \"height\": 15.475281, \"text\": \"\" }, { \"top\": 129.38457, \"left\": 403.987, \"width\": 69.88223, \"height\": 15.475281, \"text\": \"\" } ], [ { \"top\": 144.85985, \"left\": 54.97015, \"width\": 69.60277, \"height\": 15.480118, \"text\": \"8.30 - 9.00\" }, { \"top\": 144.85985, \"left\": 124.572914, \"width\": 69.84507, \"height\": 15.480118, \"text\": \"\" }, { \"top\": 144.85985, \"left\": 194.41798, \"width\": 69.87288, \"height\": 15.480118, \"text\": \"\" }, { \"top\": 144.85985, \"left\": 264.29086, \"width\": 69.8483, \"height\": 15.480118, \"text\": \"\" }, { \"top\": 144.85985, \"left\": 334.13916, \"width\": 69.84784, \"height\": 15.480118, \"text\": \"\" }, { \"top\": 144.85985, \"left\": 403.987, \"width\": 69.88223, \"height\": 15.480118, \"text\": \"\" } ], [ { \"top\": 160.33997, \"left\": 54.97015, \"width\": 69.60277, \"height\": 15.480331, \"text\": \"9.00 - 9.30\" }, { \"top\": 160.33997, \"left\": 124.572914, \"width\": 69.84507, \"height\": 15.480331, \"text\": \"\" }, { \"top\": 160.33997, \"left\": 194.41798, \"width\": 69.87288, \"height\": 15.480331, \"text\": \"\" }, { \"top\": 160.33997, \"left\": 264.29086, \"width\": 69.8483, \"height\": 15.480331, \"text\": \"\" }, { \"top\": 160.33997, \"left\": 334.13916, \"width\": 69.84784, \"height\": 15.480331, \"text\": \"\" }, { \"top\": 160.33997, \"left\": 403.987, \"width\": 69.88223, \"height\": 15.480331, \"text\": \"\" } ] ] }, { \"extraction_method\": \"lattice\", \"top\": 606.47534, \"left\": 53.875286, \"width\": 479.09586, \"height\": 109.97766, \"right\": 532.9711, \"bottom\": 716.453, \"data\": [ [ { \"top\": 606.47534, \"left\": 53.875286, \"width\": 52.82519, \"height\": 10.875671, \"text\": \"ALGA[I] (T)\" }, { \"top\": 606.47534, \"left\": 106.70048, \"width\": 181.70715, \"height\": 10.875671, \"text\": \"<NAME>\" }, { \"top\": 606.47534, \"left\": 288.40762, \"width\": 122.303314, \"height\": 10.875671, \"text\": \"\" }, { \"top\": 606.47534, \"left\": 410.71094, \"width\": 122.26019, \"height\": 10.875671, \"text\": \"\" } ], [ { \"top\": 617.351, \"left\": 53.875286, \"width\": 52.82519, \"height\": 11.068726, \"text\": \"E[I] (P)\" }, { \"top\": 617.351, \"left\": 106.70048, \"width\": 181.70715, \"height\": 11.068726, \"text\": \"<NAME>\" }, { \"top\": 617.351, \"left\": 288.40762, \"width\": 122.303314, \"height\": 11.068726, \"text\": \"\" }, { \"top\": 617.351, \"left\": 410.71094, \"width\": 122.26019, \"height\": 11.068726, \"text\": \"\" } ], [ { \"top\": 628.41974, \"left\": 53.875286, \"width\": 52.82519, \"height\": 11.040283, \"text\": \"\" }, { \"top\": 628.41974, \"left\": 106.70048, \"width\": 181.70715, \"height\": 11.040283, \"text\": \"<NAME>\" }, { \"top\": 628.41974, \"left\": 288.40762, \"width\": 122.303314, \"height\": 11.040283, \"text\": \"\" }, { \"top\": 628.41974, \"left\": 410.71094, \"width\": 122.26019, \"height\": 11.040283, \"text\": \"\" } ] ] } ]" private val validButNotMatchingJson = "[ { \"extraction_method\": \"lattice\", \"top\": 113.945274, \"left\": 53.875286, \"width\": 489.77463, \"height\": 480.44003, \"right\": 543.6499, \"bottom\": 594.3853, \"data\": [ [ { \"top\": 113.945274, \"left\": 124.572914, \"width\": 69.84507, \"height\": 15.439293, \"text\": \"Segunda\" }, { \"top\": 113.945274, \"left\": 194.41798, \"width\": 69.87288, \"height\": 15.439293, \"text\": \"Terça\" }, { \"top\": 113.945274, \"left\": 264.29086, \"width\": 69.8483, \"height\": 15.439293, \"text\": \"Quarta\" }, { \"top\": 113.945274, \"left\": 334.13916, \"width\": 69.84784, \"height\": 15.439293, \"text\": \"Quinta\" }, { \"top\": 113.945274, \"left\": 403.987, \"width\": 69.88223, \"height\": 15.439293, \"text\": \"Sexta\" }, { \"top\": 113.945274, \"left\": 473.86923, \"width\": 69.78067, \"height\": 15.439293, \"text\": \"Sábado\" } ], [ { \"top\": 129.38457, \"left\": 54.97015, \"width\": 69.60277, \"height\": 15.475281, \"text\": \"8.00 - 8.30\" }, { \"top\": 129.38457, \"left\": 124.572914, \"width\": 69.84507, \"height\": 15.475281, \"text\": \"\" }, { \"top\": 129.38457, \"left\": 194.41798, \"width\": 69.87288, \"height\": 15.475281, \"text\": \"\" }, { \"top\": 129.38457, \"left\": 264.29086, \"width\": 69.8483, \"height\": 15.475281, \"text\": \"\" }, { \"top\": 129.38457, \"left\": 334.13916, \"width\": 69.84784, \"height\": 15.475281, \"text\": \"\" }, { \"top\": 129.38457, \"left\": 403.987, \"width\": 69.88223, \"height\": 15.475281, \"text\": \"\" } ], [ { \"top\": 144.85985, \"left\": 54.97015, \"width\": 69.60277, \"height\": 15.480118, \"text\": \"8.30 - 9.00\" }, { \"top\": 144.85985, \"left\": 124.572914, \"width\": 69.84507, \"height\": 15.480118, \"text\": \"\" }, { \"top\": 144.85985, \"left\": 194.41798, \"width\": 69.87288, \"height\": 15.480118, \"text\": \"\" }, { \"top\": 144.85985, \"left\": 264.29086, \"width\": 69.8483, \"height\": 15.480118, \"text\": \"\" }, { \"top\": 144.85985, \"left\": 334.13916, \"width\": 69.84784, \"height\": 15.480118, \"text\": \"\" }, { \"top\": 144.85985, \"left\": 403.987, \"width\": 69.88223, \"height\": 15.480118, \"text\": \"\" } ], [ { \"top\": 160.33997, \"left\": 54.97015, \"width\": 69.60277, \"height\": 15.480331, \"text\": \"9.00 - 9.30\" }, { \"top\": 160.33997, \"left\": 124.572914, \"width\": 69.84507, \"height\": 15.480331, \"text\": \"\" }, { \"top\": 160.33997, \"left\": 194.41798, \"width\": 69.87288, \"height\": 15.480331, \"text\": \"\" }, { \"top\": 160.33997, \"left\": 264.29086, \"width\": 69.8483, \"height\": 15.480331, \"text\": \"\" }, { \"top\": 160.33997, \"left\": 334.13916, \"width\": 69.84784, \"height\": 15.480331, \"text\": \"\" }, { \"top\": 160.33997, \"left\": 403.987, \"width\": 69.88223, \"height\": 15.480331, \"text\": \"\" } ] ] }, { \"extraction_method\": \"lattice\", \"top\": 606.47534, \"left\": 53.875286, \"width\": 479.09586, \"height\": 109.97766, \"right\": 532.9711, \"bottom\": 716.453, \"data\": [ [ { \"top\": 606.47534, \"left\": 53.875286, \"width\": 52.82519, \"height\": 10.875671, \"text\": \"ALGA[I] (T)\" }, { \"top\": 606.47534, \"left\": 106.70048, \"width\": 181.70715, \"height\": 10.875671, \"text\": \"<NAME>\" }, { \"top\": 606.47534, \"left\": 288.40762, \"width\": 122.303314, \"height\": 10.875671, \"text\": \"\" }, { \"top\": 606.47534, \"left\": 410.71094, \"width\": 122.26019, \"height\": 10.875671, \"text\": \"\" } ], [ { \"top\": 617.351, \"left\": 53.875286, \"width\": 52.82519, \"height\": 11.068726, \"text\": \"E[I] (P)\" }, { \"top\": 617.351, \"left\": 106.70048, \"width\": 181.70715, \"height\": 11.068726, \"text\": \"<NAME>\" }, { \"top\": 617.351, \"left\": 288.40762, \"width\": 122.303314, \"height\": 11.068726, \"text\": \"\" }, { \"top\": 617.351, \"left\": 410.71094, \"width\": 122.26019, \"height\": 11.068726, \"text\": \"\" } ], [ { \"top\": 628.41974, \"left\": 53.875286, \"width\": 52.82519, \"height\": 11.040283, \"text\": \"\" }, { \"top\": 628.41974, \"left\": 106.70048, \"width\": 181.70715, \"height\": 11.040283, \"text\": \"<NAME>\" }, { \"top\": 628.41974, \"left\": 288.40762, \"width\": 122.303314, \"height\": 11.040283, \"text\": \"\" }, { \"top\": 628.41974, \"left\": 410.71094, \"width\": 122.26019, \"height\": 11.040283, \"text\": \"\" } ] ] } ], { \"top\": 628.41974, \"left\": 410.71094, \"width\": 122.26019, \"height\": 11.040283, \"text\": \"\" }" private val invalidTimeTableJson = "[ { \"extraction_method\": \"lattice\", \"top\": 113.945274, \"left\": 53.875286, \"width\": 489.77463, \"height\": 480.44003, \"right\": 543.6499, \"bottom\": 594.3853, \"data\": [ [ { \"top\": 113.945274, \"left\": 124.572914, \"width\": 69.84507, \"height\": 15.439293, \"text\": \"Segunda\" }, { \"top\": 113.945274, \"left\": 194.41798, \"width\": 69.87288, \"height\": 15.439293, \"text\": \"Terça\" }, { \"top\": 113.945274, \"left\": 264.29086, \"width\": 69.8483, \"height\": 15.439293, \"text\": \"Quarta\" }, { \"top\": 113.945274, \"left\": 334.13916, \"width\": 69.84784, \"height\": 15.439293, \"text\": \"Quinta\" }, { \"top\": 113.945274, \"left\": 403.987, \"width\": 69.88223, \"height\": 15.439293, \"text\": \"Sexta\" }, { \"top\": 113.945274, \"left\": 473.86923, \"width\": 69.78067, \"height\": 15.439293, \"text\": \"Sábado\" } ], [ { \"top\": 129.38457, \"left\": 54.97015, \"width\": 69.60277, \"height\": 15.475281, \"text\": \"8.00 - 8.30\" }, { \"top\": 129.38457, \"left\": 124.572914, \"width\": 69.84507, \"height\": 15.475281, \"text\": \"\" }, { \"top\": 129.38457, \"left\": 194.41798, \"width\": 69.87288, \"height\": 15.475281, \"text\": \"\" }, { \"top\": 129.38457, \"left\": 264.29086, \"width\": 69.8483, \"height\": 15.475281, \"text\": \"\" }, { \"top\": 129.38457, \"left\": 334.13916, \"width\": 69.84784, \"height\": 15.475281, \"text\": \"\" }, { \"top\": 129.38457, \"left\": 403.987, \"width\": 69.88223, \"height\": 15.475281, \"text\": \"\" } ], [ { \"top\": 144.85985, \"left\": 54.97015, \"width\": 69.60277, \"height\": 15.480118, \"text\": \"8.30 - 9.00\" }, { \"top\": 144.85985, \"left\": 124.572914, \"width\": 69.84507, \"height\": 15.480118, \"text\": \"\" }, { \"top\": 144.85985, \"left\": 194.41798, \"width\": 69.87288, \"height\": 15.480118, \"text\": \"\" }, { \"top\": 144.85985, \"left\": 264.29086, \"width\": 69.8483, \"height\": 15.480118, \"text\": \"\" }, { \"top\": 144.85985, \"left\": 334.13916, \"width\": 69.84784, \"height\": 15.480118, \"text\": \"\" }, { \"top\": 144.85985, \"left\": 403.987, \"width\": 69.88223, \"height\": 15.480118, \"text\": \"\" } ], [ { \"top\": 160.33997, \"left\": 54.97015, \"width\": 69.60277, \"height\": 15.480331, \"text\": \"9.00 - 9.30\" }, { \"top\": 160.33997, \"left\": 124.572914, \"width\": 69.84507, \"height\": 15.480331, \"text\": \"\" }, { \"top\": 160.33997, \"left\": 194.41798, \"width\": 69.87288, \"height\": 15.480331, \"text\": \"\" }, { \"top\": 160.33997, \"left\": 264.29086, \"width\": 69.8483, \"height\": 15.480331, \"text\": \"\" }, { \"top\": 160.33997, \"left\": 334.13916, \"width\": 69.84784, \"height\": 15.480331, \"text\": \"\" }, { \"top\": 160.33997, \"left\": 403.987, \"width\": 69.88223, \"height\": 15.480331, \"text\": \"\" } ] ] },{ ]" private val exactMatch = "Turma: LI11D Ano Letivo: 2019/20-Verão\r" private val matchingText = "$exactMatch the quick fox jumps over the lazy dog" private val notMatchingText = "Alice 123" private val validUTCDate = "20210516T214838Z" private val validInstructorJson = "[{\"extraction_method\":\"stream\",\"top\":671.0,\"left\":36.0,\"width\":521.0,\"height\":152.0,\"right\":557.0,\"bottom\":823.0,\"data\":[[{\"top\":677.97,\"left\":40.8,\"width\":43.77017593383789,\"height\":3.7100000381469727,\"text\":\"ALGA[T] (T)\"},{\"top\":677.97,\"left\":120.48,\"width\":107.44999694824219,\"height\":3.7100000381469727,\"text\":\"<NAME>\"}],[{\"top\":691.65,\"left\":40.8,\"width\":62.52817153930664,\"height\":3.7100000381469727,\"text\":\"ALGA[T] - 1 (T/P)\"},{\"top\":691.65,\"left\":120.48,\"width\":127.38999938964844,\"height\":3.7100000381469727,\"text\":\"<NAME>\"}],[{\"top\":705.33,\"left\":40.8,\"width\":42.10811233520508,\"height\":3.7100000381469727,\"text\":\"IC[T] - 1 (P)\"},{\"top\":705.33,\"left\":120.48,\"width\":95.19999694824219,\"height\":3.7100000381469727,\"text\":\"<NAME>\"}],[{\"top\":719.01,\"left\":40.8,\"width\":42.38066482543945,\"height\":3.7100000381469727,\"text\":\"IC[T] - 2 (P)\"},{\"top\":719.01,\"left\":120.48,\"width\":103.88999938964844,\"height\":3.7100000381469727,\"text\":\"<NAME>\"}],[{\"top\":732.69,\"left\":40.8,\"width\":30.850666046142578,\"height\":3.7100000381469727,\"text\":\"IC[T] (T)\"},{\"top\":732.69,\"left\":120.48,\"width\":95.19999694824219,\"height\":3.7100000381469727,\"text\":\"<NAME>\"}],[{\"top\":746.37,\"left\":40.8,\"width\":49.82218551635742,\"height\":3.7100000381469727,\"text\":\"LSD[T] - 1 (P)\"},{\"top\":746.37,\"left\":120.48,\"width\":146.5900115966797,\"height\":3.7100000381469727,\"text\":\"<NAME>\"}],[{\"top\":760.05,\"left\":40.8,\"width\":38.00986862182617,\"height\":3.7100000381469727,\"text\":\"LSD[T] (T)\"},{\"top\":760.05,\"left\":120.48,\"width\":146.5900115966797,\"height\":3.7100000381469727,\"text\":\"<NAME>\"}],[{\"top\":773.73,\"left\":40.8,\"width\":50.310665130615234,\"height\":3.7100000381469727,\"text\":\"PG I[T] - 1 (P)\"},{\"top\":773.73,\"left\":120.48,\"width\":96.63999938964844,\"height\":3.7100000381469727,\"text\":\"<NAME>\"}],[{\"top\":787.41,\"left\":40.8,\"width\":38.78065872192383,\"height\":3.7100000381469727,\"text\":\"PG I[T] (T)\"},{\"top\":787.41,\"left\":120.48,\"width\":96.63999938964844,\"height\":3.7100000381469727,\"text\":\"<NAME>\"}]]}]" private val invalidInstructorJson = "[{\"extraction_method\":\"stream\",\"top\":671.0,\"left\":36.0,\"width\":521.0,\"height\":152.0,\"right\":557.0,\"bottom\":823.0,\"data\":[[{\"top\":677.97,\"left\":40.8,\"width\":43.77017593383789,\"height\":3.7100000381469727,\"text\":\"ALGA[T] (T)\"},{\"top\":677.97,\"left\":120.48,\"width\":107.44999694824219,\"height\":3.7100000381469727,\"text\":\"<NAME>\"}],[{\"top\":691.65,\"left\":40.8,\"width\":62.52817153930664,\"height\":3.7100000381469727,\"text\":\"ALGA[T] - 1 (T/P)\"},{\"top\":691.65,\"left\":120.48,\"width\":127.38999938964844,\"height\":3.7100000381469727,\"text\":\"<NAME>\"}],[{\"top\":705.33,\"left\":40.8,\"width\":42.10811233520508,\"height\":3.7100000381469727,\"text\":\"IC[T] - 1 (P)\"},{\"top\":705.33,\"left\":120.48,\"width\":95.19999694824219,\"height\":3.7100000381469727,\"text\":\"Vítor Manuel da Silva Costa\"}],[{\"top\":719.01,\"left\":40.8,\"width\":42.38066482543945,\"height\":3.7100000381469727,\"text\":\"IC[T] - 2 (P)\"},{\"top\":719.01,\"left\":120.48,\"width\":103.88999938964844,\"height\":3.7100000381469727,\"text\":\"<NAME>\"}],[{\"top\":732.69,\"left\":40.8,\"width\":30.850666046142578,\"height\":3.7100000381469727,\"text\":\"IC[T] (T)\"},{\"top\":732.69,\"left\":120.48,\"width\":95.19999694824219,\"height\":3.7100000381469727,\"text\":\"<NAME>\"}],[{\"top\":746.37,\"left\":40.8,\"width\":49.82218551635742,\"height\":3.7100000381469727,\"text\":\"LSD[T] - 1 (P)\"},{\"top\":746.37,\"left\":120.48,\"width\":146.5900115966797,\"height\":3.7100000381469727,\"text\":\"<NAME>\"}],[{\"top\":760.05,\"left\":40.8,\"width\":38.00986862182617,\"height\":3.7100000381469727,\"text\":\"LSD[T] (T)\"},{\"top\":760.05,\"left\":120.48,\"width\":146.5900115966797,\"height\":3.7100000381469727,\"text\":\"<NAME>\"}],[{\"top\":773.73,\"left\":40.8,\"width\":50.310665130615234,\"height\":3.7100000381469727,\"text\":\"PG I[T] - 1 (P)\"},{\"top\":773.73,\"left\":120.48,\"width\":96.63999938964844,\"height\":3.7100000381469727,\"text\":\"<NAME>\"}],[{\"top\":787.41,\"left\":40.8,\"width\":38.78065872192383,\"height\":3.7100000381469727,\"text\":\"PG I[T] (T)\"},{\"top\":787.41,\"left\":120.48,\"width\":96.63999938964844,\"height\":3.7100000381469727,\"text\":\"<NAME>\"}]]" @Test fun `when Both Fields Of Dynamic Object Are Valid then Assert Result True`() { val dynamicObject = RawTimetableData( validTimeTableJson, listOf(exactMatch), validInstructorJson, validUTCDate ) val fc = ISELTimetableFormatChecker() val res = fc.checkFormat(dynamicObject).orThrow() assertTrue(res) } @Test fun `when Both Fields Do Not Match then Throw CompositeException`() { val dynamicObject = RawTimetableData( validButNotMatchingJson, listOf(notMatchingText), validInstructorJson, validUTCDate ) val fc = ISELTimetableFormatChecker() val ex = assertThrows<CompositeException> { fc.checkFormat(dynamicObject).orThrow() } assertEquals("FormatCheckException", ex.exceptions[0].javaClass.simpleName) assertEquals("FormatCheckException", ex.exceptions[1].javaClass.simpleName) } @Test fun `when Invalid Json And Matching String then Throw FormatCheckException`() { val dynamicObject = RawTimetableData( invalidTimeTableJson, listOf(matchingText), invalidInstructorJson, validUTCDate ) val fc = ISELTimetableFormatChecker() val ex = assertThrows<CompositeException> { fc.checkFormat(dynamicObject).orThrow() } assertEquals(2, ex.exceptions.count()) assertTrue(ex.exceptions.all { it is FormatCheckException }) } @Test fun `when Valid but Not Matching Json then Throw FormatCheckException`() { val dynamicObject = RawTimetableData( validButNotMatchingJson, listOf(matchingText), validInstructorJson, validUTCDate ) val fc = ISELTimetableFormatChecker() val ex = assertThrows<FormatCheckException> { fc.checkFormat(dynamicObject).orThrow() } assertEquals("The timetable table changed its format", ex.message) } @Test fun `when Valid Json And Matching Text then Assert Result Is True`() { val dynamicObject = RawTimetableData( validTimeTableJson, listOf(matchingText), validInstructorJson, validUTCDate ) val fc = ISELTimetableFormatChecker() val res = fc.checkFormat(dynamicObject).orThrow() assertTrue(res) } @Test fun `when Valid Json And Empty String then Throw FormatCheckException`() { val dynamicObject = RawTimetableData( validTimeTableJson, listOf(""), validInstructorJson, validUTCDate ) val fc = ISELTimetableFormatChecker() val ex = assertThrows<FormatCheckException> { fc.checkFormat(dynamicObject).orThrow() } assertEquals("The timetable header changed its format", ex.message) } @Test fun `when Valid Json And Not Matching Text then Throw FormatCheckException`() { val dynamicObject = RawTimetableData( validTimeTableJson, listOf(notMatchingText), validInstructorJson, validUTCDate ) val fc = ISELTimetableFormatChecker() val ex = assertThrows<FormatCheckException> { fc.checkFormat(dynamicObject).orThrow() } assertEquals("The timetable header changed its format", ex.message) } }
10
Kotlin
0
3
d221d71dd5252da878953f2a0a93734a720a5290
20,388
integration
Apache License 2.0
projects/parsing/src/main/kotlin/silentorb/imp/parsing/parser/Integrity.kt
silentorb
235,929,224
false
null
package silentorb.imp.parsing.parser import silentorb.imp.core.* import silentorb.imp.parsing.general.* import silentorb.imp.parsing.resolution.FunctionApplication import java.nio.file.Path fun validateFunctionTypes(referenceOptions: Map<PathKey, Map<PathKey, TypeHash>>, nodeMap: NodeMap): ImpErrors { return referenceOptions .filter { it.value.none() } .map { (node, _) -> val fileRange = nodeMap[node]!! newParsingError(TextId.unknownFunction, fileRange) } } fun getArgumentTypeNames( context: Context, applications: Map<PathKey, FunctionApplication>, types: Map<PathKey, TypeHash>, parents: Map<PathKey, List<PathKey>>, node: PathKey ): List<String> { val application = applications.entries.firstOrNull { it.value.target == node }?.key val arguments = parents[application] return if (arguments == null) listOf() else { arguments.map { argumentKey -> val argumentType = types[argumentKey] if (argumentType != null) getTypeNameOrUnknown(context, argumentType) else unknownSymbol } } } fun validateSignatures( context: Context, types: Map<PathKey, TypeHash>, referenceOptions: Set<PathKey>, parents: Map<PathKey, List<PathKey>>, signatureOptions: Map<PathKey, List<SignatureMatch>>, applications: Map<PathKey, FunctionApplication>, nodeMap: NodeMap ): ImpErrors { return referenceOptions .mapNotNull { node -> val options = signatureOptions[node] ?: listOf() if (options.size == 1) null else if (options.none()) { val argumentTypeNames = getArgumentTypeNames(context, applications, types, parents, node) val argumentClause = if (argumentTypeNames.any()) argumentTypeNames.joinToString(", ") else "Unit" ImpError(TextId.noMatchingSignature, fileRange = nodeMap[node]!!, arguments = listOf(argumentClause)) } else ImpError(TextId.ambiguousOverload, fileRange = nodeMap[node]!!) } } fun isValueWithinConstraint(constraint: NumericTypeConstraint, value: Any): Boolean { val doubleValue = when (value) { is Double -> value is Int -> value.toDouble() is Float -> value.toDouble() else -> null } return if (doubleValue == null) false else doubleValue >= constraint.minimum && doubleValue <= constraint.maximum } fun validateTypeConstraints(values: Map<PathKey, Any>, context: Context, constraints: ConstrainedLiteralMap, nodeMap: NodeMap): ImpErrors { return values.mapNotNull { (node, value) -> val constraintType = constraints[node] if (constraintType != null) { val constraint = resolveNumericTypeConstraint(constraintType)(context) if (constraint == null || isValueWithinConstraint(constraint, value)) null else newParsingError(TextId.outsideTypeRange, nodeMap[node]!!) } else null } } fun validateUnusedImports(context: Context, importMap: Map<Path, List<TokenizedImport>>, definitions: Map<PathKey, TokenizedDefinition>): ImpErrors { val unusedImports = importMap .filter { (key, _) -> definitions.none { it.value.file == key } } return unusedImports.flatMap { (_, imports) -> imports .flatMap { tokenizedImport -> parseImport(context)(tokenizedImport).errors } } }
3
Kotlin
0
1
ca465c2b0a9864ded53114120d8b98dad44551dd
3,384
imp-kotlin
MIT License
src/main/kotlin/me/coderfrish/shulkerPack/listener/EventListener.kt
XieFrish2021
850,327,835
false
{"Kotlin": 13181, "Java": 508, "Shell": 40}
package me.coderfrish.shulkerPack.listener @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.RUNTIME) @Deprecated(message = "null.") annotation class EventListener
0
Kotlin
0
0
d7523fa1c8ad45b2faec10a1e2a028e810bc812b
178
ShulkerPackPlus
Apache License 2.0
frontend/app/src/main/java/com/proelbtn/linesc/activities/LoginActivity.kt
line-school2018summer
144,241,660
false
null
package com.proelbtn.linesc.activities import android.content.Context import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.MenuItem import android.widget.Button import android.widget.EditText import com.proelbtn.linesc.R import com.proelbtn.linesc.presenters.LoginPresenter class LoginActivity : AppCompatActivity(), LoginPresenter.View { val presenter = LoginPresenter(this) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setTheme(R.style.AppTheme) setContentView(R.layout.activity_login) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.title = "Login" findViewById<Button>(R.id.button_login).setOnClickListener { presenter.onLogin() } } override fun getContext(): Context { return this } override fun getSid(): String { return findViewById<EditText>(R.id.text_sid).text.toString() } override fun getPassword(): String { return findViewById<EditText>(R.id.text_password).text.toString() } override fun navigateToEntryActivity() { val intent = Intent(this, EntryActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK startActivity(intent) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { android.R.id.home -> finish() else -> return super.onOptionsItemSelected(item) } return true } }
11
Kotlin
0
2
b3802b53c0299a1c435db20089c0cb619f7955aa
1,594
tokyo-d
MIT License
app/src/main/java/com/theapache64/topcorn/models/FeedItem.kt
theapache64
256,630,741
false
null
package com.theapache64.topcorn.models import com.theapache64.topcorn.data.remote.Movie data class FeedItem( val id: Long, val genre: String, val movies: List<Movie> )
4
Kotlin
41
211
0bbe8556ab38cf61a8193e8b5cc9ec670f0a2f34
183
topcorn
Apache License 2.0
backend/src/test/kotlin/app/KotlinJunitTest.kt
sz-piotr
84,575,954
false
{"JavaScript": 26091, "Kotlin": 24806, "CSS": 5824, "HTML": 293}
package app /** * Created by michal on 27/03/2017. */ import org.junit.Assert import org.junit.Test class KotlinJunitTest { @Test fun firstTest() { Assert.assertTrue(1 == 1) } }
0
JavaScript
1
0
8fecfc2e30ad29208d9743b9e3f5ec2eb9d5277b
204
pik-projekt
MIT License
app/src/main/java/com/example/dropy/ui/components/maps/markers/GoogleMapMarker.kt
dropyProd
705,360,878
false
{"Kotlin": 3916897, "Java": 20617}
package com.example.dropy.ui.components.commons.maps.markers import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import com.google.android.gms.maps.model.LatLng import com.google.maps.android.compose.Marker import com.google.maps.android.compose.MarkerState @Composable fun GoogleMapMarker( position: LatLng, title:String = "Marker title", snippet:String = "Marker snippet", infoWindowClicked: (()->Unit)? = null, infoWindowLongClick: (()->Unit)? = null, ){ val infoWindowShown = remember { mutableStateOf(false) } Marker( state = MarkerState(position = position), title = title, snippet = snippet, onClick = { if (infoWindowShown.value){ it.hideInfoWindow() }else{ it.showInfoWindow() } infoWindowShown.value = !infoWindowShown.value true }, onInfoWindowClick = { if (infoWindowClicked != null) { infoWindowClicked() } }, onInfoWindowLongClick = { if (infoWindowLongClick != null) { infoWindowLongClick() } } ) }
0
Kotlin
0
0
6d994c9c61207bac28c49717b6c250656fe4ae6b
1,283
DropyLateNights
Apache License 2.0
examples/src/benchmarks/kotlin/scientifik/kmath/structures/ArrayBenchmark.kt
koperagen
226,191,158
true
{"Kotlin": 217723}
package scientifik.kmath.structures import org.openjdk.jmh.annotations.Benchmark import org.openjdk.jmh.annotations.Scope import org.openjdk.jmh.annotations.State import java.nio.IntBuffer @State(Scope.Benchmark) class ArrayBenchmark { @Benchmark fun benchmarkArrayRead() { var res = 0 for (i in 1..size) { res += array[size - i] } } @Benchmark fun benchmarkBufferRead() { var res = 0 for (i in 1..size) { res += arrayBuffer.get(size - i) } } @Benchmark fun nativeBufferRead() { var res = 0 for (i in 1..size) { res += nativeBuffer.get(size - i) } } companion object { val size = 1000 val array = IntArray(size) { it } val arrayBuffer = IntBuffer.wrap(array) val nativeBuffer = IntBuffer.allocate(size).also { for (i in 0 until size) { it.put(i, i) } } } }
0
null
0
0
b91695dcf80788aff827114afd31bb62b4092bed
997
kmath
Apache License 2.0
mockmvc/src/main/kotlin/com/ninjasquad/springrestdocskotlin/mockmvc/MockMvcDsl.kt
sdeleuze
171,487,728
true
{"Kotlin": 59303}
package com.ninjasquad.springrestdocskotlin.mockmvc import com.ninjasquad.springrestdocskotlin.core.DocumentationScope import com.ninjasquad.springrestdocskotlin.core.documentationScope import org.springframework.http.HttpMethod import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders import org.springframework.restdocs.operation.preprocess.OperationRequestPreprocessor import org.springframework.restdocs.operation.preprocess.OperationResponsePreprocessor import org.springframework.test.web.servlet.ResultActions import org.springframework.test.web.servlet.ResultHandler import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder import org.springframework.test.web.servlet.request.MockMultipartHttpServletRequestBuilder fun docGet(urlTemplate: String, vararg urlVariables: Any): MockHttpServletRequestBuilder = RestDocumentationRequestBuilders.get(urlTemplate, *urlVariables) fun docPost(urlTemplate: String, vararg urlVariables: Any): MockHttpServletRequestBuilder = RestDocumentationRequestBuilders.post(urlTemplate, *urlVariables) fun docPut(urlTemplate: String, vararg urlVariables: Any): MockHttpServletRequestBuilder = RestDocumentationRequestBuilders.put(urlTemplate, *urlVariables) fun docDelete(urlTemplate: String, vararg urlVariables: Any): MockHttpServletRequestBuilder = RestDocumentationRequestBuilders.delete(urlTemplate, *urlVariables) fun docHead(urlTemplate: String, vararg urlVariables: Any): MockHttpServletRequestBuilder = RestDocumentationRequestBuilders.head(urlTemplate, *urlVariables) fun docOptions(urlTemplate: String, vararg urlVariables: Any): MockHttpServletRequestBuilder = RestDocumentationRequestBuilders.options(urlTemplate, *urlVariables) fun docPatch(urlTemplate: String, vararg urlVariables: Any): MockHttpServletRequestBuilder = RestDocumentationRequestBuilders.patch(urlTemplate, *urlVariables) fun docFileUpload(urlTemplate: String, vararg urlVariables: Any): MockMultipartHttpServletRequestBuilder = RestDocumentationRequestBuilders.fileUpload(urlTemplate, *urlVariables) fun docRequest(httpMethod: HttpMethod, urlTemplate: String, vararg urlVariables: Any): MockHttpServletRequestBuilder = RestDocumentationRequestBuilders.request(httpMethod, urlTemplate, *urlVariables) fun ResultActions.andDocument(identifier: String, configure: DocumentationScope.() -> Unit): ResultActions = andDo(documentationScope(identifier).apply(configure).toResultHandler()) private fun DocumentationScope.toResultHandler(): ResultHandler = MockMvcRestDocumentation.document( identifier, requestPreprocessor ?: OperationRequestPreprocessor { request -> request }, responsePreprocessor ?: OperationResponsePreprocessor { response -> response }, *snippets.toTypedArray() )
0
Kotlin
0
0
78e1eb56948ae3129d2808b18b62511506c74e3a
2,900
spring-rest-docs-kotlin
MIT License
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/filled/CommentEdit.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.filled import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Filled.CommentEdit: ImageVector get() { if (_commentEdit != null) { return _commentEdit!! } _commentEdit = fluentIcon(name = "Filled.CommentEdit") { fluentPath { moveTo(2.0f, 14.75f) curveTo(2.0f, 16.55f, 3.46f, 18.0f, 5.25f, 18.0f) lineTo(6.0f, 18.0f) verticalLineToRelative(3.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.58f, 0.82f) lineToRelative(2.59f, -1.84f) lineToRelative(0.35f, -1.4f) curveToRelative(0.16f, -0.65f, 0.5f, -1.24f, 0.97f, -1.72f) lineToRelative(5.9f, -5.9f) arcToRelative(3.29f, 3.29f, 0.0f, false, true, 4.61f, -0.04f) lineTo(22.0f, 6.25f) curveTo(22.0f, 4.45f, 20.54f, 3.0f, 18.75f, 3.0f) lineTo(5.25f, 3.0f) arcTo(3.25f, 3.25f, 0.0f, false, false, 2.0f, 6.25f) verticalLineToRelative(8.5f) close() moveTo(18.1f, 11.67f) lineToRelative(-5.9f, 5.9f) curveToRelative(-0.35f, 0.35f, -0.6f, 0.78f, -0.71f, 1.25f) lineToRelative(-0.46f, 1.83f) curveToRelative(-0.2f, 0.8f, 0.52f, 1.52f, 1.32f, 1.32f) lineToRelative(1.83f, -0.46f) curveToRelative(0.47f, -0.12f, 0.9f, -0.36f, 1.25f, -0.7f) lineToRelative(5.9f, -5.9f) arcToRelative(2.29f, 2.29f, 0.0f, true, false, -3.23f, -3.24f) close() } } return _commentEdit!! } private var _commentEdit: ImageVector? = null
0
Kotlin
0
24
336c85b59b6a6ad97a522a25a0042cd8e0750474
1,932
compose-fluent-ui
Apache License 2.0
domain/src/main/java/org/commcare/dalvik/domain/usecases/SubmitPatientConsentUsecase.kt
dimagi
531,775,811
false
{"Kotlin": 310454}
package org.commcare.dalvik.domain.usecases import org.commcare.dalvik.domain.model.PatientConsentDetailModel import org.commcare.dalvik.domain.repositories.AbdmRepository import javax.inject.Inject class SubmitPatientConsentUsecase @Inject constructor(val repository: AbdmRepository) { fun execute(patientConsentDetailModel: PatientConsentDetailModel) = repository.submitPatientConsent(patientConsentDetailModel) }
0
Kotlin
1
0
a580934bf0ad6ed270a631e6c817d54f3c823c40
429
abdm-app
Apache License 2.0
app/src/main/java/com/ajibsbaba/acefood/navigation/NavGraph.kt
AjibsBaba
709,508,604
false
{"Kotlin": 40796}
package com.ajibsbaba.acefood.navigation import android.content.Context import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.platform.LocalContext import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import com.ajibsbaba.acefood.OnboardingManager import com.ajibsbaba.acefood.screens.OnboardingScreen import com.ajibsbaba.acefood.screens.home.HomeScreen import com.ajibsbaba.acefood.screens.scan.ScanScreen object AcefoodDestinations { const val HOME_ROUTE = "home" const val ONBOARDING_ROUTE = "onboarding" const val SCAN_ROUTE = "scan_screen" } @Composable fun AcefoodNavigation() { val navController = rememberNavController() val context: Context = LocalContext.current val isOnboardingCompleted by OnboardingManager.onboardingCompleted( context ).collectAsState(initial = false) NavHost( navController = navController, startDestination = if (isOnboardingCompleted) AcefoodDestinations.HOME_ROUTE else AcefoodDestinations.ONBOARDING_ROUTE ) { composable(AcefoodDestinations.ONBOARDING_ROUTE) { OnboardingScreen(navController = navController) } composable(AcefoodDestinations.HOME_ROUTE) { HomeScreen(navController = navController) } composable(AcefoodDestinations.SCAN_ROUTE) { ScanScreen(navController = navController) } } }
1
Kotlin
0
0
cd294b2072268dea462ee00eb943e74ea3e5045f
1,590
acefood
MIT License
feedparser/src/main/java/io/github/lazyengineer/feedparser/model/channel/FeedChannel.kt
lazy-engineer
294,155,514
false
null
package io.github.lazyengineer.feedparser.model.channel import io.github.lazyengineer.feedparser.model.atom.AtomEntry import io.github.lazyengineer.feedparser.model.namespace.atom.AtomAuthor import io.github.lazyengineer.feedparser.model.namespace.atom.AtomCategory import io.github.lazyengineer.feedparser.model.namespace.atom.AtomContributor import io.github.lazyengineer.feedparser.model.namespace.atom.AtomGenerator import io.github.lazyengineer.feedparser.model.namespace.atom.AtomLink import io.github.lazyengineer.feedparser.model.namespace.atom.AtomNamespace import io.github.lazyengineer.feedparser.model.namespace.atom.AtomSubtitle import io.github.lazyengineer.feedparser.model.namespace.atom.AtomTitle import io.github.lazyengineer.feedparser.model.namespace.dublincore.DublinCoreNamespace import io.github.lazyengineer.feedparser.model.namespace.itunes.ITunes import io.github.lazyengineer.feedparser.model.namespace.syndication.SyndicationNamespace import io.github.lazyengineer.feedparser.model.rss.RSSChannelCategory import io.github.lazyengineer.feedparser.model.rss.RSSChannelCloud import io.github.lazyengineer.feedparser.model.rss.RSSChannelImage import io.github.lazyengineer.feedparser.model.rss.RSSChannelItem import io.github.lazyengineer.feedparser.model.rss.RSSChannelSkipDay import io.github.lazyengineer.feedparser.model.rss.RSSChannelTextInput import java.util.Date sealed class FeedChannel data class RSSChannel( var title: String = "No Channel Title", var link: String = "No Channel Link", var description: String = "No Channel Description", var language: String? = null, var copyright: String? = null, var managingEditor: String? = null, var webMaster: String? = null, var pubDate: Date? = null, var lastBuildDate: Date? = null, var categories: MutableList<RSSChannelCategory> = mutableListOf(), var generator: String? = null, var docs: String? = null, var cloud: RSSChannelCloud? = null, var rating: String? = null, var ttl: Int? = null, var image: RSSChannelImage? = null, var textInput: RSSChannelTextInput? = null, var skipHours: MutableList<Int> = mutableListOf(), var skipDays: MutableList<RSSChannelSkipDay> = mutableListOf(), var items: MutableList<RSSChannelItem> = mutableListOf(), var iTunes: ITunes? = ITunes(), var syndicationNamespace: SyndicationNamespace? = SyndicationNamespace(), var dublinCoreNamespace: DublinCoreNamespace? = DublinCoreNamespace(), var atomNamespace: AtomNamespace? = AtomNamespace() ) : FeedChannel() data class RDFChannel( var title: String = "No Channel Title", var link: String = "No Channel Link", var description: String = "No Channel Description", var itemsResource: String? = null, var imageResource: String? = null, var textInputResource: String? = null, var image: RSSChannelImage? = null, var textInput: RSSChannelTextInput? = null, var items: MutableList<RSSChannelItem> = mutableListOf(), var syndicationNamespace: SyndicationNamespace? = SyndicationNamespace(), var dublinCoreNamespace: DublinCoreNamespace? = DublinCoreNamespace(), var attributes: Attributes? = null ) : FeedChannel() { data class Attributes(var about: String?) { constructor(attributes: Map<String, String>) : this(about = attributes["rdf:about"]) } } data class AtomChannel( var id: String? = null, var authors: MutableList<AtomAuthor> = mutableListOf(), var categories: MutableList<AtomCategory> = mutableListOf(), var contributors: MutableList<AtomContributor> = mutableListOf(), var generator: AtomGenerator? = null, var icon: String? = null, var logo: String? = null, var links: MutableList<AtomLink> = mutableListOf(), var rights: String? = null, var subtitle: AtomSubtitle? = null, var title: AtomTitle? = null, var updated: Date? = null, var entries: MutableList<AtomEntry> = mutableListOf() ) : FeedChannel()
0
Kotlin
0
0
e088bee87ab29db9ff781c7afb172f8a08500208
3,831
FeedParser
MIT License
src/main/kotlin/com/soogung/ohouse/domain/product/domain/ProductImage.kt
soolung
529,124,995
false
{"Kotlin": 62357}
package com.soogung.ohouse.domain.product.domain import com.soogung.ohouse.global.entity.BaseTimeEntity import javax.persistence.* @Entity @Table(name = "tbl_product_image") class ProductImage( @Column(nullable = false) var imageUri: String, @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "product_id", nullable = false) var product: Product, @Column(name = "product_image_id") @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long? = null, ): BaseTimeEntity() { }
0
Kotlin
0
0
fd2d83227aa885e082021bbbdc98503056ef790b
522
clone-ohouse-server
MIT License
statistikk/src/main/kotlin/no/nav/su/se/bakover/statistikk/behandling/BehandlingYtelseDetaljer.kt
navikt
227,366,088
false
{"Kotlin": 9248077, "Shell": 4372, "TSQL": 1233, "Dockerfile": 800}
package no.nav.su.se.bakover.statistikk.behandling import no.nav.su.se.bakover.domain.behandling.Stønadsbehandling import no.nav.su.se.bakover.statistikk.StønadsklassifiseringDto.Companion.stønadsklassifisering import vilkår.domain.grunnlag.Bosituasjon internal fun Stønadsbehandling.behandlingYtelseDetaljer(): List<BehandlingsstatistikkDto.BehandlingYtelseDetaljer> { return this.grunnlagsdata.bosituasjon.filterIsInstance<Bosituasjon.Fullstendig>().map { BehandlingsstatistikkDto.BehandlingYtelseDetaljer(satsgrunn = it.stønadsklassifisering()) } }
2
Kotlin
1
1
9fbc1f8db1063c2375380bb776e27299e30591c9
570
su-se-bakover
MIT License
lightbulb-easyrecyclerview/src/main/java/com/github/rooneyandshadows/lightbulb/easyrecyclerview/layout_managers/AutoFitGridLayoutManager.kt
RooneyAndShadows
424,519,760
false
{"Kotlin": 224016}
package com.github.rooneyandshadows.lightbulb.easyrecyclerview.layout_managers import android.content.Context import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView @Suppress("unused") class AutoFitGridLayoutManager(context: Context?, columnWidth: Int) : GridLayoutManager(context, 1) { private var columnWidth = 0 private var columnWidthChanged = true init { setColumnWidth(columnWidth) } @Override override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State) { if (columnWidthChanged && columnWidth > 0) { val totalSpace: Int = if (orientation == VERTICAL) width - paddingRight - paddingLeft else height - paddingTop - paddingBottom val spanCount = Math.max(1, totalSpace / columnWidth) setSpanCount(spanCount) columnWidthChanged = false } super.onLayoutChildren(recycler, state) } private fun setColumnWidth(newColumnWidth: Int) { if (newColumnWidth > 0 && newColumnWidth != columnWidth) { columnWidth = newColumnWidth columnWidthChanged = true } } }
0
Kotlin
3
9
2fc63a8a7828e16eb22185a07b18442b8fe08f31
1,235
lightbulb-easyrecyclerview
Apache License 2.0
core/src/test/kotlin/br/com/guiabolso/events/model/EventErrorTypeTest.kt
lfkimura
129,949,845
true
{"Kotlin": 65298, "Java": 4396, "Shell": 201}
package br.com.guiabolso.events.model import br.com.guiabolso.events.model.EventErrorType.* import br.com.guiabolso.events.model.EventErrorType.Companion.getErrorType import org.junit.Assert.assertEquals import org.junit.Test class EventErrorTypeTest { @Test fun testErrorMapping() { assertEquals(Generic, getErrorType("error")) assertEquals("error", getErrorType("error").typeName) assertEquals(NotFound, getErrorType("notFound")) assertEquals("notFound", getErrorType("notFound").typeName) assertEquals(Unauthorized, getErrorType("unauthorized")) assertEquals("unauthorized", getErrorType("unauthorized").typeName) assertEquals(Forbidden, getErrorType("forbidden")) assertEquals("forbidden", getErrorType("forbidden").typeName) assertEquals(Unknown("somethingElse"), getErrorType("somethingElse")) assertEquals("somethingElse", getErrorType("somethingElse").typeName) } }
0
Kotlin
0
0
8a89dec6f91b13242227e8cf0d32617d192f401f
973
events-protocol
Apache License 2.0
idea/testData/quickfix/experimental/hasOptInAnnotation3.kt
JetBrains
278,369,660
false
null
// "Add '@OptIn(A::class)' annotation to 'root'" "true" // WITH_RUNTIME @RequiresOptIn annotation class A @A fun f1() {} @OptIn fun root() { <caret>f1() }
0
Kotlin
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
160
intellij-kotlin
Apache License 2.0
network/src/main/java/com/lloydsbyte/network/examples/CountryInterface.kt
Jeremyscell82
742,598,615
false
{"Kotlin": 249008}
package com.lloydsbyte.network.examples interface CountryInterface { fun onPullCompleted(countryResponseList: List<CountryResponse.CountryResponse>) fun onPullFailed(error: Throwable) }
0
Kotlin
0
0
7e7c67ff2d7c159c0d41f0811f202c81a5bddb5f
194
CareerAdvr_AI
Apache License 2.0
langzeitbelichtung_ktor_opencv/src/main/kotlin/com/example/plugins/Routing.kt
mi-classroom
792,312,004
false
{"Kotlin": 5040}
package com.example.plugins import com.example.routes.fileRouting import io.ktor.server.application.* import io.ktor.server.response.* import io.ktor.server.routing.* fun Application.configureRouting() { routing { get("/") { call.respondText("Hello World!") } fileRouting() } }
0
Kotlin
0
0
be5d4a32cc5d9cdc28434ed42228c8ca7cae979f
324
mi-web-technologien-beiboot-ss2024-Methusshan25
MIT License
app/src/main/java/com/benxinm/travelapp/viewModel/SearchViewModel.kt
Benxinm
522,448,719
false
{"Kotlin": 267366}
package com.benxinm.travelapp.viewModel import androidx.lifecycle.ViewModel class SearchViewModel:ViewModel() { }
0
Kotlin
0
0
3e85c9bf5688ee89f3cb08513c4041671b5a78b2
115
TravelApp
Apache License 2.0
libnavigation-router/src/main/java/com/mapbox/navigation/route/internal/RouterWrapper.kt
k4anubhav
439,334,238
true
{"Kotlin": 4189704, "Java": 26254, "Python": 11580, "Makefile": 6163, "Shell": 5704}
/** * Tampering with any file that contains billing code is a violation of Mapbox Terms of Service and will result in enforcement of the penalties stipulated in the ToS. */ package com.mapbox.navigation.route.internal import com.mapbox.annotation.module.MapboxModule import com.mapbox.annotation.module.MapboxModuleType import com.mapbox.api.directions.v5.models.DirectionsRoute import com.mapbox.api.directions.v5.models.RouteOptions import com.mapbox.base.common.logger.model.Message import com.mapbox.base.common.logger.model.Tag import com.mapbox.navigation.base.internal.utils.parseDirectionsResponse import com.mapbox.navigation.base.route.RouteRefreshCallback import com.mapbox.navigation.base.route.RouteRefreshError import com.mapbox.navigation.base.route.Router import com.mapbox.navigation.base.route.RouterCallback import com.mapbox.navigation.base.route.RouterFailure import com.mapbox.navigation.navigator.internal.mapToRoutingMode import com.mapbox.navigation.navigator.internal.mapToSdkRouteOrigin import com.mapbox.navigation.route.internal.util.ACCESS_TOKEN_QUERY_PARAM import com.mapbox.navigation.route.internal.util.redactQueryParam import com.mapbox.navigation.utils.internal.ThreadController import com.mapbox.navigation.utils.internal.logI import com.mapbox.navigation.utils.internal.logW import com.mapbox.navigator.RouteRefreshOptions import com.mapbox.navigator.RouterErrorType import com.mapbox.navigator.RouterInterface import com.mapbox.navigator.RoutingProfile import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.net.URL @MapboxModule(MapboxModuleType.NavigationRouter) class RouterWrapper( private val accessToken: String, private val router: RouterInterface, private val threadController: ThreadController, ) : Router { private val mainJobControl by lazy { threadController.getMainScopeAndRootJob() } override fun getRoute(routeOptions: RouteOptions, callback: RouterCallback): Long { val routeUrl = routeOptions.toUrl(accessToken).toString() return router.getRoute(routeUrl) { result, origin -> val urlWithoutToken = URL(routeUrl.redactQueryParam(ACCESS_TOKEN_QUERY_PARAM)) result.fold( { mainJobControl.scope.launch { if (it.type == RouterErrorType.REQUEST_CANCELLED) { logI( TAG, Message( """ Route request cancelled: $routeOptions $origin """.trimIndent() ) ) callback.onCanceled(routeOptions, origin.mapToSdkRouteOrigin()) } else { val failureReasons = listOf( RouterFailure( url = urlWithoutToken, routerOrigin = origin.mapToSdkRouteOrigin(), message = it.message, code = it.code ) ) logW( TAG, Message( """ Route request failed with: $failureReasons """.trimIndent() ) ) callback.onFailure(failureReasons, routeOptions) } } }, { mainJobControl.scope.launch { parseDirectionsResponse( ThreadController.IODispatcher, it, routeOptions ) { logI(TAG, Message("Response metadata: $it")) }.fold( { throwable -> callback.onFailure( listOf( RouterFailure( urlWithoutToken, origin.mapToSdkRouteOrigin(), "failed for response: $it", throwable = throwable ) ), routeOptions ) }, { routes -> callback.onRoutesReady(routes, origin.mapToSdkRouteOrigin()) } ) } } ) } } override fun getRouteRefresh( route: DirectionsRoute, legIndex: Int, callback: RouteRefreshCallback ): Long { val routeOptions = route.routeOptions() val requestUuid = route.requestUuid() val routeIndex = route.routeIndex()?.toIntOrNull() if (routeOptions == null || requestUuid == null || routeIndex == null) { val errorMessage = """ Route refresh failed because of a null param: routeOptions = $routeOptions requestUuid = $requestUuid routeIndex = $routeIndex """.trimIndent() logW(TAG, Message(errorMessage)) callback.onError( RouteRefreshError("Route refresh failed", Exception(errorMessage)) ) return REQUEST_FAILURE } val refreshOptions = RouteRefreshOptions( requestUuid, routeIndex, legIndex, RoutingProfile(routeOptions.profile().mapToRoutingMode(), routeOptions.user()) ) return router.getRouteRefresh(refreshOptions, route.toJson()) { result, _ -> result.fold( { mainJobControl.scope.launch { val errorMessage = """ Route refresh failed. message = ${it.message} code = ${it.code} type = ${it.type} requestId = ${it.requestId} legIndex = $legIndex """.trimIndent() logW(TAG, Message(errorMessage)) callback.onError( RouteRefreshError("Route refresh failed", Exception(errorMessage)) ) } }, { mainJobControl.scope.launch { val refreshedRoute = withContext(ThreadController.IODispatcher) { DirectionsRoute.fromJson( it, routeOptions, route.requestUuid() ) } callback.onRefresh(refreshedRoute) } } ) } } override fun cancelRouteRequest(requestId: Long) { router.cancelRequest(requestId) } override fun cancelRouteRefreshRequest(requestId: Long) { router.cancelRequest(requestId) } override fun cancelAll() { router.cancelAll() } override fun shutdown() { router.cancelAll() } private companion object { private val TAG = Tag("MbxRouterWrapper") private const val ROUTES_LIST_EMPTY = "routes list is empty" private const val REQUEST_FAILURE = -1L } }
0
null
1
1
3751b1323b3e585976a5476176810049061ca1ec
8,299
mapbox-navigation-android
Apache License 2.0
tests/src/main/kotlin/se/ansman/kotshi/GenericClass.kt
ansman
95,685,398
false
{"Kotlin": 392472, "Shell": 246}
package se.ansman.kotshi @Target(AnnotationTarget.TYPE) annotation class SomeTypeAnnotation @JsonSerializable data class GenericClass<out T : CharSequence, out C : Collection<T>>( val collection: C, val value: T, val valueWithTypeAnnotation: @SomeTypeAnnotation T )
4
Kotlin
43
759
524311f039c15a4ca7b08bfcb27dbde1b2c2b6a0
280
kotshi
Apache License 2.0
kafkistry-service-logic/src/main/kotlin/com/infobip/kafkistry/service/topic/validation/NamingValidator.kt
infobip
456,885,171
false
{"Kotlin": 2628950, "FreeMarker": 812501, "JavaScript": 297269, "CSS": 7204}
package com.infobip.kafkistry.service.topic.validation import com.infobip.kafkistry.model.KafkaClusterIdentifier import com.infobip.kafkistry.model.TopicName import com.infobip.kafkistry.service.KafkistryValidationException import org.springframework.stereotype.Component @Component class NamingValidator { private val namePattern = Regex("""\w+([\w\-.]+\w+)?""") fun validateTopicName(topicName: TopicName) = validateName(topicName) fun validateClusterIdentifier(clusterIdentifier: KafkaClusterIdentifier) = validateName(clusterIdentifier) private fun validateName(name: String) { if (!namePattern.matches(name)) { throw KafkistryValidationException( "Name '$name' is not valid name, name is allowed to contain only ascii " + "letters, digits, underscore and dot/minus except on start/end" ) } } }
1
Kotlin
6
42
62403993a76fdf60b4cae3a87c5be0abe4fb3a88
913
kafkistry
Apache License 2.0
app/src/main/java/com/danielefavaro/openweather/OpenWeather.kt
dfavaro
637,725,290
false
null
package com.danielefavaro.openweather import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class OpenWeather : Application()
0
Kotlin
0
0
3f0930a20337ce47f651d1e9085e5cad58b8de7e
163
openweather-android
MIT License
ui/feature/details/src/test/java/com/houlis/haris/feature/details/ui/DetailsViewModelTest.kt
HarisHoulis
595,512,452
false
{"Kotlin": 75718, "Shell": 135}
package com.houlis.haris.feature.details.ui import com.houlis.haris.picfind.feature.details.ui.DetailsMiddleware import com.houlis.haris.picfind.feature.details.ui.DetailsReducer import com.houlis.haris.picfind.feature.details.ui.DetailsState import com.houlis.haris.picfind.feature.details.ui.DetailsViewModel import com.houlis.haris.picfind.feature.details.ui.LoadState import com.houlis.haris.picfind.test.data.FakePicturesRepository import com.houlis.haris.picfind.test.domain.provider.dummyPicture1 import com.houlis.haris.picfind.ui.common.testutil.TestCloseableScope import com.houlis.haris.picfind.ui.common.testutil.assertStatesFor import org.junit.jupiter.api.Test internal class DetailsViewModelTest { private val scope = TestCloseableScope() private val sut = DetailsViewModel( scope, DetailsReducer() ) { dispatcher -> listOf(DetailsMiddleware(FakePicturesRepository(), dispatcher, scope)) } @Test fun `fetches picture's details`() { with(scope) { sut.assertStatesFor( DetailsState(), DetailsState(LoadState.Loading, null), DetailsState(LoadState.Loaded, dummyPicture1().image) ) { detailsFor("any") } } } }
10
Kotlin
0
0
a50c1324ae085712b0655613b91abb07efba46a1
1,293
PicFind
Apache License 2.0
clients/kotlin/generated/src/main/kotlin/org/openapitools/client/models/CatalogsHotelAttributesAllOfMainImage.kt
oapicf
489,369,143
false
{"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31}
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package org.openapitools.client.models import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * The main hotel image * * @param link <p><= 2000 characters</p> <p>The link to the main hotel image. Image should be at least 75x75 pixels to avoid errors. Use the additional_image_link field to add more images of your hotel. The URL of your main_image.link must be accessible by the Pinterest user-agent, and send the accurate image. Please make sure there is no template or placeholder image at the link. Must start with http:// or https://.</p> * @param tag Tag appended to the image that identifies image category or details. There can be multiple tags associated with an image */ data class CatalogsHotelAttributesAllOfMainImage ( /* <p><= 2000 characters</p> <p>The link to the main hotel image. Image should be at least 75x75 pixels to avoid errors. Use the additional_image_link field to add more images of your hotel. The URL of your main_image.link must be accessible by the Pinterest user-agent, and send the accurate image. Please make sure there is no template or placeholder image at the link. Must start with http:// or https://.</p> */ @Json(name = "link") val link: kotlin.String? = null, /* Tag appended to the image that identifies image category or details. There can be multiple tags associated with an image */ @Json(name = "tag") val tag: kotlin.collections.List<kotlin.String>? = null )
0
Java
0
2
dcd328f1e62119774fd8ddbb6e4bad6d7878e898
1,732
pinterest-sdk
MIT License
src/main/kotlin/br/com/jiratorio/repository/LeadTimeConfigRepository.kt
7u4
219,912,318
true
{"Kotlin": 522067, "Dockerfile": 315, "TSQL": 269, "PLSQL": 52}
package br.com.jiratorio.repository import br.com.jiratorio.domain.entity.LeadTimeConfig import org.springframework.data.repository.CrudRepository import org.springframework.stereotype.Repository @Repository interface LeadTimeConfigRepository : CrudRepository<LeadTimeConfig, Long> { fun findByBoardId(boardId: Long): List<LeadTimeConfig> fun findByIdAndBoardId(id: Long, boardId: Long): LeadTimeConfig? }
0
null
0
0
2f788cbcb6c9ef15880af58b90fee356cfe59753
419
jirareport
MIT License
wear/src/main/java/io/homeassistant/companion/android/sensors/SensorReceiver.kt
sviete
238,044,525
true
{"Kotlin": 1797103}
package io.homeassistant.companion.android.sensors import android.annotation.SuppressLint import android.app.NotificationManager import android.content.Context import android.content.Intent import android.media.AudioManager import android.net.wifi.WifiManager import android.os.Build import android.os.PowerManager import dagger.hilt.android.AndroidEntryPoint import io.homeassistant.companion.android.BuildConfig import io.homeassistant.companion.android.common.sensors.AppSensorManager import io.homeassistant.companion.android.common.sensors.AudioSensorManager import io.homeassistant.companion.android.common.sensors.BatterySensorManager import io.homeassistant.companion.android.common.sensors.DNDSensorManager import io.homeassistant.companion.android.common.sensors.LastUpdateManager import io.homeassistant.companion.android.common.sensors.NetworkSensorManager import io.homeassistant.companion.android.common.sensors.NextAlarmManager import io.homeassistant.companion.android.common.sensors.PowerSensorManager import io.homeassistant.companion.android.common.sensors.SensorManager import io.homeassistant.companion.android.common.sensors.SensorReceiverBase import io.homeassistant.companion.android.common.sensors.StepsSensorManager @AndroidEntryPoint class SensorReceiver : SensorReceiverBase() { override val tag: String get() = TAG override val currentAppVersion: String get() = BuildConfig.VERSION_NAME override val managers: List<SensorManager> get() = MANAGERS companion object { const val TAG = "SensorReceiver" private val allManager = listOf( AppSensorManager(), AudioSensorManager(), BatterySensorManager(), BedtimeModeSensorManager(), DNDSensorManager(), HeartRateSensorManager(), LastUpdateManager(), NetworkSensorManager(), NextAlarmManager(), OnBodySensorManager(), PowerSensorManager(), StepsSensorManager(), TheaterModeSensorManager(), WetModeSensorManager() ) val MANAGERS = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) allManager.plus(HealthServicesSensorManager()) else allManager const val ACTION_REQUEST_SENSORS_UPDATE = "io.homeassistant.companion.android.background.REQUEST_SENSORS_UPDATE" fun updateAllSensors(context: Context) { val intent = Intent(context, SensorReceiver::class.java) intent.action = ACTION_UPDATE_SENSORS context.sendBroadcast(intent) } } // Suppress Lint because we only register for the receiver if the android version matches the intent @SuppressLint("InlinedApi") override val skippableActions = mapOf( WifiManager.WIFI_STATE_CHANGED_ACTION to NetworkSensorManager.wifiState.id, "android.app.action.NEXT_ALARM_CLOCK_CHANGED" to NextAlarmManager.nextAlarm.id, Intent.ACTION_SCREEN_OFF to PowerSensorManager.interactiveDevice.id, Intent.ACTION_SCREEN_ON to PowerSensorManager.interactiveDevice.id, PowerManager.ACTION_POWER_SAVE_MODE_CHANGED to PowerSensorManager.powerSave.id, PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED to PowerSensorManager.doze.id, NotificationManager.ACTION_INTERRUPTION_FILTER_CHANGED to DNDSensorManager.dndSensor.id, AudioManager.ACTION_MICROPHONE_MUTE_CHANGED to AudioSensorManager.micMuted.id, AudioManager.ACTION_SPEAKERPHONE_STATE_CHANGED to AudioSensorManager.speakerphoneState.id, AudioManager.RINGER_MODE_CHANGED_ACTION to AudioSensorManager.audioSensor.id, "com.google.android.clockwork.actions.WET_MODE_STARTED" to WetModeSensorManager.wetModeSensor.id, "com.google.android.clockwork.actions.WET_MODE_ENDED" to WetModeSensorManager.wetModeSensor.id ) override fun getSensorSettingsIntent(context: Context, id: String): Intent? = null }
6
Kotlin
0
0
178ccc4c13e9b82d5f6fb1d6ab41209b40d16de0
4,007
AIS-companion-android
Apache License 2.0
src/main/kotlin/com/kryszak/gwatlin/clients/items/ItemsClient.kt
Kryszak
214,791,260
false
null
package com.kryszak.gwatlin.clients.items import com.kryszak.gwatlin.api.ApiLanguage import com.kryszak.gwatlin.api.items.model.item.Item import com.kryszak.gwatlin.http.BaseHttpClient internal class ItemsClient : BaseHttpClient() { private val itemEndpoint = "items" fun getItemIds(): List<Int> { return getRequest(itemEndpoint) } fun getItems(ids: List<Int>, language: ApiLanguage?): List<Item> { val params = ids.joinToString(",") return getRequest("$itemEndpoint?ids=$params", language) } }
10
Kotlin
0
3
e86b74305df2b4af8deda8c0a5d2929d8110e41d
544
gwatlin
MIT License
app/src/main/java/tech/thdev/githubusersearch/util/LifecycleExtensionsUtil.kt
taehwandev
141,778,287
false
null
@file:Suppress("UNCHECKED_CAST") package tech.thdev.githubusersearch.util import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider import android.arch.lifecycle.ViewModelProviders import android.support.v4.app.Fragment import android.support.v4.app.FragmentActivity fun <T : ViewModel> Class<T>.inject(fragment: Fragment, customKey: String = "", onCreateViewModel: () -> T): T = ViewModelProviders.of(fragment, createViewModel(onCreateViewModel)).run { if (customKey.isNotEmpty()) { this.get(customKey, this@inject) } else { this.get(this@inject) } } fun <T : ViewModel> Class<T>.inject(fragmentActivity: FragmentActivity, customKey: String = "", onCreateViewModel: () -> T): T = ViewModelProviders.of(fragmentActivity, createViewModel(onCreateViewModel)).run { if (customKey.isNotEmpty()) { this.get(customKey, this@inject) } else { get(this@inject) } } private fun <T : ViewModel> createViewModel(onCreateViewModel: () -> T) = object : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return onCreateViewModel() as T } }
0
Kotlin
0
5
0478ba09e75f9e58d2bc312fdd0ece583a8b1feb
1,286
GithubUserSearch
Apache License 2.0
increase-java-core/src/main/kotlin/com/increase/api/services/async/InboundWireTransferServiceAsync.kt
Increase
614,596,462
false
{"Kotlin": 10835729, "Shell": 3638, "Dockerfile": 399}
// File generated from our OpenAPI spec by Stainless. @file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 package com.increase.api.services.async import com.increase.api.core.RequestOptions import com.increase.api.models.InboundWireTransfer import com.increase.api.models.InboundWireTransferListPageAsync import com.increase.api.models.InboundWireTransferListParams import com.increase.api.models.InboundWireTransferRetrieveParams import java.util.concurrent.CompletableFuture interface InboundWireTransferServiceAsync { /** Retrieve an Inbound Wire Transfer */ @JvmOverloads fun retrieve( params: InboundWireTransferRetrieveParams, requestOptions: RequestOptions = RequestOptions.none() ): CompletableFuture<InboundWireTransfer> /** List Inbound Wire Transfers */ @JvmOverloads fun list( params: InboundWireTransferListParams, requestOptions: RequestOptions = RequestOptions.none() ): CompletableFuture<InboundWireTransferListPageAsync> }
0
Kotlin
0
3
0df00547244c75a524bf33646de61aea3c82aca7
1,049
increase-java
Apache License 2.0
src/tutorials/kotlin/007_procedures.kt
urosjarc
747,245,291
false
{"Kotlin": 746524, "Shell": 1030}
package procedures import com.urosjarc.dbmessiah.domain.Table import com.urosjarc.dbmessiah.impl.mssql.MssqlSchema import com.urosjarc.dbmessiah.impl.mssql.MssqlSerializer import com.urosjarc.dbmessiah.impl.mssql.MssqlService import com.urosjarc.dbmessiah.serializers.BasicTS import java.util.* import kotlin.test.assertEquals /** * It's not best practice to have any logic inside database. * The ease of maintaining and understanding Kotlin code will be always superior to any code written inside database procedure. * It's ok to have small number of procedures inside you project but please of the love of Clean Architecture and Uncle Bob, * do write your core logic with proper programming language. */ /** * Define your domain classes (tables)... */ data class Parent(var pk: Int? = null, var value: String) /** * Define Procedures with arguments as inputs... */ data class Procedure0(val value: Int) data class Procedure1(val value: Int) /** * Define your database schema with registered procedures... * In this demonstration I will be using MS SQL server since sqlite does not have procedures * and postgresql support only functions. */ val schema = MssqlSchema( name = "procedures", tables = listOf(Table(Parent::pk)), procedures = listOf(Procedure0::class, Procedure1::class) // Register procedures here... ) val service = MssqlService( ser = MssqlSerializer(schemas = listOf(schema), globalSerializers = BasicTS.postgresql), config = Properties().apply { this["jdbcUrl"] = "jdbc:sqlserver://localhost:1433;encrypt=false;" this["username"] = "sa" this["password"] = "Root_root1" } ) fun procedures() { service.autocommit { /** * Setup database */ it.schema.create(schema = schema) it.table.drop<Parent>() it.table.create<Parent>() /** * Create some elements */ val parent0 = Parent(value = "asdf") val parent1 = Parent(value = "xxxx") it.row.insert(row = parent0) it.row.insert(row = parent1) /** * To create the procedure you have to provide the class which will hold input values and * callback where you provide execution body for the procedure. Database serializer * will create proper SQL in background. Note that some databases have no support for the procedures. */ it.procedure.create<Procedure0> { """SELECT * FROM procedures.Parent where pk = @${Procedure0::value.name};""" } /** * Call procedure by providing created object for that specific procedure * and output class that you want to receive back. */ val parents0 = it.procedure.call(procedure = Procedure0(value = 1), Parent::class) assertEquals(parents0, listOf(parent0)) /** * Create procedure with multiple output */ it.procedure.create<Procedure1> { """ SELECT * FROM procedures.Parent where pk = @${Procedure1::value.name}; SELECT * FROM procedures.Parent; """ } /** * Call procedure and get result. * Note that now that you want to receive multiple outputs the returning structure is matrix where each row represents * the results from that specific output. */ val parents1: MutableList<List<Any>> = it.procedure.call(procedure = Procedure1(value = 1), Parent::class, Parent::class) assertEquals(parents1[0], listOf(parent0)) assertEquals(parents1[1], listOf(parent0, parent1)) } }
0
Kotlin
0
16
bb334a4e606e2c1906d119625aeaa57149d5e1cd
3,633
db-messiah
Apache License 2.0
app/src/main/java/com/ozcanalasalvar/bitcointicker/data/local/db/AppDao.kt
OzcanAlasalvar
297,089,487
false
null
package com.ozcanalasalvar.bitcointicker.data.local.db import androidx.room.* import com.ozcanalasalvar.bitcointicker.data.model.SimpleModel @Dao interface AppDao { @Insert(onConflict = OnConflictStrategy.IGNORE) fun insertAll(cities: List<SimpleModel>) @Query("SELECT *FROM coinModel") fun fetchCoins(): List<SimpleModel> @Query("Select *FROM coinModel WHERE name LIKE :query or symbol LIKE :query") fun fetchCoinByQuery(query: String): List<SimpleModel> @Query("DELETE FROM coinModel") fun deleteDB() }
0
Kotlin
0
1
c9335dbd9e4022386cad3810b65e13058e096c5c
543
BitcoinTicker
Apache License 2.0
app/src/main/java/com/balocco/androidnavigation/di/ViewModelFactoryModule.kt
AlexBalo
286,418,679
false
null
package com.balocco.androidnavigation.di import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.balocco.androidcomponents.di.ApplicationScope import com.balocco.androidnavigation.common.viewmodel.ViewModelFactory import dagger.Module import dagger.Provides import javax.inject.Provider /* Module that contains dependencies for view models. */ @Module class ViewModelFactoryModule { @Provides @ApplicationScope fun provideViewModelFactory(providerMap: Map<Class<out ViewModel>, Provider<ViewModel>>): ViewModelProvider.Factory = ViewModelFactory(providerMap) }
0
Kotlin
0
0
24e98d71f252cd3f0f49e8d52ec14e2bcae00b8f
622
AndroidNavigation
Apache License 2.0
data/src/main/java/com/yapp/gallery/data/source/local/record/ExhibitRecordLocalDataSource.kt
Team-Artie
624,497,647
false
null
package com.yapp.gallery.data.source.local.record import com.yapp.gallery.data.room.post.TempPost import kotlinx.coroutines.flow.Flow interface ExhibitRecordLocalDataSource { fun insertTempPost( postId: Long, name: String, categoryId: Long, postDate: String, postLink: String?, ): Flow<Long> fun updateTempPost( postId: Long, name: String, categoryId: Long, postDate: String, postLink: String?, ): Flow<Long> fun getTempPost() : Flow<TempPost> fun deleteTempPost() : Flow<Long> }
0
Kotlin
0
0
18ed241938fdd084e2ff28a7415380846fc665f7
522
Artie_Android
Apache License 2.0
app/src/main/java/com/tcc/alif/data/api/CepService.kt
Limatucano
343,949,865
false
null
package com.tcc.alif.data.api import com.tcc.alif.data.model.AddressResponse import retrofit2.http.GET import retrofit2.http.Path interface CepService { @GET("{cep}/json/") suspend fun getAddress( @Path("cep") cep : String ) : AddressResponse }
0
Kotlin
0
4
a5774ef6e248f94d9e886bda5fcb972af6056c23
267
alif
MIT License
projects/club/test/integration/api/UserApiTest.kt
csieflyman
359,559,498
false
{"Kotlin": 785294, "JavaScript": 17435, "HTML": 6167, "PLpgSQL": 5563, "Dockerfile": 126}
/* * Copyright (c) 2021. fanpoll All rights reserved. */ package integration.api import fanpoll.club.ClubAuth import fanpoll.club.ClubUserRole import fanpoll.club.ClubUserType import fanpoll.club.user.domain.Gender import fanpoll.club.user.dtos.CreateUserForm import fanpoll.club.user.dtos.UpdateUserForm import fanpoll.club.user.dtos.UpdateUserPasswordForm import fanpoll.club.user.dtos.UserDTO import fanpoll.infra.auth.AuthConst import fanpoll.infra.auth.provider.UserRunAsAuthProvider import fanpoll.infra.auth.provider.UserRunAsToken import fanpoll.infra.base.response.InfraResponseCode import fanpoll.infra.i18n.Lang import integration.util.* import io.github.oshai.kotlinlogging.KotlinLogging import io.kotest.core.spec.style.scopes.FunSpecContainerScope import io.ktor.client.HttpClient import io.ktor.client.request.* import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode import io.ktor.http.contentType import kotlinx.serialization.json.jsonPrimitive import java.util.* import kotlin.test.assertEquals import kotlin.test.assertNotNull val userApiTest: suspend FunSpecContainerScope.(HttpClient) -> Unit = { client -> val logger = KotlinLogging.logger {} lateinit var userId: UUID lateinit var runAsToken: UserRunAsToken val userAdmin1Form = CreateUserForm( "<EMAIL>", "123456", true, "admin1", Gender.Male, 2000, "<EMAIL>", "0987654321", Lang.zh_TW, setOf(ClubUserRole.Admin, ClubUserRole.User) ) test("create admin user") { val createUserResponse = client.post(mergeRootPath("/users")) { contentType(ContentType.Application.Json) header(AuthConst.API_KEY_HEADER_NAME, getServiceApiKey(ClubAuth.RootSource)) setBody(userAdmin1Form) } assertEquals(HttpStatusCode.OK, createUserResponse.status) val userIdStr = createUserResponse.dataJsonObject()["id"]?.jsonPrimitive?.content assertNotNull(userIdStr) userId = UUID.fromString(userIdStr) runAsToken = UserRunAsToken(ClubUserType.User, userId) val getAdminResponse = client.get(mergeRootPath("/users")) { header(AuthConst.API_KEY_HEADER_NAME, getRunAsKey(ClubAuth.Android)) header(UserRunAsAuthProvider.RUN_AS_TOKEN_HEADER_NAME, runAsToken.value) } assertEquals(HttpStatusCode.OK, getAdminResponse.status) assertEquals(1, getAdminResponse.dataJsonArray().size) val userDTO = getAdminResponse.dataList<UserDTO>().first() assertEquals(userAdmin1Form.account, userDTO.account) } test("create user with duplicated account") { val createUserResponse = client.post(mergeRootPath("/users")) { contentType(ContentType.Application.Json) header(AuthConst.API_KEY_HEADER_NAME, getServiceApiKey(ClubAuth.RootSource)) setBody(userAdmin1Form) } assertEquals(HttpStatusCode.Conflict, createUserResponse.status) assertEquals(InfraResponseCode.ENTITY_ALREADY_EXISTS, createUserResponse.code()) } test("update user data") { val updateUserResponse = client.put(mergeRootPath("/users/$userId")) { contentType(ContentType.Application.Json) header(AuthConst.API_KEY_HEADER_NAME, getRunAsKey(ClubAuth.Android)) header(UserRunAsAuthProvider.RUN_AS_TOKEN_HEADER_NAME, runAsToken.value) setBody(UpdateUserForm(userId, enabled = false)) } assertEquals(HttpStatusCode.OK, updateUserResponse.status) val getUserResponse = client.get(mergeRootPath("/users?q_filter=[enabled = false]")) { header(AuthConst.API_KEY_HEADER_NAME, getRunAsKey(ClubAuth.Android)) header(UserRunAsAuthProvider.RUN_AS_TOKEN_HEADER_NAME, runAsToken.value) } assertEquals(HttpStatusCode.OK, getUserResponse.status) assertEquals(1, getUserResponse.dataJsonArray().size) val userDTO = getUserResponse.dataList<UserDTO>().first() assertEquals(userAdmin1Form.account, userDTO.account) assertEquals(false, userDTO.enabled) } test("update my password with incorrect old password") { val response = client.put(mergeRootPath("/users/myPassword")) { contentType(ContentType.Application.Json) header(AuthConst.API_KEY_HEADER_NAME, getRunAsKey(ClubAuth.Android)) header(UserRunAsAuthProvider.RUN_AS_TOKEN_HEADER_NAME, runAsToken.value) setBody(UpdateUserPasswordForm("incorrectOldPassword", "<PASSWORD>")) } assertEquals(HttpStatusCode.Unauthorized, response.status) assertEquals(InfraResponseCode.AUTH_BAD_PASSWORD, response.code()) } test("update my password with correct old password") { val response = client.put(mergeRootPath("/users/myPassword")) { contentType(ContentType.Application.Json) header(AuthConst.API_KEY_HEADER_NAME, getRunAsKey(ClubAuth.Android)) header(UserRunAsAuthProvider.RUN_AS_TOKEN_HEADER_NAME, runAsToken.value) setBody(UpdateUserPasswordForm(userAdmin1Form.password, "<PASSWORD>")) } assertEquals(HttpStatusCode.OK, response.status) } }
1
Kotlin
9
74
1a7d54115dbc42c6a02230f527d9ad56862b4a0b
5,203
multi-projects-architecture-with-Ktor
MIT License
app/src/main/java/org/haidy/servify/presentation/screens/bookingTrack/BookingTrackRoute.kt
HaidyAbuGom3a
805,534,454
false
{"Kotlin": 702248}
package org.haidy.servify.presentation.screens.bookingTrack import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable import org.haidy.servify.app.navigation.ServifyDestination private const val ROUTE = ServifyDestination.BOOKING_TRACK fun NavController.navigateToBookingTrack(clearBackStack: Boolean = false) { navigate(ROUTE){ if(clearBackStack){ popUpTo(graph.id) { inclusive = true } } } } fun NavGraphBuilder.bookingTrackRoute(){ composable(ROUTE){ BookingTrackScreen() } }
0
Kotlin
0
2
8c2ba73cea5d29cc2ef7048d832f8ecea13f34ee
622
Servify
Apache License 2.0
backend/mlreef-rest/src/main/kotlin/com/mlreef/rest/config/SchedulerConfig.kt
Wesamalmashayekh
402,921,049
true
{"Kotlin": 1691169, "JavaScript": 1365079, "Python": 165260, "SCSS": 130450, "Shell": 122742, "Ruby": 100068, "TypeScript": 51701, "ANTLR": 27697, "CSS": 18550, "Dockerfile": 17453, "HTML": 8484, "PLpgSQL": 3248, "Batchfile": 310}
package com.mlreef.rest.config import org.springframework.beans.factory.annotation.Value import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.scheduling.TaskScheduler import org.springframework.scheduling.annotation.EnableScheduling import org.springframework.scheduling.annotation.SchedulingConfigurer import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler import org.springframework.scheduling.config.ScheduledTaskRegistrar @Configuration @EnableScheduling class SchedulerConfig( @Value("\${mlreef.scheduler.pool-size:100}") val poolSize: Int ): SchedulingConfigurer { override fun configureTasks(taskRegistrar: ScheduledTaskRegistrar) { taskRegistrar.setTaskScheduler(taskScheduler()) } @Bean fun taskScheduler(): TaskScheduler { val scheduler = ThreadPoolTaskScheduler() scheduler.threadNamePrefix = "mlreef-task-scheduler" scheduler.poolSize = poolSize scheduler.initialize() return scheduler } }
0
null
0
1
e7fec51e75e5fc74211e78c3228ba7bdf076f832
1,079
mlreef
MIT License
samples/kaspresso-sample/src/androidTest/kotlin/com/kaspersky/kaspressample/device_tests/DeviceLanguageSampleTest.kt
KasperskyLab
208,070,025
false
null
package com.kaspersky.kaspressample.device_tests import android.Manifest import androidx.test.rule.ActivityTestRule import androidx.test.rule.GrantPermissionRule import com.kaspersky.kaspressample.MainActivity import com.kaspersky.kaspressample.screen.MainScreen import com.kaspersky.kaspresso.testcases.api.testcase.TestCase import java.util.Locale import org.junit.Rule import org.junit.Test class DeviceLanguageSampleTest : TestCase() { companion object { private const val SLEEP_TIME: Long = 2000 } @get:Rule val runtimePermissionRule: GrantPermissionRule = GrantPermissionRule.grant( Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE ) @get:Rule val activityTestRule = ActivityTestRule(MainActivity::class.java, true, true) private lateinit var default: Locale @Test fun languageSampleTest() { before { default = device.targetContext.resources.configuration.locales[0] }.after { device.language.switchInApp(default) }.run { step("Change locale to english") { device.language.switchInApp(Locale.ENGLISH) // it's so important to reload current active Activity // you can do it using activityTestRule or manipulating in the Application through great Kaspresso activityTestRule.finishActivity() activityTestRule.launchActivity(null) Thread.sleep(SLEEP_TIME) } step("Start MainScreen in default locale") { MainScreen { simpleButton { isVisible() containsText("Simple fragment") } } } step("Change locale to russian") { device.language.switchInApp(Locale("ru")) // it's so important to reload current active Activity // you can do it using activityTestRule or manipulating in the Application through great Kaspresso activityTestRule.finishActivity() activityTestRule.launchActivity(null) Thread.sleep(SLEEP_TIME) } step("Start MainScreen in russian locale") { MainScreen { simpleButton { isVisible() containsText("Простой пример") } } } } } }
35
Kotlin
101
1,295
2255c921e61550c97545a19eda25c81be5e3c5ee
2,540
Kaspresso
Apache License 2.0
app/src/main/java/com/atakan/mainserver/service/BroadcastReceiver.kt
atakanakin
677,015,233
false
null
package com.atakan.mainserver.service import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log import com.atakan.mainserver.constants.CURR1 import com.atakan.mainserver.constants.CURR2 import com.atakan.mainserver.constants.CURR3 import com.atakan.mainserver.constants.PACKAGE_NAME import com.atakan.mainserver.constants.PID import com.atakan.mainserver.constants.RATE1 import com.atakan.mainserver.constants.RATE2 import com.atakan.mainserver.constants.RATE3 import com.atakan.mainserver.constants.TIME import com.atakan.mainserver.data.model.Client import com.atakan.mainserver.data.model.RecentClient import com.atakan.mainserver.presentation.ClientDataViewModel import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class BroadcastReceiver: BroadcastReceiver() { @Inject lateinit var viewModel: ClientDataViewModel override fun onReceive(context: Context?, intent: Intent?) { RecentClient.client = Client( intent?.getStringExtra(PACKAGE_NAME), intent?.getStringExtra(PID), intent?.getStringExtra(CURR1), intent?.getStringExtra(CURR2), intent?.getStringExtra(CURR3), intent?.getDoubleExtra(RATE1, 0.0), intent?.getDoubleExtra(RATE2, 0.0), intent?.getDoubleExtra(RATE3, 0.0), intent?.getStringExtra(TIME), "Broadcast" ) viewModel.updateClientData(RecentClient.client!!) Log.d("Broadcast", "Package Received.") } }
0
Kotlin
0
0
7103458cd43a649a46a00017778951104437c7cf
1,592
Server
MIT License
src/main/java/io/ejekta/kambrikx/ext/ExtApi.kt
ejektaflex
273,374,760
false
null
package io.ejekta.kambrikx.ext import io.ejekta.kambrik.Kambrik import io.ejekta.kambrikx.recipe.KambrikSpecialRecipeApi private val specialRecipeApi = KambrikSpecialRecipeApi() val Kambrik.SpecialRecipes: KambrikSpecialRecipeApi get() = specialRecipeApi
1
Kotlin
2
8
4689a76f64968e463b3332f6a6534656ca85af24
261
Kambrik
MIT License
api/webflux/src/main/kotlin/com/rafael/apiwebflux/http/EligibleController.kt
RafaelPereiraSantos
278,705,536
false
null
package com.rafael.apiwebflux.http import com.rafael.apiwebflux.service.EligibleSearchService import com.rafael.common.models.Eligible import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestHeader import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import java.util.* @RestController class EligibleController(private val eligibleSearchService: EligibleSearchService) { @GetMapping("/web-flux-controller/eligibility") fun search( @RequestHeader("x-session") session: String, @RequestParam email: String?, @RequestParam token: String?, @RequestParam("personal_document") personalDocument: String? ): ResponseEntity<Eligible> { println(session) val result = eligibleSearchService .searchBy(email, token, personalDocument) return result.uniqueResult() ?.let { eligibility -> ResponseEntity.ok(eligibility) } ?: ResponseEntity.notFound().build() } }
0
Kotlin
0
2
557e8972f7125fea13ed574b8b9ba692b6b2464a
1,131
signup-service
MIT License
app/src/main/java/com/gloryfootwarefsm/features/newcollection/model/NewCollectionListResponseModel.kt
DebashisINT
608,204,106
false
null
package com.gloryfootwarefsm.features.newcollection.model import com.gloryfootwarefsm.app.domain.CollectionDetailsEntity import com.gloryfootwarefsm.base.BaseResponse import com.gloryfootwarefsm.features.shopdetail.presentation.model.collectionlist.CollectionListDataModel /** * Created by Saikat on 15-02-2019. */ class NewCollectionListResponseModel : BaseResponse() { //var collection_list: ArrayList<CollectionListDataModel>? = null var collection_list: ArrayList<CollectionDetailsEntity>? = null }
0
Kotlin
0
0
639d492a5f6e33c77f397a7ad52a34545519c37b
514
GloryFootware
Apache License 2.0
lib/src/main/java/quevedo/leandro/madeeasy/swipetorefresh/delegate/OnStepCallbackDelegate.kt
LeandroSQ
386,032,019
false
null
package quevedo.leandro.madeeasy.swipetorefresh.delegate internal typealias OnStepCallback = (step: Float) -> Unit
0
Kotlin
0
0
d154ca00349a00c6383255ac819a81286f65bad5
115
swipe-to-refresh-made-easy
MIT License
app/src/main/java/app/jerboa/freetypeandroid/ui/theme/Color.kt
Jerboa-app
566,342,268
false
{"Kotlin": 15972, "C++": 14381, "CMake": 2197, "C": 263}
package app.jerboa.freetypeandroid.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFFFFFFFF)
0
Kotlin
0
1
9cdb6923a0853fddf51ed83d60eda2d9a382bb2a
221
FreeTypeAndroid
MIT License
app/src/main/kotlin/net/tlalka/fiszki/view/activities/TestListActivity.kt
jtlalka
52,197,843
false
null
package net.tlalka.fiszki.view.activities import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.ListView import butterknife.BindView import net.tlalka.fiszki.R import net.tlalka.fiszki.domain.controllers.ListController import net.tlalka.fiszki.model.dto.parcel.LessonDto import net.tlalka.fiszki.model.entities.Lesson import net.tlalka.fiszki.view.adapters.LessonsAdapter import net.tlalka.fiszki.view.navigations.Navigator import javax.inject.Inject class LessonListActivity : BasePageActivity(), AdapterView.OnItemClickListener { @BindView(R.id.lesson_list_view) lateinit var listView: ListView @Inject lateinit var listController: ListController @Inject lateinit var navigator: Navigator public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) super.setContentView(R.layout.lesson_list_activity) super.activityComponent.inject(this) initLessonsList() } private fun initLessonsList() { listView.adapter = LessonsAdapter(this, listController.getLessonList()) listView.onItemClickListener = this } override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) { val lesson = parent.getItemAtPosition(position) as Lesson navigator.openLessonActivity(this, LessonDto(lesson, position + 1)) navigator.finish(this) } }
0
Kotlin
0
2
7e7c2aba5d9a1634a5b295319ec1bb5a4b5a7aa0
1,460
fiszki
MIT License
src/main/kotlin/com/example/parking/exit/ExitService.kt
johnGachihi
365,287,855
false
null
package com.example.parking.exit import com.example.parking.models.FinishedVisit import com.example.parking.models.OngoingVisit import com.example.parking.models.Payment import com.example.parking.util.Minutes import com.example.parking.visit.InvalidTicketCodeException import com.example.parking.visit.FinishedVisitRepo import com.example.parking.visit.OngoingVisitRepo import org.springframework.stereotype.Service import java.time.Instant import java.time.temporal.ChronoUnit import kotlin.math.absoluteValue @Service class ExitService( private val registeredVehicleRepository: RegisteredVehicleRepository, private val ongoingVisitRepo: OngoingVisitRepo, // private val finishedVisitRepo: FinishedVisitRepo, //combine? private val paymentService: PaymentService ) { fun exit(ticketCode: Long) { val ongoingVisit = ongoingVisitRepo.findByTicketCode(ticketCode) ?: throw InvalidTicketCodeException( "The provided ticket code is not in use. Ticket code: $ticketCode") if (registeredVehicleRepository.existsByTicketCode(ticketCode)) { markOnGoingEntryAsFinished(ongoingVisit) return } val parkingFee = paymentService.calculateFee( getTimeOfStay(ongoingVisit)) if (parkingFee == 0.0) { markOnGoingEntryAsFinished(ongoingVisit) return } if (ongoingVisit.payments.isEmpty()) { throw UnservicedParkingBill() } val latestPayment = getLatestPayment(ongoingVisit)!! if (paymentService.paymentExpired(latestPayment)) { throw UnservicedParkingBill("Latest payment expired") } markOnGoingEntryAsFinished(ongoingVisit) } private fun markOnGoingEntryAsFinished(ongoingVisit: OngoingVisit) { val finishedVisit = FinishedVisit().apply { entryTime = ongoingVisit.entryTime this.ticketCode = ongoingVisit.ticketCode this.payments = payments } finishedVisitRepo.save(finishedVisit) ongoingVisitRepo.delete(ongoingVisit) } private fun getTimeOfStay(ongoingVisit: OngoingVisit): Minutes = Minutes(Instant.now().until(ongoingVisit.entryTime, ChronoUnit.MINUTES).absoluteValue) // TODO: Added .absoluteValue. See what was happening before private fun getLatestPayment(ongoingVisit: OngoingVisit): Payment? = ongoingVisit.payments.maxByOrNull { it.madeAt } } class UnservicedParkingBill( message: String? = null ) : Exception(message)
0
Kotlin
0
0
d2f1cb4af890f0e14faf57d26327115edfb73e5e
2,562
parking-spring
MIT License
src/main/kotlin/com/example/parking/exit/ExitService.kt
johnGachihi
365,287,855
false
null
package com.example.parking.exit import com.example.parking.models.FinishedVisit import com.example.parking.models.OngoingVisit import com.example.parking.models.Payment import com.example.parking.util.Minutes import com.example.parking.visit.InvalidTicketCodeException import com.example.parking.visit.FinishedVisitRepo import com.example.parking.visit.OngoingVisitRepo import org.springframework.stereotype.Service import java.time.Instant import java.time.temporal.ChronoUnit import kotlin.math.absoluteValue @Service class ExitService( private val registeredVehicleRepository: RegisteredVehicleRepository, private val ongoingVisitRepo: OngoingVisitRepo, // private val finishedVisitRepo: FinishedVisitRepo, //combine? private val paymentService: PaymentService ) { fun exit(ticketCode: Long) { val ongoingVisit = ongoingVisitRepo.findByTicketCode(ticketCode) ?: throw InvalidTicketCodeException( "The provided ticket code is not in use. Ticket code: $ticketCode") if (registeredVehicleRepository.existsByTicketCode(ticketCode)) { markOnGoingEntryAsFinished(ongoingVisit) return } val parkingFee = paymentService.calculateFee( getTimeOfStay(ongoingVisit)) if (parkingFee == 0.0) { markOnGoingEntryAsFinished(ongoingVisit) return } if (ongoingVisit.payments.isEmpty()) { throw UnservicedParkingBill() } val latestPayment = getLatestPayment(ongoingVisit)!! if (paymentService.paymentExpired(latestPayment)) { throw UnservicedParkingBill("Latest payment expired") } markOnGoingEntryAsFinished(ongoingVisit) } private fun markOnGoingEntryAsFinished(ongoingVisit: OngoingVisit) { val finishedVisit = FinishedVisit().apply { entryTime = ongoingVisit.entryTime this.ticketCode = ongoingVisit.ticketCode this.payments = payments } finishedVisitRepo.save(finishedVisit) ongoingVisitRepo.delete(ongoingVisit) } private fun getTimeOfStay(ongoingVisit: OngoingVisit): Minutes = Minutes(Instant.now().until(ongoingVisit.entryTime, ChronoUnit.MINUTES).absoluteValue) // TODO: Added .absoluteValue. See what was happening before private fun getLatestPayment(ongoingVisit: OngoingVisit): Payment? = ongoingVisit.payments.maxByOrNull { it.madeAt } } class UnservicedParkingBill( message: String? = null ) : Exception(message)
0
Kotlin
0
0
d2f1cb4af890f0e14faf57d26327115edfb73e5e
2,562
parking-spring
MIT License
app/src/main/java/com/github/vitorfg8/popcorn/home/populartvshows/ui/PopularTvShowsAdapter.kt
vitorfg8
677,008,016
false
{"Kotlin": 77726}
package com.github.vitorfg8.popcorn.home.populartvshows.ui import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.github.vitorfg8.popcorn.databinding.ItemPosterBinding import com.github.vitorfg8.popcorn.home.populartvshows.ui.dataUi.PopularTvShowDataUi class PopularTvShowsAdapter(private val clickListener: (movieId: Int) -> Unit) : ListAdapter<PopularTvShowDataUi, PopularTvShowsAdapter.ViewHolder>(PopularTvShowsDiffUtils()) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val binding = ItemPosterBinding.inflate( LayoutInflater.from(parent.context), parent, false ) return ViewHolder(binding) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(getItem(position), clickListener) } class ViewHolder(private val binding: ItemPosterBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(popularMovie: PopularTvShowDataUi, clickListener: (movieId: Int) -> Unit) { binding.textMovieTitle.text = popularMovie.title Glide.with(binding.imageMoviePoster.context).load(popularMovie.posterUrl) .into(binding.imageMoviePoster) binding.root.setOnClickListener { clickListener.invoke(popularMovie.id) } } } class PopularTvShowsDiffUtils : DiffUtil.ItemCallback<PopularTvShowDataUi>() { override fun areItemsTheSame( oldItem: PopularTvShowDataUi, newItem: PopularTvShowDataUi ): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame( oldItem: PopularTvShowDataUi, newItem: PopularTvShowDataUi ): Boolean { return oldItem == newItem } } }
0
Kotlin
0
0
755862675a4c2ad44c3282fc38a422dd03072ad4
2,034
Popcorn
MIT License
src/main/java/de/mrapp/textmining/util/tokenizer/AbstractTokenizer.kt
michael-rapp
111,042,013
false
null
/* * Copyright 2017 - 2019 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package de.mrapp.textmining.util.tokenizer import de.mrapp.textmining.util.Token /** * An abstract base class for all tokenizers. * * @param TokenType The type of the tokens, the texts are split into * @author <NAME> * @since 1.2.0 */ abstract class AbstractTokenizer<TokenType : Token> : Tokenizer<TokenType> { /** * Adds a new [token] to a [map], if it is not already contained. Otherwise, the token's * [position] is added to the existing token. A [tokenFactory] for converting the given [token] * to the type [T] must be provided. * * @param T The type of the token */ protected fun <T : Token> addToken(map: MutableMap<String, T>, token: String, position: Int, tokenFactory: (String, Int) -> T) { var existingToken = map[token] if (existingToken == null) { if (token.isNotEmpty()) { existingToken = tokenFactory.invoke(token, position) map[token] = existingToken } } else { existingToken.addPosition(position) } } /** * The method, which is invoked on subclasses in order to tokenize a specific [text]. The tokens * should be added to the given [map]. */ protected abstract fun onTokenize(text: String, map: MutableMap<String, TokenType>) override fun tokenize(text: CharSequence): Collection<TokenType> { if (text.isNotEmpty()) { val tokens = HashMap<String, TokenType>() onTokenize(text.toString(), tokens) return tokens.values } return emptyList() } }
0
Kotlin
0
1
2103d68964608780ca1d572887ba57c595adcb7b
2,233
TextMiningUtil
Apache License 2.0
features/timers/data/src/main/kotlin/org/timemates/backend/timers/data/db/TableTimersSessionUsersDataSource.kt
timemates
575,534,781
false
{"Kotlin": 377244, "Dockerfile": 859}
package org.timemates.backend.timers.data.db import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq import org.jetbrains.exposed.sql.SqlExpressionBuilder.lessEq import org.jetbrains.exposed.sql.transactions.transaction import org.timemates.backend.exposed.suspendedTransaction import org.timemates.backend.exposed.update import org.timemates.backend.exposed.upsert import org.timemates.backend.pagination.Ordering import org.timemates.backend.pagination.Page import org.timemates.backend.pagination.PageToken import org.timemates.backend.timers.data.db.entities.DbSessionUser import org.timemates.backend.timers.data.db.entities.TimerParticipantPageToken import org.timemates.backend.timers.data.db.tables.TimersSessionUsersTable import org.timemates.backend.timers.data.mappers.TimerSessionMapper class TableTimersSessionUsersDataSource( private val database: Database, private val timerSessionMapper: TimerSessionMapper, private val json: Json = Json, ) { init { transaction(database) { SchemaUtils.create(TimersSessionUsersTable) } } suspend fun isAnyUserActiveAfter( timerId: Long, afterTime: Long, ): Boolean = suspendedTransaction(database) { TimersSessionUsersTable.select { TimersSessionUsersTable.TIMER_ID eq timerId and (TimersSessionUsersTable.LAST_ACTIVITY_TIME greater afterTime) }.empty().not() } suspend fun getUsers( timerId: Long, pageToken: PageToken?, afterTime: Long, pageSize: Int, ): Page<DbSessionUser> = suspendedTransaction(database) { val currentPage: TimerParticipantPageToken? = pageToken?.forInternal()?.let(json::decodeFromString) // TODO join and sort by name val result = TimersSessionUsersTable.select { TimersSessionUsersTable.TIMER_ID eq timerId and (TimersSessionUsersTable.LAST_ACTIVITY_TIME greater afterTime) and (TimersSessionUsersTable.USER_ID greater (currentPage?.lastReceivedUserId ?: 0)) }.orderBy(TimersSessionUsersTable.USER_ID, SortOrder.ASC) .limit(pageSize) .map(timerSessionMapper::resultRowToSessionUser) val nextPageToken = result.lastOrNull()?.userId?.let { TimerParticipantPageToken(it) .let(json::encodeToString) .let(PageToken.Companion::toGive) } ?: pageToken return@suspendedTransaction Page( value = result, nextPageToken = nextPageToken, ordering = Ordering.ASCENDING, ) } suspend fun getUsersCount( timerId: Long, afterTime: Long, ): Int = suspendedTransaction(database) { TimersSessionUsersTable.select { TimersSessionUsersTable.TIMER_ID eq timerId and (TimersSessionUsersTable.LAST_ACTIVITY_TIME greater afterTime) }.count().toInt() } suspend fun assignUser( timerId: Long, userId: Long, isConfirmed: Boolean, lastActivityTime: Long, ): Unit = suspendedTransaction(database) { val condition = Op.build { TimersSessionUsersTable.TIMER_ID eq timerId and (TimersSessionUsersTable.USER_ID eq userId) } TimersSessionUsersTable.upsert(condition = condition) { statement, _ -> statement[TIMER_ID] = timerId statement[USER_ID] = userId statement[IS_CONFIRMED] = isConfirmed statement[LAST_ACTIVITY_TIME] = lastActivityTime } } suspend fun updateLastActivityTime( timerId: Long, userId: Long, time: Long, ): Unit = suspendedTransaction(database) { val condition = TimersSessionUsersTable.USER_ID eq userId and (TimersSessionUsersTable.TIMER_ID eq timerId) TimersSessionUsersTable.update(condition) { it[LAST_ACTIVITY_TIME] = time } } suspend fun isEveryoneConfirmed(timerId: Long): Boolean = suspendedTransaction(database) { TimersSessionUsersTable.select { TimersSessionUsersTable.TIMER_ID eq timerId and not(TimersSessionUsersTable.IS_CONFIRMED) }.empty() } suspend fun removeUsersBefore(time: Long): Unit = suspendedTransaction(database) { TimersSessionUsersTable.deleteWhere { LAST_ACTIVITY_TIME lessEq time } } suspend fun removeNotConfirmedUsers(timerId: Long): Unit = suspendedTransaction(database) { TimersSessionUsersTable.deleteWhere { TIMER_ID lessEq timerId and not(IS_CONFIRMED) } } suspend fun unassignUser( timerId: Long, userId: Long, ): Unit = suspendedTransaction(database) { TimersSessionUsersTable.deleteWhere { TIMER_ID eq timerId and (USER_ID eq userId) } } suspend fun getTimerIdFromUserSession(userId: Long, afterTime: Long): Long? = suspendedTransaction(database) { TimersSessionUsersTable.select { TimersSessionUsersTable.USER_ID eq userId and (TimersSessionUsersTable.LAST_ACTIVITY_TIME greater afterTime) }.singleOrNull()?.getOrNull(TimersSessionUsersTable.TIMER_ID) } suspend fun setAllAsNotConfirmed( timerId: Long, ): Unit = suspendedTransaction(database) { TimersSessionUsersTable.update(TimersSessionUsersTable.TIMER_ID eq timerId) { it[IS_CONFIRMED] = false } } }
13
Kotlin
1
8
bdf5fb92950493ab651156c5d67734f698e5d960
5,628
backend
MIT License
library/src/main/java/me/thanel/swipeprogressview/internal/View+Util.kt
Tunous
192,789,828
false
null
package me.thanel.swipeprogressview.internal import android.view.View import androidx.core.view.ViewCompat internal fun View.isLayoutRtl(): Boolean = ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL
0
Kotlin
0
3
97e3256a98e796ec0e6cb2ba84bc2c0d7d92e0f9
227
SwipeProgressView
Apache License 2.0
sample/src/main/java/com/yitimo/ymage/sample/AppGlideModule.kt
yitimo
150,513,519
false
null
package com.yitimo.ymage.sample import com.bumptech.glide.annotation.GlideModule import com.bumptech.glide.module.AppGlideModule @GlideModule class AppGlideModule : AppGlideModule()
0
Kotlin
2
6
ddc7c4a7d42646cc97ef31034c2e0cb8e72eeb59
183
ymage
Apache License 2.0