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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
weaver/src/main/java/com/triophore/weaver/Weaver.kt
|
Triophore
| 868,914,079
| false
|
{"Kotlin": 25292}
|
package com.triophore.weaver
import android.Manifest
import android.content.Context
import androidx.annotation.RequiresPermission
import kotlinx.coroutines.flow.MutableStateFlow
/**
* An interface defining methods for controlling a local hotspot on Android devices.
*
* Provides methods to start, stop, and check the state of a local hotspot.
*
* @see WeaverImpl
*/
interface Weaver {
/**
* Starts a local hotspot with the specified configuration.
*
* @param ssid The SSID (name) of the hotspot.
* @param password The password for the hotspot.
* @param securityType The security type (e.g., SECURITY_TYPE_WPA2_PSK).
* @param hotspotChannel The desired channel for the hotspot (optional).
* @param band The band for the hotspot (defaults to BAND_2GHZ).
* @param autoShutdownEnabled Whether to enable auto-shutdown for the hotspot (defaults to false).
* @param macRandomizationSetting The MAC randomization setting for the hotspot (defaults to RANDOMIZATION_PERSISTENT).
*/
fun startTethering(
ssid: String,
password: String,
securityType: Int = SECURITY_TYPE_WPA2_PSK,
hotspotChannel: Int? = null,
band: Int = BAND_2GHZ,
autoShutdownEnabled: Boolean = false,
macRandomizationSetting: Int = RANDOMIZATION_PERSISTENT
)
/**
* Stops the currently active local hotspot.
*/
fun stopTethering()
/**
* Gets the current state of the local hotspot.
*
* @return True if the hotspot is active, false otherwise.
*/
fun getTetherState(): Boolean
/**
* A state flow indicating the current state of the local hotspot (active/inactive).
*/
val tetherState: MutableStateFlow<Boolean>
companion object {
const val BAND_2GHZ = 1.shl(0)
const val BAND_5GHZ = 1.shl(1)
const val BAND_6GHZ = 1.shl(2)
const val BAND_60GHZ = 1.shl(3)
const val BAND_ANY = BAND_2GHZ.or(BAND_5GHZ).or(BAND_6GHZ).or(BAND_60GHZ)
const val RANDOMIZATION_NONE = 0
const val RANDOMIZATION_PERSISTENT = 1
const val RANDOMIZATION_NON_PERSISTENT = 2
const val SECURITY_TYPE_OPEN = 0
const val SECURITY_TYPE_WPA2_PSK = 1
const val SECURITY_TYPE_WPA3_SAE_TRANSITION = 2
const val SECURITY_TYPE_WPA3_SAE = 3
const val SECURITY_TYPE_WPA3_OWE_TRANSITION = 4
const val SECURITY_TYPE_WPA3_OWE = 5
/**
* Creates a new instance of the `WeaverImpl` class for managing local hotspots.
*
* @param context The application context.
* @return A new `WeaverImpl` instance.
*/
@RequiresPermission(Manifest.permission.NEARBY_WIFI_DEVICES)
fun create(context: Context): Weaver {
return WeaverImpl(context)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
5c49a7e0035ae76a12ac7c4d4b6e8ae306ebb713
| 2,846
|
LocalOnlyHotspot
|
MIT License
|
app/src/main/java/com/pavelrekun/rekado/screens/logs_fragment/LogsContract.kt
|
ealfonso93
| 139,771,973
| true
|
{"Kotlin": 63470, "C++": 1279, "Java": 817, "CMake": 145}
|
package com.pavelrekun.rekado.screens.logs_fragment
interface LogsContract {
interface View {
fun initViews()
fun initList()
fun initClickListeners()
fun initDesign()
}
}
| 0
|
Kotlin
|
0
| 0
|
5216f0b5c3157f1e7465d5f1680fd744ab0317fa
| 218
|
Rekado
|
MIT License
|
MacrobenchmarkSample/app/src/main/java/com/example/macrobenchmark/target/Utils.kt
|
pyricau
| 440,587,136
| true
|
{"Kotlin": 115454, "TypeScript": 11355, "Shell": 544}
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.macrobenchmark.target
import android.content.Context
import android.util.TypedValue
fun Int.dp(context: Context): Float =
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
this.toFloat(),
context.resources.displayMetrics
)
| 0
|
Kotlin
|
0
| 1
|
a4decf3462cc88f0de0b3dcadb09c366400febcf
| 901
|
performance-samples
|
Apache License 2.0
|
src/main/kotlin/org/rust/lang/core/types/ty/TyArray.kt
|
Kobzol
| 174,706,351
| true
|
{"Kotlin": 8149163, "Rust": 119828, "Python": 80380, "Lex": 20075, "HTML": 18030, "Java": 1274, "Shell": 760, "RenderScript": 89}
|
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.types.ty
import org.rust.lang.core.types.consts.Const
import org.rust.lang.core.types.consts.asLong
import org.rust.lang.core.types.infer.TypeFolder
import org.rust.lang.core.types.infer.TypeVisitor
data class TyArray(val base: Ty, val const: Const) : Ty(base.flags or const.flags) {
val size: Long? get() = const.asLong()
override fun superFoldWith(folder: TypeFolder): Ty =
TyArray(base.foldWith(folder), const.foldWith(folder))
override fun superVisitWith(visitor: TypeVisitor): Boolean =
base.visitWith(visitor) || const.visitWith(visitor)
}
| 0
|
Kotlin
|
0
| 4
|
7d5f70bcf89dcc9c772efbeecf20fea7b0fb331e
| 713
|
intellij-rust
|
MIT License
|
idling-registry-okhttp/app/src/main/java/com/sqisland/espresso/idling_registry/okhttp/MainActivity.kt
|
chiuki
| 34,593,880
| false
| null |
package com.sqisland.espresso.idling_registry.okhttp
import android.app.Activity
import android.os.Bundle
import android.widget.TextView
import okhttp3.OkHttpClient
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
class MainActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val nameView = findViewById<TextView>(R.id.name)
val client = OkHttpClient()
if (BuildConfig.DEBUG) {
IdlingResources.registerOkHttp(client)
}
val retrofit = Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(MoshiConverterFactory.create())
.client(client)
.build()
val service = retrofit.create<GitHubService>(GitHubService::class.java)
service.getUser("chiuki").enqueue(object : Callback<User> {
override fun onResponse(call: Call<User>, response: Response<User>) {
val user = response.body()
nameView.text = user!!.name
}
override fun onFailure(call: Call<User>, t: Throwable) {
nameView.text = t.message
}
})
}
}
| 5
|
Kotlin
|
159
| 638
|
e54564a8a8fc961491392968a1c6da971111b064
| 1,254
|
espresso-samples
|
Apache License 2.0
|
src/en/kunmanga/src/eu/kanade/tachiyomi/extension/en/kunmanga/KunManga.kt
|
komikku-app
| 720,497,299
| false
|
{"Kotlin": 6775539, "JavaScript": 2160}
|
package eu.kanade.tachiyomi.extension.en.kunmanga
import eu.kanade.tachiyomi.multisrc.madara.Madara
class KunManga : Madara("Kun Manga", "https://kunmanga.com", "en")
| 22
|
Kotlin
|
8
| 97
|
7fc1d11ee314376fe0daa87755a7590a03bc11c0
| 169
|
komikku-extensions
|
Apache License 2.0
|
petblocks-bukkit-plugin/src/main/kotlin/com/github/shynixn/petblocks/bukkit/logic/business/service/YamlConfigurationServiceImpl.kt
|
Tominous
| 180,851,910
| true
|
{"Kotlin": 1474097, "Shell": 2544}
|
package com.github.shynixn.petblocks.bukkit.logic.business.service
import com.github.shynixn.petblocks.api.business.service.YamlConfigurationService
import com.github.shynixn.petblocks.bukkit.logic.business.extension.deserializeToMap
import org.bukkit.configuration.file.YamlConfiguration
/**
* Created by Shynixn 2019.
* <p>
* Version 1.2
* <p>
* MIT License
* <p>
* Copyright (c) 2019 by Shynixn
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
class YamlConfigurationServiceImpl : YamlConfigurationService {
/**
* Serializes the given [map] and [key] to a string.
*/
override fun serializeToString(key: String, map: Map<String, Any?>): String {
val yamlSerializer = YamlConfiguration()
yamlSerializer.set(key, map)
return yamlSerializer.saveToString()
}
/**
* DeSerializes the given [data] and turns all memory sections into maps.
*/
override fun deserializeToMap(key: String, data: String): Map<String, Any?> {
val yamlSerializer = YamlConfiguration()
yamlSerializer.loadFromString(data)
return yamlSerializer.deserializeToMap(key)
}
}
| 0
|
Kotlin
|
0
| 1
|
8ca7dcc8083200dab6869fdb4e0a493ebc6ea2b0
| 2,183
|
PetBlocks
|
Apache License 2.0
|
app/src/test/java/com/vincenzopavano/discounttracker/DataManagerTest.kt
|
VincenzoPavano
| 146,538,603
| false
| null |
package com.vincenzopavano.discounttracker
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.mock
import com.vincenzopavano.discounttracker.common.TestDataFactory
import com.vincenzopavano.discounttracker.data.DataManager
import com.vincenzopavano.discounttracker.data.model.PokemonListResponse
import com.vincenzopavano.discounttracker.data.remote.PokemonApi
import com.vincenzopavano.discounttracker.util.RxSchedulersOverrideRule
import io.reactivex.Single
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers.anyInt
import org.mockito.ArgumentMatchers.anyString
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class DataManagerTest {
@Rule @JvmField val overrideSchedulersRule = RxSchedulersOverrideRule()
val namedResourceList = TestDataFactory.makeNamedResourceList(5)
val pokemonListResponse = PokemonListResponse(namedResourceList)
val name = "charmander"
val pokemon = TestDataFactory.makePokemon(name)
val mockPokemonApi: PokemonApi = mock {
on { getPokemonList(anyInt()) } doReturn Single.just(pokemonListResponse)
on { getPokemon(anyString()) } doReturn Single.just(pokemon)
}
private var dataManager = DataManager(mockPokemonApi)
@Test
fun getPokemonListCompletesAndEmitsPokemonList() {
dataManager.getPokemonList(10)
.test()
.assertComplete()
.assertValue(TestDataFactory.makePokemonNameList(namedResourceList))
}
@Test
fun getPokemonCompletesAndEmitsPokemon() {
dataManager.getPokemon(name)
.test()
.assertComplete()
.assertValue(pokemon)
}
}
| 0
|
Kotlin
|
0
| 0
|
df91d499b95dab7956d9b54279e469b55f66328c
| 1,768
|
WhoHasTheKey
|
The Unlicense
|
app/src/main/java/com/mmdub/qofee/data/firebase/FirebaseSource.kt
|
fahmigutawan
| 648,655,600
| false
| null |
package com.mmdub.qofee.data.firebase
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.Query
import com.google.firebase.storage.StorageReference
import com.mmdub.qofee.model.response.category.CategoryItem
import com.mmdub.qofee.model.response.coffee.CoffeeItem
import com.mmdub.qofee.model.response.seller.SellerResponse
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import javax.inject.Inject
class FirebaseSource @Inject constructor(
private val firestore: FirebaseFirestore,
private val storage: StorageReference
) {
fun getAllCategory(): Flow<Resource<List<CategoryItem?>>> = callbackFlow {
trySend(Resource.Loading())
val ref = firestore.collection("category")
val listener = ref.addSnapshotListener { value, error ->
if (error != null) {
trySend(Resource.Error(error.message ?: "Error!"))
return@addSnapshotListener
}
value?.let {
val tmp = it.documents.map { doc -> doc.toObject(CategoryItem::class.java) }
trySend(Resource.Success(tmp))
}
}
awaitClose { listener.remove() }
}
fun getFirstCoffee(
uid: String = "",
category_id: String = ""
): Flow<Resource<List<CoffeeItem>>> = callbackFlow {
trySend(Resource.Loading())
delay(1500)
var ref = firestore
.collection("coffee")
.orderBy("created_at", Query.Direction.DESCENDING)
.limit(6)
if (uid.isNotEmpty()) {
ref = ref.whereEqualTo("admin_uid", uid)
}
if (category_id.isNotEmpty()) {
ref = ref.whereEqualTo("category_id", category_id)
}
val listener = ref.addSnapshotListener { value, error ->
if (error != null) {
trySend(Resource.Error(error.message ?: "Error!"))
return@addSnapshotListener
}
value?.let {
val tmp = ArrayList<CoffeeItem>()
if (it.documents.isEmpty()) {
trySend(Resource.Success(listOf()))
} else {
it.documents.forEach { doc ->
firestore
.collection("category")
.document(doc.get("category_id").toString())
.addSnapshotListener { category, errorCategory ->
firestore
.collection("seller")
.document(doc.get("admin_uid").toString())
.addSnapshotListener { seller, errorSeller ->
seller?.let { sellerNotNull ->
tmp.add(
CoffeeItem(
id = doc.get("id").toString(),
name = doc.get("name").toString(),
description = doc.get("description").toString(),
category = category?.get("word").toString(),
thumbnail = doc.get("thumbnail").toString(),
seller = sellerNotNull.get("name").toString(),
prices = doc.get("prices") as List<Map<String, Long>>,
admin_uid = doc.get("admin_uid").toString()
)
)
if (tmp.size == it.documents.size) {
trySend(Resource.Success(tmp))
}
}
}
}
}
}
}
}
awaitClose { listener.remove() }
}
fun getNextCoffee(
lastId: String,
uid: String = "",
category_id: String = ""
): Flow<Resource<List<CoffeeItem>>> = callbackFlow {
trySend(Resource.Loading())
delay(1500)
val listener = firestore
.collection("coffee")
.document(lastId)
.addSnapshotListener { value, error ->
var ref = firestore
.collection("coffee")
.orderBy("created_at", Query.Direction.DESCENDING)
.startAfter(value?.get("created_at"))
.limit(6)
if (uid.isNotEmpty()) {
ref = ref.whereEqualTo("admin_uid", uid)
}
if (category_id.isNotEmpty()) {
ref = ref.whereEqualTo("category_id", category_id)
}
ref.addSnapshotListener { value2, error2 ->
if (error2 != null) {
trySend(Resource.Error(error2.message ?: "Error!"))
return@addSnapshotListener
}
value2?.let {
val tmp = ArrayList<CoffeeItem>()
if (it.documents.isEmpty()) {
trySend(Resource.Success(listOf()))
} else {
it.documents.forEach { doc ->
firestore
.collection("category")
.document(doc.get("category_id").toString())
.addSnapshotListener { category, errorCategory ->
firestore
.collection("seller")
.document(doc.get("admin_uid").toString())
.addSnapshotListener { seller, errorSeller ->
seller?.let { sellerNotNull ->
tmp.add(
CoffeeItem(
id = doc.get("id").toString(),
name = doc.get("name").toString(),
description = doc.get("description")
.toString(),
category = category?.get("word")
.toString(),
thumbnail = doc.get("thumbnail")
.toString(),
seller = sellerNotNull.get("name")
.toString(),
prices = doc.get("prices") as List<Map<String, Long>>,
admin_uid = doc.get("admin_uid")
.toString()
)
)
if (tmp.size == it.documents.size) {
trySend(Resource.Success(tmp))
}
}
}
}
}
}
}
}
}
awaitClose { listener.remove() }
}
fun getCoffeeByCoffeeId(
coffeeId: String
): Flow<Resource<CoffeeItem>> = callbackFlow {
trySend(Resource.Loading())
val listener = firestore
.collection("coffee")
.document(coffeeId)
.addSnapshotListener { value, error ->
if (error != null) {
trySend(Resource.Error(error.message ?: "Error"))
}
value?.let { doc ->
firestore
.collection("category")
.document(doc.get("category_id").toString())
.addSnapshotListener { value2, error2 ->
if (error2 != null) {
trySend(Resource.Error(error2.message ?: "Error"))
}
value2?.let { doc2 ->
firestore
.collection("seller")
.document(doc.get("admin_uid").toString())
.addSnapshotListener { valueSeller, errorSeller ->
if(errorSeller != null){
trySend(Resource.Error(errorSeller.message ?: "Error"))
return@addSnapshotListener
}
valueSeller?.let {sellerNotNull ->
trySend(
Resource.Success(
CoffeeItem(
id = doc.get("id").toString(),
name = doc.get("name").toString(),
description = doc.get("description").toString(),
category = doc2.get("word").toString(),
thumbnail = doc.get("thumbnail").toString(),
seller = sellerNotNull.get("name").toString(),
prices = doc.get("prices") as List<Map<String, Long>>,
admin_uid = doc.get("admin_uid").toString()
)
)
)
}
}
}
}
}
}
awaitClose { listener.remove() }
}
fun getAllBannerUrl(): Flow<Resource<List<String>>> = callbackFlow {
trySend(Resource.Loading())
delay(1500)
val listener = firestore
.collection("home-banner")
.orderBy("created_at", Query.Direction.DESCENDING)
.addSnapshotListener { value, error ->
if (error != null) {
trySend(Resource.Error(error.message ?: "Error"))
return@addSnapshotListener
}
value?.let {
trySend(
Resource.Success(
it.documents.map { it.get("url").toString() }
)
)
}
}
awaitClose {
listener.remove()
}
}
fun getSellerDetail(
uid: String
): Flow<Resource<SellerResponse?>> = callbackFlow {
trySend(Resource.Loading())
val listener = firestore
.collection("seller")
.document(uid)
.addSnapshotListener { value, error ->
if (error != null) {
trySend(Resource.Error(error.message ?: "Error"))
return@addSnapshotListener
}
value?.let {
trySend(Resource.Success(it.toObject(SellerResponse::class.java)))
}
}
awaitClose { listener.remove() }
}
fun getAllSeller(): Flow<Resource<List<SellerResponse?>>> = callbackFlow {
val listener = firestore
.collection("seller")
.addSnapshotListener { value, error ->
if (error != null) {
trySend(Resource.Error(error.message ?: "Error"))
return@addSnapshotListener
}
value?.let {
trySend(
Resource.Success(
it.documents.map {
it.toObject(SellerResponse::class.java)
}
)
)
}
}
awaitClose { listener.remove() }
}
}
| 0
|
Kotlin
|
0
| 0
|
685bba170f47c521a193fb54d3eae0f616aba096
| 13,355
|
Jetpack-Qofee
|
MIT License
|
app/src/main/java/com/hami/sports_assist/data/mapper/NbaTransactionsMapper.kt
|
hongwei-bai
| 345,632,970
| false
| null |
package com.hami.sports_assist.data.mapper
import com.hami.sports_assist.data.network.model.nba.NbaTransactionsResponse
import com.hami.sports_assist.data.network.model.nba.TransactionResponse
import com.hami.sports_assist.data.room.nba.NbaTransaction
import com.hami.sports_assist.data.room.nba.NbaTransactionsEntity
object NbaTransactionsMapper {
fun NbaTransactionsResponse.map(): NbaTransactionsEntity = NbaTransactionsEntity(
dataVersion = dataVersion,
transactions = transactions.map { it.map() }
)
private fun TransactionResponse.map(): NbaTransaction = NbaTransaction(
unixTimeStamp = unixTimeStamp,
description = description,
teamAbbr = teamAbbr,
teamDisplayName = teamDisplayName,
teamLogo = teamLogo
)
}
| 2
|
Kotlin
|
6
| 36
|
611a35a45b3e564778616d8249abf53e80d3d370
| 789
|
android-nba-assist
|
Apache License 2.0
|
src/commonMain/kotlin/gui/domain/fileSelector.kt
|
shalva97
| 371,007,326
| false
| null |
package gui.domain
import gui.models.HistoryFile
expect suspend fun selectAndParseFilesFromDisk(): List<HistoryFile>
| 21
|
Kotlin
|
0
| 11
|
8e634469b2bbd4e6cbe014d6676e57688b64c1d4
| 118
|
Youtube_history_parser
|
The Unlicense
|
src/main/kotlin/view/PushPokerApplication.kt
|
denizcaygoz
| 780,887,548
| false
|
{"Kotlin": 138993}
|
package view
import entity.Player
import service.RootService
import tools.aqua.bgw.core.BoardGameApplication
/**
* This class works like a main pool for each scene in the game.
*/
class PushPokerApplication : BoardGameApplication("PushPoker"),Refreshable {
// Central service from which all others are created/accessed
// also holds the currently active game
private val rootService = RootService()
// This is where the game takes place
private val inGameScene = InGameScene(rootService)
// This Scene is shown after each finished game
private val scoreboardScene = ScoreboardScene(rootService).apply {
goToMenuButton.onMouseClicked = {
this@PushPokerApplication.showMenuScene(mainMenuScene)
}
}
// To Exit the game.
private val mainMenuScene = MainMenuScene(rootService).apply {
quitButton.onMouseClicked = {
exit()
}
}
private val nextPlayerScene = NextPlayerScene(rootService)
init {
rootService.addRefreshables(
this,
inGameScene,
scoreboardScene,
mainMenuScene
)
this.showGameScene(inGameScene)
this.showMenuScene(mainMenuScene, 0)
}
override fun refreshAfterStartNewGame() {
this.hideMenuScene()
}
override fun refreshAfterEndGame() {
scoreboardScene.scoreboard = rootService.playerActionService.scoreboardList
scoreboardScene.generateTexts()
this@PushPokerApplication.showMenuScene(scoreboardScene)
}
override fun refreshAfterEndTurn() {
nextPlayerScene.headlineTextGenerator()
this@PushPokerApplication.showMenuScene(nextPlayerScene)
}
override fun refreshAfterStartTurn(player: Player) {
this.hideMenuScene()
}
override fun refreshAfterEndRound(roundsLeft: Int) {
nextPlayerScene.headlineTextRoundEndGenerator()
this@PushPokerApplication.showMenuScene(nextPlayerScene)
}
}
| 0
|
Kotlin
|
0
| 0
|
a0a5167e5484665d2e8253b833e0d35d16cec459
| 2,003
|
PushPoker
|
MIT License
|
app/src/main/java/com/holoo/library/breadcrumbviewsample/MainActivity.kt
|
msayan
| 136,901,163
| false
| null |
package com.holoo.library.breadcrumbviewsample;
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.TextView
import android.widget.Toast
import com.holoo.library.breadcrumb.BreadCrumb
import com.holoo.library.breadcrumb.BreadCrumbView
class MainActivity : AppCompatActivity() {
private var counter = 4
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val list = mutableListOf<BreadCrumb>()
list.add(BreadCrumb.Builder().setTitle("Crumb 1").build())
list.add(BreadCrumb.Builder().setTitle("Crumb 2").build())
list.add(BreadCrumb.Builder().setTitle("Crumb 3").build())
findViewById<BreadCrumbView>(R.id.bread_crumb_view).setBreadCrumbList(list)
findViewById<BreadCrumbView>(R.id.bread_crumb_view).setListener(object : BreadCrumbView.Listener {
override fun onBreadCrumbSelected(crumb: BreadCrumb) {
Toast.makeText(this@MainActivity, "Bread Crumb Clicked ${crumb.getTitle()}", Toast.LENGTH_LONG).show()
}
})
findViewById<TextView>(R.id.add_bread_crumb).setOnClickListener {
findViewById<BreadCrumbView>(R.id.bread_crumb_view).addBreadCrumb(BreadCrumb.Builder().setTitle("Crumb $counter").build())
counter++
}
findViewById<TextView>(R.id.get_current).setOnClickListener {
Toast.makeText(this@MainActivity, "Current Bread Crumb : ${findViewById<BreadCrumbView>(R.id.bread_crumb_view).getCurrentCrumb()?.getTitle()}", Toast.LENGTH_LONG).show()
}
}
override fun onBackPressed() {
if (!findViewById<BreadCrumbView>(R.id.bread_crumb_view).goBack())
super.onBackPressed()
}
}
| 1
|
Kotlin
|
1
| 12
|
b34f0ce2a7da55697999b6b345d4a11e636c4d8f
| 1,822
|
bread-crumb-view
|
MIT License
|
app/src/main/java/com/example/cs391_ble/BLEConnect.kt
|
brandonsgh123127
| 221,824,738
| false
| null |
package com.example.cs391_ble
import android.Manifest
import android.app.ActivityManager
import android.bluetooth.*
import android.content.Context
import android.net.ConnectivityManager
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatDrawableManager.get
import kotlinx.android.synthetic.main.activity_main.*
import android.bluetooth.BluetoothDevice
import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.content.pm.PackageManager
import androidx.core.app.ComponentActivity
import androidx.core.app.ComponentActivity.ExtraData
import androidx.core.content.ContextCompat.getSystemService
import android.icu.lang.UCharacter.GraphemeClusterBreak.T
import android.icu.text.SimpleDateFormat
import android.text.format.Time
import android.view.View
import androidx.core.content.PermissionChecker
import com.spotify.android.appremote.api.SpotifyAppRemote
import com.spotify.protocol.error.SpotifyAppRemoteException
import java.lang.Math.log
import java.lang.Math.sqrt
import java.lang.Thread.sleep
import java.util.*
import kotlin.concurrent.fixedRateTimer
import kotlin.system.measureNanoTime
private val TAG = BLEConnect::class.java.simpleName
private const val STATE_DISCONNECTED = 0
private const val STATE_CONNECTING = 1
private const val STATE_CONNECTED = 2
private const val SCAN_PERIOD: Long = 5000
const val ACTION_GATT_CONNECTED = "com.example.cs391_ble.ACTION_GATT_CONNECTED"
const val ACTION_GATT_DISCONNECTED = "com.example.cs391_ble.ACTION_GATT_DISCONNECTED"
const val ACTION_GATT_SERVICES_DISCOVERED =
"com.example.cs391_ble.ACTION_GATT_SERVICES_DISCOVERED"
/**
* Coordinate-based system!
*/
private val BEACON1_COORD = Pair(2,0) //beacon 1 on right of diagram
private val BEACON2_COORD = Pair(0,2) // beacon 2 in middle
private val BEACON3_COORD = Pair(0,0) // beacon 3 on left
private val rbeacon = 75 //meters-- range of beacon
private val width = 10.5
private val height = 10.5
var rssi1:Int = 0
var rssi2:Int = 0
var rssi3:Int = 0
private const val SYS_DELAY = 0.11111 // Reading each Device's rssi creates lag... about 8 ns lag
private const val SIGNAL_S = .299792 //Speed(m) of signal per ns....
var time1Lst:MutableList<Long> = mutableListOf()
var time2Lst:MutableList<Long> = mutableListOf()
var time3Lst:MutableList<Long> = mutableListOf()
var curPlaylist = ""
/**
* As of now, everything will be implemented inside the onCreate function, as there is
* not enough time to fully implement everything with ease.
*/
class BLEConnect: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
//finish()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
SpotifyAPIBUTTON.visibility = View.INVISIBLE
progressBar.visibility = View.INVISIBLE
/**
* Listener to check and see if switch is pressed. Will change mode from RSSI to TDOA
*/
on_Switch.setOnCheckedChangeListener{buttonView, isChecked ->
if(isChecked==false){
on_Switch.text= getResources().getString(R.string.Beacon_RSSI)
}
else if(isChecked==true)
{
on_Switch.text= getResources().getString(R.string.Beacon_TDOA)
val intent = Intent(this, TDOAConnect::class.java)
startActivity(intent)
}
}
initBLERSSI()
}
// RSSI Calculated-method
private fun initBLERSSI(){
isConnectedText.setText("Connected!")
Toast.makeText(this, "Done", Toast.LENGTH_LONG).show()
// Represents bluetooth device on phone.
val bluetoothAdapter: BluetoothAdapter? by lazy(LazyThreadSafetyMode.NONE) {
val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
bluetoothManager.adapter
}
// FIRST BLE DEVICES..........
var bluetoothLEScanner = bluetoothAdapter?.getBluetoothLeScanner()
var device: BluetoothDevice? = bluetoothAdapter?.getRemoteDevice("80:6F:B0:6C:94:2B")
var device2: BluetoothDevice? = bluetoothAdapter?.getRemoteDevice("E0:7D:EA:2D:29:AB")
var device3: BluetoothDevice? = bluetoothAdapter?.getRemoteDevice("80:6F:B0:6C:8F:B6")
var connectionState = STATE_DISCONNECTED
//Now, Initialize a BL Adapter for usage later on...
// With bluetoothAdapter, one is able to interact with bluetooth devices
bluetoothAdapter?.takeIf { !it.isEnabled }?.apply {
val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
startActivityForResult(enableBtIntent, 1)
}
/**
* Now, Let's connect to a GATT server, aka the BLE devices...
* Here is where the fun begins...
*/
/**
* value of rssi resorts here to the callback!!
*/
var bluetoothGatt: BluetoothGatt? = null
var gattCallback = object : BluetoothGattCallback() {
override fun onConnectionStateChange(
gatt: BluetoothGatt,
status: Int,
newState: Int
) {
/**
* INTENTS TO BE IMPLEMENTED
*/
val intentAction: String
when (newState) {
//if conected state, change variables
BluetoothProfile.STATE_CONNECTED -> {
intentAction = ACTION_GATT_CONNECTED
connectionState = STATE_CONNECTED
broadcastUpdate(intentAction)
Log.i(TAG, "Connected to GATT server.")
Log.i(
TAG, "Attempting to start service discovery: " +
bluetoothGatt?.discoverServices()
)
}
BluetoothProfile.STATE_DISCONNECTED -> {
intentAction = ACTION_GATT_DISCONNECTED
connectionState = STATE_DISCONNECTED
Log.i(TAG, "Disconnected from GATT server.")
broadcastUpdate(intentAction)
}
}
}
}
// retrieves rssi below and device info...
bluetoothGatt = device?.connectGatt(this, true, gattCallback)
var bluetoothGatt2 = device2?.connectGatt(this,true,gattCallback)
var bluetoothGatt3 = device3?.connectGatt(this,true,gattCallback)
Log.i(TAG, "Trying to connect")
// Stores all of the important info in this callback
var scanCallback = object : ScanCallback() {
override fun onScanResult(callbackType : Int, result:ScanResult) {
gattCallback.onReadRemoteRssi(bluetoothGatt,rssi1,0)
gattCallback.onReadRemoteRssi(bluetoothGatt2,rssi2,0)
gattCallback.onReadRemoteRssi(bluetoothGatt3,rssi3,0)
var isConnected:Boolean? = bluetoothGatt?.readRemoteRssi()
var isConnected2:Boolean? = bluetoothGatt2?.readRemoteRssi()
var isConnected3:Boolean? = bluetoothGatt3?.readRemoteRssi()
Log.d("isConnect","${isConnected}, ${isConnected2}, ${isConnected3}.")
//Setting rssi ..... First implementation...
if(result?.device?.address == "80:6F:B0:6C:94:2B")
time1Lst.add(measureNanoTime{rssi1 = result.getRssi()})
//Log.d("time1!!!","${measureNanoTime {rssi1 = result.getRssi()}}")
else if(result?.device?.address == "E0:7D:EA:2D:29:AB")
time2Lst.add(measureNanoTime{rssi2 = result.getRssi()})
//Log.d("time2!!!","${measureNanoTime {rssi2 = result.getRssi()}}")
else if(result?.device?.address == "80:6F:B0:6C:8F:B6")
time3Lst.add(measureNanoTime{rssi3 = result.getRssi()})
//Log.d("time3!!!","${measureNanoTime {rssi3 = result.getRssi()}}")
Beacon1RSSI.text=Integer.toString(rssi1) + " dBm"
Beacon2RSSI.text=Integer.toString(rssi2) + " dBm"
Beacon3RSSI.text=Integer.toString(rssi3) + " dBm"
angleCalc(bluetoothGatt)
}
}
/**
* Allows for user to accept location permission for location...
*/
when (PermissionChecker.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
PackageManager.PERMISSION_GRANTED -> {
bluetoothLEScanner?.startScan(scanCallback)
}
else -> requestPermissions(arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), 1)
}
bluetoothGatt?.connect()
bluetoothGatt2?.connect()
bluetoothGatt3?.connect()
sleep(1000)
Toast.makeText(this, "Connected!", Toast.LENGTH_SHORT)
gattCallback.onReadRemoteRssi(bluetoothGatt,rssi1,0)
gattCallback.onReadRemoteRssi(bluetoothGatt2,rssi2,0)
gattCallback.onReadRemoteRssi(bluetoothGatt3,rssi3,0)
fixedRateTimer("timer", false, 0L, 10 * 1000) { //EVERY 10 SECONDS!
this@BLEConnect.runOnUiThread {
/*
CALCULATING DISTANCE OF EACH BEACON IN VECTOR FORMAT
*/
var rA = Math.pow(10.0,((rssi1-(-70))/(-10*(4.0))))
var rB = Math.pow(10.0,((rssi2-(-70))/(-10*(4.0))))
var rC = Math.pow(10.0,((rssi3-(-70))/(-10*(4.0))))
var ABx = BEACON2_COORD.first - BEACON1_COORD.first
var ABy = BEACON2_COORD.second - BEACON1_COORD.second
var ACx = BEACON3_COORD.first - BEACON1_COORD.first
var ACy = BEACON3_COORD.second - BEACON1_COORD.second
var BCx = BEACON3_COORD.first - BEACON2_COORD.first
var BCy = BEACON3_COORD.second - BEACON2_COORD.second
// VECTOR! square root of sum of squares
var AB = sqrt(Math.pow(ABx.toDouble(), 2.0) + Math.pow(ABy.toDouble(), 2.0))
var AC = sqrt(Math.pow(ACx.toDouble(), 2.0) + Math.pow(ACy.toDouble(), 2.0))
var BC = sqrt(Math.pow(BCx.toDouble(), 2.0) + Math.pow(BCy.toDouble(), 2.0))
//(radius squared plus ab squared - radius squared) divided by 2AB
var ax = (Math.pow(rA.toDouble(), 2.0) + Math.pow(AB, 2.0) - Math.pow(rB.toDouble(),2.0)) / (2 * AB)
var ay = Math.pow(rA.toDouble(), 2.0) - Math.pow(ax, 2.0)
var bx = (Math.pow(rB.toDouble(),2.0) + Math.pow(BC, 2.0) - Math.pow(rC.toDouble(),2.0)) / (2 * BC)
var by = Math.pow(rB.toDouble(),2.0) - Math.pow(bx, 2.0)
var cx = (Math.pow(rC.toDouble(),2.0) + Math.pow(AC, 2.0) - Math.pow(rA.toDouble(),2.0)) / (2 * AC)
var cy = Math.pow(rC.toDouble(),2.0) - Math.pow(cx, 2.0)
if (ay > 0 || by > 0 || cy > 0) {
ay = sqrt(ay);by = sqrt(by);cy = sqrt(cy)
}
//UNIT VECTOR
var eax = ABx / AB
var ebx = BCx / BC
var ecx = ACx / AC
var eay = ABy / AB
var eby = BCy / BC
var ecy = ACy / AC
var nax = -eay
var nbx = -eby
var ncx = -ecy
var nay = eax
var nby = ebx
var ncy = ecx
//polynomial representation of point from beacons....
var Q1ax = BEACON1_COORD.first + ax * eax
var Q1bx = BEACON2_COORD.first + bx * ebx
var Q1cx = BEACON3_COORD.first + cx * ecx
var Q1ay = BEACON1_COORD.second + ax * eay
var Q1by = BEACON2_COORD.second + bx * eby
var Q1cy = BEACON2_COORD.second + cx * ecy
//if multiple intersection
//if(ay != 0.0 && by != 0.0 && cy != 0.0) {
var Q2ax = Q1ax - ay * nax
var Q2bx = Q1bx - by * nbx
var Q2cx = Q1cx - cy * ncx
var Q2ay = Q1ay - ay * nay
var Q2by = Q1by - by * nby
var Q2cy = Q1cy - cy * ncy
Q1ax += ay * nax
Q1bx += by * nbx
Q1cx += cy * ncx
Q1ay += ay * nay
Q1by += by * nby
Q1cy += cy * ncy
// val avg1 = time1Lst.average() * SYS_DELAY * SIGNAL_S
// val avg2 = time2Lst.average() * SYS_DELAY * SIGNAL_S
// val avg3 = time3Lst.average() * SYS_DELAY * SIGNAL_S
/**
* Q1a,Q1b,Q1c,Q2a,Q2b,Q2c are used here to check quadrants!!!
* | B | Trilateration...
* | // | \\ |
* |_____ //____| ___\\____|
* | // | \\ | Problem: Facing away beacon in sector...
* | //________|_______ \\|
* C A
*/
// THIS IS THE PART WHERE PLAYLIST WILL CHANGGE
if (rA < rB && (rA+ rC)/2 < ((rC + rB)/2))// bottom RIGHT '90s'
{
if (SpotifyService.getPlayllist() != "spotify:playlist:71JXQ7EwfZMKmLPrzKZAB4")
SpotifyService.play("spotify:playlist:71JXQ7EwfZMKmLPrzKZAB4")
}
else if(rC < rB && (rA + rB)/2 > ((rC + rB)/2)) //Bottom LEFT 'cali' WORKS
{
if (SpotifyService.getPlayllist() != "spotify:playlist:37i9dQZF1DWTlgzqHpWg4m")
SpotifyService.play("spotify:playlist:37i9dQZF1DWTlgzqHpWg4m")
}
else if (rB < rA && (rA + rB) / 2 < Math.sqrt(Math.pow(rB, 2.0) + Math.pow(rC, 2.0)))//top LEFT 'ari' WORKS
{
if (SpotifyService.getPlayllist() != "spotify:playlist:37i9dQZF1DX1PfYnYcpw8w")
SpotifyService.play("spotify:playlist:37i9dQZF1DX1PfYnYcpw8w")
} else if (rB <= rC && rB < Math.sqrt(Math.pow(rB, 2.0) + Math.pow(rC, 2.0)))// top RIGHT 'mega'
{
if (SpotifyService.getPlayllist() != "spotify:playlist:37i9dQZF1DXbYM3nMM0oPk")
SpotifyService.play("spotify:playlist:37i9dQZF1DXbYM3nMM0oPk")
}
time1Lst = mutableListOf()
time2Lst = mutableListOf()
time3Lst = mutableListOf()
}
}
}
/**
* USES TDOA TO CALCULATE LOCATION
*/
fun angleCalc(gatt:BluetoothGatt?){
Log.d("list1 time", time1Lst.average().toString())
Log.d("list2 time", time2Lst.average().toString())
Log.d("list3 time", time3Lst.average().toString())
}
private fun broadcastUpdate(action: String) {
val intent = Intent(action)
sendBroadcast(intent)
}
}
/**
* THIS CLASS IS USED FOR WHEN THE SWITCH IS PRESSED TO DO LONG DISTANCE BEACON LOCATION:
* THIS CLASS USES 'SUCCESS PACKETS' TO CONFIGURE LOCATIONS...
*
*/
class PACKETConnect:AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
}
| 0
|
Kotlin
|
1
| 0
|
80cde8b3764fc8e83ff15aeaee03a8d3a97e49e5
| 15,626
|
BlueJammin
|
Apache License 2.0
|
subscriptions/subscriptions-impl/src/test/java/com/duckduckgo/subscriptions/impl/ui/RestoreSubscriptionViewModelTest.kt
|
duckduckgo
| 78,869,127
| false
|
{"Kotlin": 11617296, "HTML": 63593, "Ruby": 14445, "JavaScript": 8619, "C++": 1813, "CMake": 1286, "Shell": 784}
|
package com.duckduckgo.subscriptions.impl.ui
import app.cash.turbine.test
import com.duckduckgo.common.test.CoroutineTestRule
import com.duckduckgo.subscriptions.impl.RealSubscriptionsManager.Companion.SUBSCRIPTION_NOT_FOUND_ERROR
import com.duckduckgo.subscriptions.impl.SubscriptionsData
import com.duckduckgo.subscriptions.impl.SubscriptionsManager
import com.duckduckgo.subscriptions.impl.pixels.SubscriptionPixelSender
import com.duckduckgo.subscriptions.impl.services.Entitlement
import com.duckduckgo.subscriptions.impl.ui.RestoreSubscriptionViewModel.Command.Error
import com.duckduckgo.subscriptions.impl.ui.RestoreSubscriptionViewModel.Command.RestoreFromEmail
import com.duckduckgo.subscriptions.impl.ui.RestoreSubscriptionViewModel.Command.SubscriptionNotFound
import com.duckduckgo.subscriptions.impl.ui.RestoreSubscriptionViewModel.Command.Success
import kotlinx.coroutines.test.runTest
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
class RestoreSubscriptionViewModelTest {
@get:Rule
val coroutineTestRule: CoroutineTestRule = CoroutineTestRule()
private val subscriptionsManager: SubscriptionsManager = mock()
private val pixelSender: SubscriptionPixelSender = mock()
private lateinit var viewModel: RestoreSubscriptionViewModel
@Before
fun before() {
viewModel = RestoreSubscriptionViewModel(
subscriptionsManager = subscriptionsManager,
dispatcherProvider = coroutineTestRule.testDispatcherProvider,
pixelSender = pixelSender,
)
}
@Test
fun whenRestoreFromEmailThenSendCommand() = runTest {
viewModel.commands().test {
viewModel.restoreFromEmail()
assertTrue(awaitItem() is RestoreFromEmail)
}
}
@Test
fun whenRestoreFromStoreIfFailureThenReturnError() = runTest {
whenever(subscriptionsManager.recoverSubscriptionFromStore()).thenReturn(
SubscriptionsData.Failure("error"),
)
viewModel.commands().test {
viewModel.restoreFromStore()
val result = awaitItem()
assertTrue(result is Error)
assertEquals("error", (result as Error).message)
}
}
@Test
fun whenRestoreFromStoreIfNoSubscriptionFoundThenReturnNotFound() = runTest {
whenever(subscriptionsManager.recoverSubscriptionFromStore()).thenReturn(
SubscriptionsData.Failure(SUBSCRIPTION_NOT_FOUND_ERROR),
)
viewModel.commands().test {
viewModel.restoreFromStore()
val result = awaitItem()
assertTrue(result is SubscriptionNotFound)
}
}
@Test
fun whenRestoreFromStoreIfNoEntitlementsThenReturnNotFound() = runTest {
whenever(subscriptionsManager.recoverSubscriptionFromStore()).thenReturn(
SubscriptionsData.Success(email = null, externalId = "test", entitlements = emptyList()),
)
viewModel.commands().test {
viewModel.restoreFromStore()
val result = awaitItem()
assertTrue(result is SubscriptionNotFound)
}
}
@Test
fun whenRestoreFromStoreIfEntitlementsThenReturnSuccess() = runTest {
whenever(subscriptionsManager.recoverSubscriptionFromStore()).thenReturn(
SubscriptionsData.Success(
email = null,
externalId = "test",
entitlements = listOf(Entitlement(id = "test", product = "test", name = "test")),
),
)
viewModel.commands().test {
viewModel.restoreFromStore()
val result = awaitItem()
assertTrue(result is Success)
}
}
@Test
fun whenRestoreFromStoreClickThenPixelIsSent() = runTest {
viewModel.restoreFromStore()
verify(pixelSender).reportActivateSubscriptionRestorePurchaseClick()
}
@Test
fun whenRestoreFromEmailClickThenPixelIsSent() = runTest {
viewModel.restoreFromEmail()
verify(pixelSender).reportActivateSubscriptionEnterEmailClick()
}
@Test
fun whenRestoreFromStoreSuccessThenPixelIsSent() = runTest {
whenever(subscriptionsManager.recoverSubscriptionFromStore()).thenReturn(
SubscriptionsData.Success(
email = null,
externalId = "test",
entitlements = listOf(Entitlement(id = "test", product = "test", name = "test")),
),
)
viewModel.restoreFromStore()
verify(pixelSender).reportRestoreUsingStoreSuccess()
}
@Test
fun whenRestoreFromStoreFailsBecauseThereAreNoEntitlementsThenPixelIsSent() = runTest {
whenever(subscriptionsManager.recoverSubscriptionFromStore()).thenReturn(
SubscriptionsData.Success(email = null, externalId = "test", entitlements = emptyList()),
)
viewModel.restoreFromStore()
verify(pixelSender).reportRestoreUsingStoreFailureSubscriptionNotFound()
}
@Test
fun whenRestoreFromStoreFailsBecauseThereIsNoSubscriptionThenPixelIsSent() = runTest {
whenever(subscriptionsManager.recoverSubscriptionFromStore()).thenReturn(
SubscriptionsData.Failure(SUBSCRIPTION_NOT_FOUND_ERROR),
)
viewModel.restoreFromStore()
verify(pixelSender).reportRestoreUsingStoreFailureSubscriptionNotFound()
}
@Test
fun whenRestoreFromStoreFailsForOtherReasonThenPixelIsSent() = runTest {
whenever(subscriptionsManager.recoverSubscriptionFromStore()).thenReturn(
SubscriptionsData.Failure("bad stuff happened"),
)
viewModel.restoreFromStore()
verify(pixelSender).reportRestoreUsingStoreFailureOther()
}
}
| 59
|
Kotlin
|
840
| 3,490
|
3e86da3fc0b6fd3caba41db140c5393b4ad4566b
| 5,867
|
Android
|
Apache License 2.0
|
app/src/main/java/com/example/mycharge/network/ServiceCreator.kt
|
wenvelope
| 506,684,779
| false
|
{"Kotlin": 44966}
|
package com.example.mycharge.network
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object ServiceCreator {
private const val BASE_URL = "http://110.40.156.9:4000/"
private val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
fun<T> create(serviceClass:Class<T>):T = retrofit.create(serviceClass)
inline fun<reified T> create():T = create(T::class.java)
}
| 0
|
Kotlin
|
1
| 1
|
3ee708c69fafe28884149493d7dcd6d89abab42e
| 492
|
MyCharge
|
Apache License 2.0
|
src/main/java/jp/co/soramitsu/androidfoundation/format/CollectionExt.kt
|
soramitsu
| 373,586,020
| false
|
{"Kotlin": 30789}
|
package jp.co.soramitsu.androidfoundation.format
import java.math.BigInteger
fun <K, V> Map<K, V>.inverseMap() = map { Pair(it.value, it.key) }.toMap()
inline fun <T> Iterable<T>.sumByBigInteger(selector: (T) -> BigInteger): BigInteger {
var sum: BigInteger = BigInteger.ZERO
for (element in this) {
sum += selector(element)
}
return sum
}
fun <T> List<T>.cycle(): Sequence<T> {
if (isEmpty()) return emptySequence()
var i = 0
return generateSequence { this[i++ % this.size] }
}
| 0
|
Kotlin
|
0
| 0
|
58553c30c0a1d0ec64de49bf5cc6f0a79192dc37
| 521
|
android-foundation
|
Apache License 2.0
|
app/src/main/java/com/movietrivia/filmfacts/domain/GetBiggestFilmographyUseCase.kt
|
jlynchsd
| 631,418,923
| false
|
{"Kotlin": 524037}
|
package com.movietrivia.filmfacts.domain
import android.content.Context
import com.movietrivia.filmfacts.R
import com.movietrivia.filmfacts.model.*
import kotlinx.coroutines.*
class GetBiggestFilmographyUseCase(
private val applicationContext: Context,
private val filmFactsRepository: FilmFactsRepository,
private val recentPromptsRepository: RecentPromptsRepository,
private val dispatcher: CoroutineDispatcher = Dispatchers.IO
) : UseCase {
override suspend fun invoke(includeGenres: List<Int>?) =
withContext(dispatcher) {
getPrompt(includeGenres)
}
private suspend fun getPrompt(includeGenres: List<Int>?): UiPrompt? {
val popularActors = getActors(
filmFactsRepository,
recentPromptsRepository,
includeGenres
).toMutableList()
val targetActorCount = 4
if (popularActors.size >= targetActorCount) {
val actorResults = getActorDetails(
filmFactsRepository,
popularActors,
targetActorCount,
) { it.profilePath.isNotEmpty() }
if (actorResults.size >= targetActorCount) {
val actorMovieResults = coroutineScope {
actorResults.map {
async {
filmFactsRepository.getMovies(
forceSettings = UserSettings(language = ""),
minimumVotes = null,
cast = listOf(it.id)
)
}
}.awaitAll().filterNotNull().distinctBy { it.totalResultCount }.toMutableList()
}
if (actorMovieResults.size == actorResults.size) {
val actorInfo = actorResults.zip(actorMovieResults).sortedByDescending { it.second.totalResultCount }
actorInfo.forEach { recentPromptsRepository.addRecentActor(it.first.id) }
val entries = actorInfo.mapIndexed { index, entry ->
val suffix = if (entry.second.totalResultCount == 1) {
R.string.suffix_filmography
} else {
R.string.suffix_filmography_plural
}
UiImageEntry(
filmFactsRepository.getImageUrl(entry.first.profilePath, ImageType.PROFILE) ?: "",
index == 0,
entry.first.name,
"${entry.second.totalResultCount} ${applicationContext.getString(suffix)}"
)
}.shuffled()
val success = preloadImages(applicationContext, *entries.map { it.imagePath }.toTypedArray())
if (success) {
return UiImagePrompt(
entries,
R.string.actor_longest_filmography_title
)
}
}
}
}
return null
}
}
| 0
|
Kotlin
|
0
| 0
|
9a6c9ae5bc2f7a743c9399a64d0c9edf5c7e0d84
| 3,160
|
FilmFacts
|
Apache License 2.0
|
app/src/main/java/com/example/bnbproject/navigation/NavGraph.kt
|
Mohanmanuhs
| 864,376,483
| false
|
{"Kotlin": 97403}
|
package com.example.bnbproject.navigation
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import com.example.bnbproject.screens.HomeScreen
import com.example.bnbproject.screens.ItemDetailsScreen
import com.example.bnbproject.screens.LoginScreen
import com.example.bnbproject.screens.MarketSpace
import com.example.bnbproject.screens.Page3Screen
import com.example.bnbproject.screens.Page5Screen
import com.example.bnbproject.screens.RegisterScreen
import com.example.bnbproject.screens.SellDetailsScreen
import com.example.bnbproject.screens.SellingScreen
import com.example.bnbproject.screens.SplashScreen
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
@Composable
fun NavGraphScreen(navController: NavHostController, modifier: Modifier = Modifier) {
NavHost(navController = navController, startDestination = NavRoutes.Splash.route) {
composable(NavRoutes.Splash.route) {
SplashScreen(navController)
}
composable(NavRoutes.BottomNav.route) {
BottomNavScreen(navController)
}
composable(NavRoutes.Home.route) {
HomeScreen()
}
composable(NavRoutes.MarketSpace.route) {
MarketSpace(navController)
}
composable(NavRoutes.Login.route) {
LoginScreen(navController)
}
composable(NavRoutes.Register.route) {
RegisterScreen(navController)
}
composable(NavRoutes.MarketDetails.route) {backStackEntry->
val data = backStackEntry.arguments!!.getString("data")
data?.let {
Log.d("MyTag",it)
SellDetailsScreen(it)
}
}
composable(NavRoutes.Page3.route) {
Page3Screen()
}
composable(NavRoutes.ItemDetails.route) {backStackEntry->
val data = backStackEntry.arguments!!.getString("data")
data?.let {
Log.d("MyTag",it)
ItemDetailsScreen(it)
}
}
composable(NavRoutes.SellingScreen.route) {
SellingScreen()
}
composable(NavRoutes.Page5.route) {
Page5Screen(navController)
}
}
}
| 0
|
Kotlin
|
1
| 0
|
9cec079543875b5ad70c57c0bfd8d9b78c94bd7f
| 2,438
|
BitNBuildAPP
|
MIT License
|
paper/src/main/kotlin/nl/chimpgamer/teleportbow/paper/TeleportBowPlugin.kt
|
ChimpGamer
| 657,776,180
| false
| null |
package nl.chimpgamer.teleportbow.paper
import org.bukkit.plugin.java.JavaPlugin
class TeleportBowPlugin : JavaPlugin() {
override fun onEnable() {
}
override fun onDisable() {
}
}
| 0
|
Kotlin
|
0
| 0
|
f8d4983994dbf06e245ff591289e398235a78087
| 202
|
TeleportBow
|
MIT License
|
src/main/kotlin/com/github/davio/aoc/y2022/Day16.kt
|
Davio
| 317,510,947
| false
|
{"Kotlin": 381599}
|
package com.github.davio.aoc.y2022
import com.github.davio.aoc.general.Day
import com.github.davio.aoc.general.getInputAsList
/**
* See [Advent of Code 2022 Day 16](https://adventofcode.com/2022/day/16)
*/
object Day16 : Day() {
private const val LINE_PATTERN = """Valve ([A-Z]{2}) has flow rate=(\d+); tunnel(?:s?) lead(?:s?) to valve(?:s?) (.+)"""
private val LINE_REGEX = Regex(LINE_PATTERN)
private val valveMap: HashMap<String, Valve> = hashMapOf()
override fun part1(): String {
getInputAsList()
.map { parseLine(it) }
.onEach { println(it) }
val route = Route()
val result = getBestRoute(route)
println(result)
return result.pressureReleased.toString()
}
private fun parseLine(line: String): Valve {
val (label, flowRate, tunnels) = LINE_REGEX.matchEntire(line)!!.destructured
val valve = valveMap.getOrPut(label) { Valve(label, flowRate.toInt()) }
valve.flowRate = flowRate.toInt()
tunnels.split(", ").forEach {
valve.addTunnel(it)
}
return valve
}
data class Valve(val label: String, var flowRate: Int = 0) {
val tunnels: MutableList<Valve> = mutableListOf()
fun addTunnel(label: String) {
val otherValve = valveMap.getOrPut(label) { Valve(label) }
tunnels.add(otherValve)
}
override fun toString(): String = "$label($flowRate): ${tunnels.joinToString { it.label }}"
}
private val routeMap: MutableMap<Route, RouteResult> = mutableMapOf()
private fun getBestRoute(route: Route): RouteResult {
if (routeMap.contains(route)) {
return routeMap.getValue(route)
}
if (route.timeRemaining < 2) {
routeMap[route] = RouteResult.EMPTY
return RouteResult.EMPTY
}
val timeRemainingAfterAction = route.timeRemaining - 1
val openThisValveAction = Action.OpenValve(route.currentValve, timeRemainingAfterAction)
var combinedResultWithClosedValve: RouteResult? = null
if (!route.openedValves.contains(route.currentValve) && route.currentValve.flowRate > 0) {
val resultWithClosedValve = RouteResult(listOf(openThisValveAction), openThisValveAction.getPressureReleased())
val resultAfterClosingValve = getBestRoute(
Route(
route.currentValve,
timeRemainingAfterAction,
route.openedValves.toMutableSet() + route.currentValve
)
)
combinedResultWithClosedValve = RouteResult(
resultWithClosedValve.actions.toMutableList() + resultAfterClosingValve.actions,
resultWithClosedValve.pressureReleased + resultAfterClosingValve.pressureReleased
)
}
val bestCombinedResultAfterMoving = route.currentValve.tunnels.map { valveMovedTo ->
val moveAction = Action.MoveToValve(valveMovedTo, timeRemainingAfterAction)
val bestRouteAfterMoving = getBestRoute(
Route(
valveMovedTo,
timeRemainingAfterAction,
route.openedValves.toMutableSet()
)
)
RouteResult(
listOf(moveAction) + bestRouteAfterMoving.actions,
bestRouteAfterMoving.pressureReleased
)
}.maxBy { it.pressureReleased }
return listOfNotNull(combinedResultWithClosedValve, bestCombinedResultAfterMoving)
.maxBy { it.pressureReleased }
.also { routeMap.putIfAbsent(route, it) }
}
data class Route(
var currentValve: Valve = valveMap.getValue("AA"),
var timeRemaining: Int = 30,
val openedValves: Set<Valve> = setOf()
)
data class RouteResult(
val actions: List<Action> = mutableListOf(),
val pressureReleased: Int = 0
) {
override fun toString(): String {
return actions.joinToString(separator = System.lineSeparator()) {
"${it.timeRemainingAfterAction + 1} $it"
} + ", pressure released: $pressureReleased"
}
companion object {
val EMPTY = RouteResult(emptyList(), 0)
}
}
sealed interface Action {
val valve: Valve
val timeRemainingAfterAction: Int
data class OpenValve(override val valve: Valve, override val timeRemainingAfterAction: Int) : Action {
fun getPressureReleased(): Int = valve.flowRate * timeRemainingAfterAction
override fun toString(): String = "open valve ${valve.label} with flowRate ${valve.flowRate} " +
"for ${valve.flowRate * timeRemainingAfterAction} pressure released"
}
data class MoveToValve(override val valve: Valve, override val timeRemainingAfterAction: Int) : Action {
override fun toString(): String = "move to valve ${valve.label}"
}
}
}
| 1
|
Kotlin
|
0
| 0
|
41863b0ae5efae95aab60dff475ebb43733564d1
| 5,041
|
advent-of-code
|
MIT License
|
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsaccreditedprogrammesapi/integration/PersonIntegrationTest.kt
|
ministryofjustice
| 615,402,552
| false
|
{"Kotlin": 555192, "Shell": 9504, "Dockerfile": 1415}
|
package uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.integration
import io.kotest.matchers.equals.shouldBeEqual
import io.kotest.matchers.ints.shouldBeGreaterThan
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.context.annotation.Import
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.web.reactive.server.expectBody
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.api.model.Offence
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.api.model.PeopleSearchRequest
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.api.model.PeopleSearchResponse
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.api.model.SentenceDetails
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.common.config.JwtAuthHelper
import uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.common.util.PRISONER_1
import java.time.LocalDate
import java.time.Month
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
@Import(JwtAuthHelper::class)
class PersonIntegrationTest : IntegrationTestBase() {
@Test
fun `get sentences by prison number should return 200 with matching entries`() {
mockClientCredentialsJwtRequest(jwt = jwtAuthHelper.bearerToken())
val prisonNumber = PRISONER_1.prisonerNumber
val sentenceDetails = getSentences(prisonNumber)
sentenceDetails.keyDates?.forEach { println("keyDate: $it \n") }
sentenceDetails.sentences!!.size shouldBe 5
sentenceDetails.sentences!![0].description shouldBe "CJA03 Standard Determinate Sentence"
sentenceDetails.keyDates!!.size.shouldBeGreaterThan(0)
val keyDate = sentenceDetails.keyDates?.firstOrNull { it.earliestReleaseDate == true }
keyDate!!.code.shouldBeEqual("PRRD")
}
@Test
fun `get sentences by prison number with no keyDates should return 200 empty keydates`() {
mockClientCredentialsJwtRequest(jwt = jwtAuthHelper.bearerToken())
val sentenceDetails = getSentences("A8610DY")
sentenceDetails.keyDates?.size shouldBe 0
}
@Test
fun `get offences by offence code is successful`() {
mockClientCredentialsJwtRequest(jwt = jwtAuthHelper.bearerToken())
val prisonNumber = "C6666DD"
val offences = getOffences(prisonNumber)
offences.isNotEmpty()
offences.first() shouldBe Offence(
offence = "Cause / permit fail to give treatment or cull sick or injured conventionally reared meat chickens - England - SX03174",
category = "Contrary to regulations 5(1)(ba), 7(1)(c) and 9 of, and paragraph 11(3) of Schedule 5A to, the Welfare of Farmed Animals (England) Regulations 2007.",
offenceDate = LocalDate.of(2012, Month.OCTOBER, 21),
)
}
@Test
fun `search for a person by prisonId`() {
mockClientCredentialsJwtRequest(jwt = jwtAuthHelper.bearerToken())
val peopleSearchRequest = PeopleSearchRequest("C6666DD", listOf("MDI"))
val response = searchPrisoners(peopleSearchRequest)
response.shouldNotBeNull()
response.first() shouldBeEqual PeopleSearchResponse(
bookingId = "1202335",
conditionalReleaseDate = null,
prisonName = "Nottingham (HMP)",
dateOfBirth = LocalDate.of(1975, 1, 1),
ethnicity = "White: Eng./Welsh/Scot./N.Irish/British",
gender = "Male",
homeDetentionCurfewEligibilityDate = null,
indeterminateSentence = false,
firstName = "MICKEY",
lastName = "SMITH",
paroleEligibilityDate = null,
prisonerNumber = "C6666DD",
religion = null,
sentenceExpiryDate = null,
sentenceStartDate = null,
tariffDate = null,
)
}
fun searchPrisoners(peopleSearchRequest: PeopleSearchRequest) =
webTestClient
.post()
.uri("/prisoner-search")
.header(HttpHeaders.AUTHORIZATION, jwtAuthHelper.bearerToken())
.accept(MediaType.APPLICATION_JSON)
.bodyValue(peopleSearchRequest)
.exchange()
.expectStatus().isOk
.expectBody<List<PeopleSearchResponse>>()
.returnResult().responseBody!!
private fun getSentences(prisonNumber: String): SentenceDetails =
webTestClient
.get()
.uri("/people/$prisonNumber/sentences")
.header(HttpHeaders.AUTHORIZATION, jwtAuthHelper.bearerToken())
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk
.expectBody<SentenceDetails>()
.returnResult().responseBody!!
private fun getOffences(prisonNumber: String): List<Offence> =
webTestClient
.get()
.uri("/people/offences/$prisonNumber")
.header(HttpHeaders.AUTHORIZATION, jwtAuthHelper.bearerToken())
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk
.expectBody<List<Offence>>()
.returnResult().responseBody!!
}
| 1
|
Kotlin
|
0
| 0
|
be95f960b88d913de51c45a153ff909bf335c00d
| 5,065
|
hmpps-accredited-programmes-api
|
MIT License
|
cordapp/src/main/java/com/template/contract/TokenContract.kt
|
vladimirevsin
| 145,014,413
| false
|
{"Gradle": 4, "Shell": 1, "Java Properties": 2, "Text": 4, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java": 17, "Kotlin": 48, "INI": 1, "JAR Manifest": 2, "Motorola 68K Assembly": 2, "SQL": 1}
|
package com.template.contract
import com.template.command.Commands
import com.template.flow.AddTokenToClient
import com.template.state.AggregateBalanceState
import com.template.state.TokenState
import net.corda.core.contracts.Contract
import net.corda.core.contracts.Requirements.using
import net.corda.core.contracts.requireThat
import net.corda.core.transactions.LedgerTransaction
class TokenContract : Contract {
companion object {
val TOKEN_CONTRACT_ID = "com.template.contract.TokenContract"
}
override fun verify(tx: LedgerTransaction) {
val command = tx.commands.get(0)
when (command.value) {
is Commands.SellToTSC -> {
val stateOutput = tx.outputs.get(0).data as TokenState
requireThat {
"Транзакция не должна иметь входов" using (tx.inputs.isEmpty())
"Транзакция должна иметь хотя бы одно состояние выхода" using (tx.outputs.size > 0)
"Банк должен являться участником данной транзакции" using (stateOutput.sender.name.organisation == "Bank")
"Клиент не может являться участником данной транзакции" using (stateOutput.sender.name.organisation != "Clients")
"Количество токенов должно быть больше нуля" using (stateOutput.value > 0)
}
}
is Commands.AddBonusClient -> {
val stateOutput = tx.outputs.get(0).data as TokenState
requireThat {
"Клиент должен являться участником данной транзакции" using (stateOutput.clientRecipient != null)
"Транзакция должна иметь хотя бы одно состояние выхода" using (tx.outputs.size > 0)
"У ТСП должно хватать средств" using (stateOutput.value >= 0)
}
}
is Commands.DestroyBonusClient -> {
val stateOutput = tx.outputs.get(0).data as TokenState
requireThat {
"Клиент должен являться участником данной транзакции" using (stateOutput.clientSender != null)
"Транзакция должна иметь хотя бы одно состояние выхода" using (tx.outputs.size > 0)
"У клиента должно хватать средств" using (stateOutput.value >= 0)
}
}
is Commands.UpdateBalance -> {
val stateOutput = tx.outputs.single().data as AggregateBalanceState
requireThat {
"Транзакция должна содержать идентификатор кошелька участника сети" using (stateOutput.clientId != null)
"Транзакция должна иметь хотя бы одно состояние выхода" using (tx.outputs.size > 0)
"Количество токенов должно быть больше нуля" using (stateOutput.newValue >= 0)
}
}
else -> {
//Todo Вывести, что команда не распознана
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
2787cbd89f1f625d15938ffffffc84816da36bc9
| 2,950
|
loyalty-system
|
MIT License
|
ChessModelTDS/checkers-model/src/main/kotlin/isel/leic/tds/checkers/model/main.kt
|
AndreBaptista1
| 549,627,939
| false
|
{"Kotlin": 15044}
|
package isel.leic.tds.checkers.model
fun main(){
val column = Column('c')
val column2 = Column('a')
println(column2.index)
}
| 0
|
Kotlin
|
0
| 0
|
3b7fefb9abaf448ad4ac35096d7f63d9e66192e6
| 137
|
CHECKERS-TDS
|
MIT License
|
src/main/kotlin/org/opensearch/replication/action/repository/ReleaseLeaderResourcesAction.kt
|
opensearch-project
| 323,830,219
| false
|
{"Kotlin": 1005221, "Python": 17931, "Shell": 8517}
|
/*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.replication.action.repository
import org.opensearch.action.ActionType
import org.opensearch.action.support.master.AcknowledgedResponse
class ReleaseLeaderResourcesAction private constructor() : ActionType<AcknowledgedResponse>(NAME, ::AcknowledgedResponse) {
companion object {
const val NAME = "indices:admin/plugins/replication/resources/release"
val INSTANCE = ReleaseLeaderResourcesAction()
}
}
| 77
|
Kotlin
|
58
| 48
|
0cc41c620b96a4798adbe2237e48b67269e3e509
| 744
|
cross-cluster-replication
|
Apache License 2.0
|
app/src/main/java/com/example/chatapplication/UserAdapter.kt
|
sohan-beniwal
| 849,731,326
| false
|
{"Kotlin": 25024}
|
package com.example.chatapplication
import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import kotlin.io.path.fileVisitor
class UserAdapter(val context: Context, val userList:ArrayList<User>):
RecyclerView.Adapter<UserAdapter.UserViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
val view : View = LayoutInflater.from(context).inflate(R.layout.user_layout,parent,false)
return UserViewHolder(view)
}
override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
val currentUser = userList[position]
holder.textname.text = currentUser.name
holder.itemView.setOnClickListener{
val intent = Intent(context,ChatActivity::class.java)
intent.putExtra("name",currentUser.name)
intent.putExtra("uid", currentUser.uid)
context.startActivity(intent)
}
}
override fun getItemCount(): Int {
return userList.size
}
class UserViewHolder(itemview: View) : RecyclerView.ViewHolder(itemview){
val textname=itemview.findViewById<TextView>(R.id.recyclerview_name)
}
}
| 0
|
Kotlin
|
0
| 0
|
08782c131506d2a2cc7fd8ed41bd5ec3b853c0f9
| 1,366
|
ChatApplication
|
MIT License
|
server/src/main/kotlin/com/IntelliLangHub/server/utils/merge.kt
|
IntelliLangHub
| 456,304,585
| false
|
{"Kotlin": 33442, "HTML": 16466, "Dockerfile": 296}
|
package com.intellilanghub.server.utils
private data class InjectionKey(
val language: String,
val injectionId: String
)
fun mergeInjectionConfigurations(
configurationsXml: List<String>,
library: String
): String {
val configurations = configurationsXml.map { readInjectionConfiguration(it) }
val merged = mergeInjectionConfigurations(configurations, library)
return writeInjectionConfiguration(merged)
}
fun mergeInjectionConfigurations(
configurations: List<LanguageInjectionConfiguration>,
library: String
): LanguageInjectionConfiguration {
val injectionKeyToPlaces = mutableMapOf<InjectionKey, MutableSet<Place>>()
for (configuration in configurations) {
for (injection in configuration.injections) {
val key = InjectionKey(injection.language, injection.injectorId)
val places = injectionKeyToPlaces.getOrPut(key) { mutableSetOf() }
places.addAll(injection.places)
}
}
val mergedConfiguration = LanguageInjectionConfiguration()
for ((key, places) in injectionKeyToPlaces) {
val injection = Injection()
injection.language = key.language
injection.injectorId = key.injectionId
injection.displayName = "$library ${injection.language}"
injection.places = places.toMutableList()
mergedConfiguration.injections.add(injection)
}
return mergedConfiguration
}
| 1
|
Kotlin
|
0
| 1
|
38f6f485d42e4f1a98721989aaeac371743279f8
| 1,430
|
IntelliLangHub
|
MIT License
|
app/src/main/java/com/mohmmed/mosa/eg/towmmen/data/module/Product.kt
|
M4A28
| 842,519,543
| false
|
{"Kotlin": 877792}
|
package com.mohmmed.mosa.eg.towmmen.data.module
import android.os.Parcelable
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import kotlinx.parcelize.Parcelize
import java.util.Date
@Parcelize
@Entity(tableName = "products", indices = [Index(value = ["barcode"], unique = true)])
data class Product(
@PrimaryKey(autoGenerate = true)
val productId: Int = 0,
val name: String,
var barcode: String, // make it uniq
var cost:Double,
var price: Double,
val description: String,
val imagePath: String = "",
val category: String,
var stockQuantity: Int,
val unit: String = "Unit",
val manufactureDate: Date,
val expireDate: Date,
val createdAt: Date,
val updatedAt: Date = Date()
): Parcelable
| 0
|
Kotlin
|
0
| 0
|
0b4a00de059b042dff209ceecb970695265d706e
| 789
|
Towmmen
|
MIT License
|
korge-foundation/src/korlibs/bignumber/BigNum.kt
|
korlibs
| 80,095,683
| false
|
{"WebAssembly": 14293935, "Kotlin": 9728800, "C": 77092, "C++": 20878, "TypeScript": 12397, "HTML": 6043, "Python": 4296, "Swift": 1371, "JavaScript": 328, "Shell": 254, "CMake": 202, "CSS": 66, "Batchfile": 41}
|
package korlibs.bignumber
import korlibs.bignumber.ranges.*
import kotlin.math.*
// Big Number
/** Converts this into a [BigNum] */
val Double.bn: BigNum get() = BigNum("$this")
/** Converts this into a [BigNum] */
val Long.bn: BigNum get() = BigNum(this.bi, 0)
/** Converts this into a [BigNum] */
val Int.bn: BigNum get() = BigNum(this.bi, 0)
/** Converts this into a [BigNum] */
val String.bn: BigNum get() = BigNum(this)
/**
* Represents a [BigNum],
* a numeric value with decimal places that is exact.
*
* There are no precision issues like happens with [Float] or [Double] floating point types.
*/
class BigNum(val int: BigInt, val scale: Int) : Comparable<BigNum> {
init {
//println("BigNum($int, $scale) == $this")
}
companion object {
/** Represents 0.0 as a [BigNum] */
val ZERO = BigNum(BigInt(0), 0)
/** Represents 1.0 as a [BigNum] */
val ONE = BigNum(BigInt(1), 0)
/** Represents 2.0 as a [BigNum] */
val TWO = BigNum(BigInt(2), 0)
/** Creates a [BigNum] from a string [str] */
operator fun invoke(str: String): BigNum {
val str = str.lowercase()
//val ss = if (str.contains('.')) str.trimEnd('0') else str
val exponentPartStr = str.substringAfter('e', "").takeIf { it.isNotEmpty() }?.trimStart('+')
val ss = str.substringBefore('e')
val point = ss.indexOf('.')
val strBase = ss.replace(".", "")
val exponent = exponentPartStr?.toInt() ?: 0
val int = BigInt(strBase)
return if (point < 0) {
BigNum(int, -exponent)
} else {
BigNum(int, ss.length - point - 1 - exponent)
}
}
}
/**
* Converts the internal scale of this BigNum to [otherScale] while keeping the same value.
*
* For example:
* ```kotlin
* assertEquals("0.0010", "0.001".bn.convertToScale(4).toString())
* ```
*/
fun convertToScale(otherScale: Int): BigNum = when {
this.scale == otherScale -> this
otherScale > this.scale -> BigNum(int * (10.bi pow (otherScale - this.scale)), otherScale)
else -> BigNum(int / (10.bi pow (this.scale - otherScale)), otherScale)
}
/** Performs this + [other] returning a [BigNum], if the scale is different for both numbers, it finds a common one */
operator fun plus(other: BigNum): BigNum = binary(other, BigInt::plus)
/** Performs this - [other] returning a [BigNum], if the scale is different for both numbers, it finds a common one */
operator fun minus(other: BigNum): BigNum = binary(other, BigInt::minus)
/** Performs this * [other] returning a [BigNum], the scale ends being the sum of both scales */
operator fun times(other: BigNum): BigNum =
BigNum(this.int * other.int, this.scale + other.scale)
/** Performs this / [other] returning a [BigNum] */
//operator fun div(other: BigNum): BigNum = div(other, other.int.significantBits / 2)
operator fun div(other: BigNum): BigNum = div(other, 0)
/** Performs this / [other] returning a [BigNum] using a specific [precision] */
fun div(other: BigNum, precision: Int): BigNum {
val scale = (10.bi pow (other.scale + precision))
val li = this.int * scale
val ri = other.int
val res = li / ri
return BigNum(res, this.scale) * BigNum(1.bi, precision)
}
/** Performs this ** [exponent] */
infix fun pow(exponent: Int) = pow(exponent, 32)
/** Performs this ** [exponent] with a specific [precision] */
fun pow(exponent: Int, precision: Int): BigNum {
//if (exponent < 0) return ONE.div(this.pow(-exponent, precision), precision)
if (exponent < 0) return ONE.div(this.pow(-exponent, precision), 0)
var result = ONE
var base = this
var exp = exponent
while (exp != 0) {
if ((exp and 1) != 0) result *= base
exp = exp shr 1
base *= base
}
return result
}
override operator fun compareTo(other: BigNum): Int {
val commonScale = this.commonScale(other)
return this.convertToScale(commonScale).int.compareTo(other.convertToScale(commonScale).int)
}
/** Creates a [ClosedBigNumRange] between this and [that] */
operator fun rangeTo(that: BigNum): ClosedBigNumRange = ClosedBigNumRange(
start = this,
endInclusive = that
)
override fun hashCode(): Int = int.hashCode() + 3 * scale.hashCode()
override fun equals(other: Any?): Boolean = (other is BigNum) && this.compareTo(other) == 0
private fun commonScale(other: BigNum) = max(this.scale, other.scale)
private inline fun binary(other: BigNum, callback: (l: BigInt, r: BigInt) -> BigInt): BigNum {
val commonScale = this.commonScale(other)
val l = this.convertToScale(commonScale)
val r = other.convertToScale(commonScale)
val li = l.int
val ri = r.int
return BigNum(callback(li, ri), commonScale)
}
override fun toString(): String {
val isNegative = int.isNegative
val out = "${int.abs()}"
val pos = out.length - scale
val negativePart = if (isNegative) "-" else ""
return negativePart + when {
pos <= 0 -> "0." + "0".repeat(-pos) + out
pos >= out.length -> out + "0".repeat(pos - out.length)
else -> (out.substring(0, pos) + "." + out.substring(pos)).trimEnd('.')
}
}
/** Converts this [BigInt] effectively losing the decimal places */
fun toBigInt(): BigInt = convertToScale(0).int
/** Converts this [BigInt] doing flooring when there are decimals */
fun toBigIntFloor(): BigInt = toBigInt()
/** Converts this [BigInt] doing ceiling when there are decimals */
fun toBigIntCeil(): BigInt {
val it = this.toBigInt()
val decimal = decimalPart
return if (decimal.isZero) it else (it + 1.bi)
}
/** Converts this [BigInt] doing rounding when there are decimals */
fun toBigIntRound(): BigInt {
val firstDigit = decimalPart / 10.bi.pow(scale - 1)
return if (firstDigit.toInt() >= 5) toBigIntCeil() else toBigIntFloor()
}
/** Returns the decimal part as a [BigInt] of this BigNum so for `1.9123.bn` it will return `9123.bi` */
val decimalPart: BigInt
get() = int % 10.bi.pow(scale)
}
| 444
|
WebAssembly
|
121
| 2,207
|
dc3d2080c6b956d4c06f4bfa90a6c831dbaa983a
| 6,459
|
korge
|
Apache License 2.0
|
01-Fizzbuzz/src/test/kotlin/com/ikarimeister/kotlinkatas/fizzbuzz/FizzBuzzTest.kt
|
IkariMeister
| 255,678,195
| false
| null |
package com.ikarimeister.kotlinkatas.fizzbuzz
import io.kotlintest.matchers.shouldBe
import io.kotlintest.specs.StringSpec
class FizzBuzzTest : StringSpec() {
init {
"Given a 3 When Fizzbuzz is called should return Fizz" {
val input = 3
val actual = fizzbuzz(input)
actual shouldBe "Fizz"
}
"Given a 5 When Fizzbuzz is called Then Return Buzz" {
val input = 5
val actual = fizzbuzz(input)
actual shouldBe "Buzz"
}
"Given A 15 When Fizzbuzz is called Then Return FizzBuzz" {
val input = 15
val actual = fizzbuzz(input)
actual shouldBe "FizzBuzz"
}
"Given A 1 When Fizzbuzz is called Then Return 1" {
val input = 1
val actual = fizzbuzz(input)
actual shouldBe "1"
}
}
}
| 0
|
Kotlin
|
0
| 0
|
6b7f7e8bc8226ef18c1562361c2163eb6651378a
| 889
|
KatasKotlin
|
Apache License 2.0
|
spoogle-backend/src/test/kotlin/no/nav/helse/spoogle/tree/TreeTest.kt
|
navikt
| 636,249,373
| false
| null |
package no.nav.helse.spoogle.tree
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import no.nav.helse.spoogle.tree.Identifikatortype.*
import org.intellij.lang.annotations.Language
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
internal class TreeTest {
@Test
fun `to json`() {
val rootNode = Node("fnr", FØDSELSNUMMER)
val childNode1 = Node("orgnr1", ORGANISASJONSNUMMER)
val childNode2 = Node("orgnr2", ORGANISASJONSNUMMER)
val grandChildNode1 = Node("periode1", VEDTAKSPERIODE_ID)
val grandChildNode2 = Node("periode2", VEDTAKSPERIODE_ID)
rootNode parentOf childNode1
rootNode parentOf childNode2
childNode1 parentOf grandChildNode1
childNode2 parentOf grandChildNode2
val tree = Tree.buildTree(rootNode)
val json = jacksonObjectMapper().readTree(tree.toJson())
val expectedJson = jacksonObjectMapper().readTree(expectedJson)
assertEquals(expectedJson, json)
}
@Test
fun `path to - ett fnr`() {
val rootNode = Node("fnr", FØDSELSNUMMER)
val childNode1 = Node("orgnr1", ORGANISASJONSNUMMER)
val childNode2 = Node("orgnr2", ORGANISASJONSNUMMER)
val grandChildNode1 = Node("periode1", VEDTAKSPERIODE_ID)
val grandChildNode2 = Node("periode2", VEDTAKSPERIODE_ID)
rootNode parentOf childNode1
rootNode parentOf childNode2
childNode1 parentOf grandChildNode1
childNode2 parentOf grandChildNode2
val tree = Tree.buildTree(rootNode)
val path1 = tree.pathTo("periode2")
val path2 = tree.pathTo("periode1")
val path3 = tree.pathTo("orgnr1")
assertEquals(listOf("fnr", "orgnr2", "periode2"), path1)
assertEquals(listOf("fnr", "orgnr1", "periode1"), path2)
assertEquals(listOf("fnr", "orgnr1"), path3)
}
@Test
fun `path to - to fnr`() {
val fnrNode1 = Node("fnr1", FØDSELSNUMMER)
val fnrNode2 = Node("fnr2", FØDSELSNUMMER)
val orgnrNode1 = Node("orgnr1", ORGANISASJONSNUMMER)
val orgnrNode2 = Node("orgnr2", ORGANISASJONSNUMMER)
val periodeNode1 = Node("periode1", VEDTAKSPERIODE_ID)
val periodeNode2 = Node("periode2", VEDTAKSPERIODE_ID)
val periodeNode3 = Node("periode3", VEDTAKSPERIODE_ID)
val periodeNode4 = Node("periode4", VEDTAKSPERIODE_ID)
fnrNode1 parentOf orgnrNode1
fnrNode1 parentOf orgnrNode2
orgnrNode1 parentOf periodeNode1
orgnrNode2 parentOf periodeNode2
fnrNode2 parentOf orgnrNode1
orgnrNode1 parentOf periodeNode3
orgnrNode1 parentOf periodeNode4
val tree1 = Tree.buildTree(fnrNode1)
val path1 = tree1.pathTo("periode2")
val path2 = tree1.pathTo("periode1")
val path3 = tree1.pathTo("orgnr1")
val tree2 = Tree.buildTree(fnrNode2)
val path4 = tree2.pathTo("periode4")
assertEquals(listOf("fnr1", "orgnr2", "periode2"), path1)
assertEquals(listOf("fnr1", "orgnr1", "periode1"), path2)
assertEquals(listOf("fnr1", "orgnr1"), path3)
assertEquals(listOf("fnr2", "orgnr1", "periode4"), path4)
}
@Language("JSON")
private val expectedJson = """
{
"id": "fnr",
"type": "FØDSELSNUMMER",
"children": [
{
"id": "orgnr1",
"type": "ORGANISASJONSNUMMER",
"children": [
{
"id": "periode1",
"type": "VEDTAKSPERIODE_ID",
"children": [],
"ugyldig_fra": null
}
],
"ugyldig_fra": null
},
{
"id": "orgnr2",
"type": "ORGANISASJONSNUMMER",
"children": [
{
"id": "periode2",
"type": "VEDTAKSPERIODE_ID",
"children": [],
"ugyldig_fra": null
}
],
"ugyldig_fra": null
}
],
"ugyldig_fra": null
}
"""
}
| 1
|
Kotlin
|
0
| 0
|
4fd961e03092140633a7f41b3750c71bd399bfbd
| 4,383
|
helse-spoogle
|
MIT License
|
reagent/common/src/main/kotlin/reagent/operator/thenReturn.kt
|
MaTriXy
| 118,458,716
| true
|
{"Kotlin": 146969, "Java": 14263, "Shell": 935}
|
package reagent.operator
import reagent.One
import reagent.Task
private val unitSupplier = { Unit }
fun Task.thenReturnUnit(): One<Unit> = TaskThenReturn(this, unitSupplier)
fun <I> Task.thenReturn(item: I): One<I> = TaskThenReturn(this, { item })
fun <I> Task.thenReturn(supplier: () -> I): One<I> = TaskThenReturn(this, supplier)
internal class TaskThenReturn<out I>(
private val upstream: Task,
private val supplier: () -> I
): One<I>() {
override suspend fun produce(): I {
upstream.run()
return supplier()
}
}
| 0
|
Kotlin
|
0
| 0
|
3f12d4227a62cf4623b9797739759bab390f28ab
| 535
|
Reagent
|
Apache License 2.0
|
tmp/arrays/youTrackTests/1112.kt
|
DaniilStepanov
| 228,623,440
| false
| null |
// Original bug: KT-45044
const val kotlin = "1.4.30-M1"
const val kotlinSerialization = "1.0.1"
const val kotlinCoroutines = "1.4.2"
const val ktlintGradlePlugin = "10.0.0"
const val ktor = "1.5.1"
| 1
| null |
11
| 1
|
602285ec60b01eee473dcb0b08ce497b1c254983
| 210
|
bbfgradle
|
Apache License 2.0
|
Steganography/src/main/kotlin/image/ImageHandler.kt
|
damcyb
| 427,749,560
| false
| null |
package image
import RGB_IMAGE_TYPE
import fromBinaryStringToByteArray
import getLSB
import isEven
import isOdd
import toEightBits
import java.awt.Color
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
class ImageHandler(private val path: String) {
val image: BufferedImage = ImageIO.read(File(path))
val colorMatrix: List<Triple<Int, Int, Int>> = readImage()
fun readImage(): List<Triple<Int, Int, Int>> {
val matrix: ArrayList<Triple<Int, Int, Int>> = arrayListOf()
var pixel: Triple<Int, Int, Int>
for (h in 0 until image.height) {
for (w in 0 until image.width) {
pixel = pixelToRgb(h, w)
matrix.add(pixel)
}
}
return matrix.toList()
}
fun writeImage(colorMatrix: List<Triple<Int, Int, Int>>, path: String) {
val bufferedImage: BufferedImage = BufferedImage(image.width, image.height, RGB_IMAGE_TYPE)
var counterWidth: Int = 0
var counterHeight: Int = 0
colorMatrix.forEach { triple ->
bufferedImage.setRGB(counterHeight, counterWidth, rgbToPixel(triple))
if (shouldMoveToNextRow(counterWidth)) {
counterWidth = 0
counterHeight++
} else {
counterWidth++
}
}
ImageIO.write(bufferedImage, "png", File(path))
}
fun encode(input: String): List<Triple<Int, Int, Int>> {
val inputByteArray = ("$input#").toByteArray() // # as termination mark
val encodedPixels: ArrayList<Triple<Int, Int, Int>> = arrayListOf()
var counter: Int = 0
val range: Int = 3
inputByteArray.forEach {
if (counter + range >= colorMatrix.size) throw IllegalArgumentException("Too long input message")
val binaryRepresentationOfSingleCharacter: String = Integer.toBinaryString(it.toInt()).toEightBits()
val threePixels: List<Triple<Int, Int, Int>> = colorMatrix.subList(counter, counter + range)
val modifiedPixels: List<Triple<Int, Int, Int>> = modifyPixels(threePixels, binaryRepresentationOfSingleCharacter)
with(encodedPixels) {
add(modifiedPixels[0])
add(modifiedPixels[1])
add(modifiedPixels[2])
}
counter += 3
}
encodedPixels.addAll(colorMatrix.subList(counter, colorMatrix.lastIndex + 1))
return encodedPixels.toList()
}
fun decode(colorMatrix: List<Triple<Int, Int, Int>>): String {
val lessSignificantBits: String = getAllLessSignificantBits(colorMatrix)
val filteredNoises = lessSignificantBits.filterIndexed { index, _ -> index % 9 != 8 }
val byteArray = filteredNoises.fromBinaryStringToByteArray()
return String(byteArray).substringBefore("#")
}
private fun getAllLessSignificantBits(colorMatrix: List<Triple<Int, Int, Int>>): String {
return colorMatrix.joinToString { triple ->
triple.first.getLSB().toString() + triple.second.getLSB().toString() + triple.third.getLSB().toString()
}.replace(", ", "")
}
fun modifyPixels(threePixels: List<Triple<Int, Int, Int>>, binaryRepresentationOfSingleCharacter: String): List<Triple<Int, Int, Int>> {
val modifiedPixels: ArrayList<Triple<Int, Int, Int>> = arrayListOf()
threePixels.forEachIndexed { index, pixel ->
val red: Int = encodePixelColor(pixel.first, binaryRepresentationOfSingleCharacter[3 * index])
val green: Int = encodePixelColor(pixel.second, binaryRepresentationOfSingleCharacter[3 * index + 1])
val blue: Int = if (isNinthBit(3 * index + 2)) {
encodePixelColor(pixel.third, '0')
} else {
encodePixelColor(pixel.third, binaryRepresentationOfSingleCharacter[3*index + 2])
}
modifiedPixels.add(Triple(red, green, blue))
}
return modifiedPixels
}
fun encodePixelColor(pixelColor: Int, char: Char): Int {
val charBitValue: Int = Character.getNumericValue(char)
if (pixelColor.isEven() && charBitValue == 1) return pixelColor + 1
if (pixelColor.isEven() && charBitValue == 0) return pixelColor
if (pixelColor.isOdd() && charBitValue == 1) return pixelColor
if (pixelColor.isOdd() && charBitValue == 0) return pixelColor - 1
else throw IllegalArgumentException("Illegal char argument")
}
private fun isNinthBit(index: Int) = index >= 8
private fun shouldMoveToNextRow(counterWidth: Int) = counterWidth == image.width - 1
private fun rgbToPixel(pixel: Triple<Int, Int, Int>): Int = 65536 * pixel.first + 256 * pixel.second + pixel.third
private fun pixelToRgb(heightCoordinate: Int, widthCoordinate: Int): Triple<Int, Int, Int> {
val pixel = image.getRGB(heightCoordinate, widthCoordinate)
val color = Color(pixel, true)
return Triple(color.red, color.green, color.blue)
}
}
| 0
|
Kotlin
|
0
| 0
|
1dd03a20e69e1b3f73b03b9e286c9978e1f122a1
| 5,050
|
BasicsOfCryptography
|
MIT License
|
library/src/main/java/com/fevziomurtekin/custom_mapview/adapter/SearchAdapter.kt
|
fevziomurtekin
| 170,517,143
| false
| null |
package com.fevziomurtekin.custom_mapview.adapter
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.RelativeLayout
import android.widget.TextView
import com.fevziomurtekin.custom_mapview.R
import com.fevziomurtekin.custom_mapview.View
import com.fevziomurtekin.custom_mapview.data.Place
class SearchAdapter : RecyclerView.Adapter<SearchAdapter.ViewHolder> {
private var list: List<Place> = ArrayList()
private var activity: View? = null
private var onClickListener: android.view.View.OnClickListener? = null
constructor(list: List<Place>, onClickListener: android.view.View.OnClickListener) {
this.list = list
this.onClickListener = onClickListener
}
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): SearchAdapter.ViewHolder {
val itemView = LayoutInflater.from(p0.getContext()).inflate(R.layout.search_item, p0, false)
return SearchAdapter.ViewHolder(itemView, this.onClickListener!!)
}
override fun getItemCount(): Int {
return list.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.txt_search_item.text = list.get(position).name
holder.btn_search_item.tag = list.get(position)
}
fun updateSearch(arrays: MutableList<Place>) {
this.list = arrays
notifyDataSetChanged()
}
class ViewHolder(
itemView: android.view.View,
onClickListener: android.view.View.OnClickListener
) : RecyclerView.ViewHolder(itemView) {
var btn_search_item: RelativeLayout
var txt_search_item: TextView
init {
btn_search_item = itemView.findViewById(R.id.btn_search_item)
txt_search_item = itemView.findViewById(R.id.txt_search_item)
btn_search_item.setOnClickListener(onClickListener)
}
}
}
| 1
|
Kotlin
|
3
| 5
|
a4e852f3a93a51536708d196542008f269253911
| 1,929
|
custom-mapview
|
Apache License 2.0
|
src/main/kotlin/xyz/chlamydomonos/hyphacraft/entity/entities/SporeCloudEntity.kt
|
Chlamydomonos
| 832,406,228
| false
|
{"Kotlin": 331227, "Java": 6074}
|
package xyz.chlamydomonos.hyphacraft.entity.entities
import net.minecraft.core.particles.ColorParticleOption
import net.minecraft.core.particles.ParticleTypes
import net.minecraft.nbt.CompoundTag
import net.minecraft.network.syncher.EntityDataSerializers
import net.minecraft.network.syncher.SynchedEntityData
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.effect.MobEffectInstance
import net.minecraft.world.effect.MobEffects
import net.minecraft.world.entity.Entity
import net.minecraft.world.entity.EntityType
import net.minecraft.world.entity.LivingEntity
import net.minecraft.world.entity.MobCategory
import net.minecraft.world.level.Level
import net.minecraft.world.phys.AABB
import xyz.chlamydomonos.hyphacraft.entity.ModEntityTags
import xyz.chlamydomonos.hyphacraft.loaders.EffectLoader
import xyz.chlamydomonos.hyphacraft.utils.ColorUtil
import kotlin.math.log2
import kotlin.math.pow
import kotlin.math.roundToInt
class SporeCloudEntity(entityType: EntityType<*>, level: Level) : Entity(entityType, level) {
companion object {
private val TICKS_LEFT = SynchedEntityData.defineId(
SporeCloudEntity::class.java,
EntityDataSerializers.INT
)
private val RANGE = SynchedEntityData.defineId(
SporeCloudEntity::class.java,
EntityDataSerializers.FLOAT
)
val BUILDER = EntityType.Builder.of(::SporeCloudEntity, MobCategory.MISC).fireImmune()
val PARTICLE = ColorParticleOption.create(ParticleTypes.ENTITY_EFFECT, ColorUtil.rgba(0x513560ff))
}
var ticksLeft
get() = entityData.get(TICKS_LEFT)
set(value) { entityData.set(TICKS_LEFT, value) }
var range
get() = entityData.get(RANGE)
set(value) { entityData.set(RANGE, value) }
private var timer = 0
override fun defineSynchedData(builder: SynchedEntityData.Builder) {
builder.define(TICKS_LEFT, 20)
builder.define(RANGE, 1.0f)
}
override fun readAdditionalSaveData(compound: CompoundTag) {
ticksLeft = compound.getInt("ticks_left")
range = compound.getFloat("range")
}
override fun addAdditionalSaveData(compound: CompoundTag) {
compound.putInt("ticks_left", ticksLeft)
compound.putFloat("range", range)
}
override fun tick() {
super.tick()
if (level().isClientSide) {
val particleCount = log2(ticksLeft + 2.0f) * range.pow(3) * 20
for (i in 1..particleCount.roundToInt()) {
level().addParticle(
PARTICLE,
x + random.nextGaussian() * range,
y + random.nextGaussian() * range,
z + random.nextGaussian() * range,
0.0,
0.0,
0.0
)
}
return
}
ticksLeft--
if (ticksLeft <= 0) {
discard()
}
timer++
if (timer < 20) {
return
}
timer = 0
val aabb = AABB.ofSize(position(), range.toDouble(), range.toDouble(), range.toDouble())
(level() as ServerLevel).entities.get(aabb) {
if (it is LivingEntity) {
val effect1 = MobEffectInstance(MobEffects.POISON, 600, 1)
val effect2 = MobEffectInstance(EffectLoader.COVERED_WITH_SPORE, 300, 2)
if (!it.type.`is`(ModEntityTags.HYPHACRAFT_INSECT)) {
it.addEffect(effect1)
}
it.addEffect(effect2)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
ec8000abb44a639e3d3c2aaaf198ad0123beb9fc
| 3,620
|
HyphaCraft
|
MIT License
|
Popular Movies stage 1/app/src/main/java/com/madonasyombua/myapplication/helpers/MovieHelper.kt
|
Madonahs
| 130,854,542
| false
|
{"Java": 437393, "Kotlin": 100566, "HTML": 6160}
|
/*
* Copyright (C) 2018 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.madonasyombua.myapplication.helpers
import android.content.Context
import android.text.format.DateFormat
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
/**
* @author madon
*/
object MovieHelper {
//this class will help me in the date conversion
/**
*
* @param date this is the date to be formatted
* @param format the format
* @return date
* @throws ParseException p
*/
@Throws(ParseException::class)
private fun getDate(date: String, format: String): Date {
val simpleDateFormat = SimpleDateFormat(format)
return simpleDateFormat.parse(date)
}
/**
*
* @param context app
* @param date date to be formatted
* @param format the format
* @return convert date to a string
* @throws ParseException
*/
@JvmStatic
@Throws(ParseException::class)
fun LocalizedDate(context: Context?, date: String, format: String): String {
val dateFormat = DateFormat.getDateFormat(context)
return dateFormat.format(getDate(date, format))
}
}
| 0
|
Java
|
24
| 68
|
c2b9529dc39e98f47fe0a8406d5e086bd4623008
| 1,705
|
Nano-Degree-Projects
|
Apache License 2.0
|
framework/src/main/kotlin/pt/isel/SHORT/html/attribute/Usemap.kt
|
48276AntonioMarques
| 762,862,793
| false
|
{"Kotlin": 290899, "CSS": 6361, "JavaScript": 2091, "HTML": 587}
|
package pt.isel.SHORT.html.attribute
import pt.isel.SHORT.html.base.attribute.Attribute
import pt.isel.SHORT.html.base.attribute.add
/**
* Represents the HTML usemap attribute.
* Description: .
* Supported elements: < img>, <input, object >
*/
fun Attribute.Companion.usemap(value: String) = add("usemap", value)
/**
* Represents the HTML usemap attribute.
* Description: .
* Supported elements: < img>, <input, object >
*/
fun List<Attribute>.usemap(value: String) = add("usemap", value)
| 0
|
Kotlin
|
0
| 1
|
0457515ab97855e4f42f7eeacec53f2919908918
| 500
|
short
|
Apache License 2.0
|
bootstrap/src/main/kotlin/jp/co/soramitsu/bootstrap/controller/EthController.kt
|
BulatSaif
| 188,790,713
| true
|
{"Gradle": 26, "Kotlin": 278, "Shell": 8, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Groovy": 2, "Markdown": 10, "Java": 42, "INI": 23, "Java Properties": 48, "HTML": 1, "CSS": 1, "Dockerfile": 14, "YAML": 19, "Python": 3, "Public Key": 24, "TOML": 1, "JSON": 3, "Gerber Image": 20, "XML": 2}
|
package jp.co.soramitsu.bootstrap.controller
import com.d3.eth.sidechain.util.DeployHelperBuilder
import jp.co.soramitsu.bootstrap.dto.EthWallet
import jp.co.soramitsu.bootstrap.dto.MasterContractResponse
import jp.co.soramitsu.bootstrap.dto.MasterContractsRequest
import mu.KLogging
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.web3j.crypto.Keys
import org.web3j.crypto.Wallet
import org.web3j.crypto.WalletFile
import javax.validation.constraints.NotNull
@RestController
@RequestMapping("/eth")
class EthController {
private val log = KLogging().logger
@PostMapping("/deploy/D3/smartContracts")
fun deployMasterSmartContracts(@NotNull @RequestBody request: MasterContractsRequest): ResponseEntity<MasterContractResponse> {
log.info { "Run predeploy with notary addresses: ${request.notaryEthereumAccounts}" }
var response: MasterContractResponse
return if (request.network != null) {
try {
val deployHelper = DeployHelperBuilder(
request.network.ethereumConfig,
request.network.ethPasswords
).setFastTransactionManager()
.build()
val relayRegistry = deployHelper.deployUpgradableRelayRegistrySmartContract()
val master =
deployHelper.deployUpgradableMasterSmartContract(
relayRegistry.contractAddress,
request.notaryEthereumAccounts
)
val relayImplementation = deployHelper.deployRelaySmartContract(master.contractAddress)
response = MasterContractResponse(
master.contractAddress,
relayRegistry.contractAddress,
relayImplementation.contractAddress,
master.tokens.send()[0].toString()
)
} catch(e:Exception) {
log.error("Cannot deploy smart contract", e)
response = MasterContractResponse(e.javaClass.simpleName, e.message)
}
ResponseEntity.status(HttpStatus.CONFLICT).body(response)
} else {
ResponseEntity.status(HttpStatus.BAD_REQUEST).body(MasterContractResponse(HttpStatus.BAD_REQUEST.name, "Network parameters are not set"))
}
}
@GetMapping("/create/wallet")
fun createWallet(@NotNull @RequestParam password: String): ResponseEntity<EthWallet> {
try {
val wallet: WalletFile = Wallet.createStandard(password, Keys.createEcKeyPair())
return ResponseEntity.ok<EthWallet>(EthWallet(wallet))
} catch (e: Exception) {
log.error("Error creating Ethereum wallet", e)
val response = EthWallet()
response.errorCode = e.javaClass.simpleName
response.message = e.message
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response)
}
}
@GetMapping("/list/servicesWithWallet/d3/{peersCount}")
fun listServiceEthWallets(@PathVariable("peersCount") peersCount: Int): ResponseEntity<List<String>> {
val list = ArrayList<String>()
var depositCounter = peersCount
while (depositCounter > 0) {
list.add("eth-deposit-service-peer$depositCounter")
depositCounter--
}
list.add("eth-registration-service")
list.add("eth-withdrawal-service")
list.add("eth-genesis-wallet")
return ResponseEntity.ok<List<String>>(list)
}
}
| 0
|
Kotlin
|
0
| 0
|
11f0109480372549542f59f71b7e9b1bab604e30
| 3,643
|
notary
|
Apache License 2.0
|
m3-hw4-vafs-app-ktor/src/main/kotlin/ru/beeline/vafs/ktor/plugins/InitAppSettings.kt
|
smith1984
| 587,390,812
| false
| null |
package ru.beeline.vafs.ktor.plugins
import io.ktor.server.application.*
import ru.beeline.vafs.biz.VafsRuleProcessor
import ru.beeline.vafs.common.VafsCorSettings
import ru.beeline.vafs.ktor.VafsAppSettings
import ru.beeline.vafs.ktor.ru.beeline.vafs.ktor.config.getSqlProperties
import ru.beeline.vafs.ktor.ru.beeline.vafs.ktor.plugins.RuleDbType
import ru.beeline.vafs.ktor.ru.beeline.vafs.ktor.plugins.getDatabaseConf
import ru.beeline.vafs.logging.common.LoggerProvider
import ru.beeline.vafs.logging.logback.loggerLogback
import ru.beeline.vafs.repo.inmemory.RuleRepoInMemory
import ru.beeline.vafs.repo.posgresql.RuleRepoPostgresql
import ru.beeline.vafs.repository.stub.RuleRepoStub
fun Application.initAppSettings(): VafsAppSettings {
val corSettings = VafsCorSettings(
loggerProvider = getLoggerProviderConf(),
repoTest = getDatabaseConf(RuleDbType.TEST),
repoProd = getDatabaseConf(RuleDbType.PROD),
repoStub = RuleRepoStub(),
)
return VafsAppSettings(
corSettings = corSettings,
processor = VafsRuleProcessor(corSettings),
)
}
fun getLoggerProviderConf(): LoggerProvider = LoggerProvider {
loggerLogback(it)
}
| 1
|
Kotlin
|
0
| 0
|
69e1d82f348f89d1f7666fbe24a60a8409cc9566
| 1,193
|
otuskotlin
|
Apache License 2.0
|
src/main/kotlin/io/openapiprocessor/core/model/EndpointResponse.kt
|
Tucos
| 378,257,924
| true
|
{"Kotlin": 436041, "Groovy": 215429, "Java": 48775, "TypeScript": 1166, "ANTLR": 688}
|
/*
* Copyright 2019 https://github.com/openapi-processor/openapi-processor-core
* PDX-License-Identifier: Apache-2.0
*/
package io.openapiprocessor.core.model
import io.openapiprocessor.core.model.datatypes.AnyOneOfObjectDataType
import io.openapiprocessor.core.model.datatypes.ResultDataType
/**
* The responses that can be returned by an endpoint method for one (successful) response.
*/
class EndpointResponse(
/**
* success response
*/
private val main: Response,
/**
* additional (error) responses
*/
private val errors: Set<Response>
) {
val contentType: String
get() = main.contentType
/**
* provides the response type.
*
* If the endpoint has multiple responses and there is no result data type the response type
* is `Object`. If the response has a result data type the response type is `ResultDataType<?>`.
*/
val responseType: String
get() {
return if (hasMultipleResponses()) {
getMultiResponseTypeName()
} else {
getSingleResponseTypeName()
}
}
val description: String?
get() = main.description
/**
* provides the imports required for {@link #getResponseType()}.
*
* @return list of imports
*/
val responseImports: Set<String>
get() {
return if (hasMultipleResponses()) {
getImportsMulti()
} else {
getImportsSingle()
}
}
/**
* returns a list with all content types.
*/
val contentTypes: Set<String>
get() {
val result = mutableSetOf<String>()
if (!main.empty) {
result.add(main.contentType)
}
errors.forEach {
result.add(it.contentType)
}
return result
}
/**
* if this response has multiple types.
*/
private fun hasMultipleResponses(): Boolean {
if (main.responseType is AnyOneOfObjectDataType) {
return true
}
return errors.isNotEmpty()
}
/**
* Object or ResultDataType<?> if wrapped
*/
private fun getMultiResponseTypeName(): String {
val rt = main.responseType
if (rt is ResultDataType) {
return rt.getNameMulti()
}
return "Object"
}
private fun getSingleResponseTypeName(): String = main.responseType.getTypeName()
private fun getImportsMulti(): Set<String> {
val rt = main.responseType
return if (rt is ResultDataType) {
rt.getImportsMulti()
} else {
emptySet()
}
}
private fun getImportsSingle(): Set<String> {
val imports = mutableSetOf<String>()
imports.addAll (main.imports)
errors.forEach {
imports.addAll (it.imports)
}
return imports
}
}
| 0
|
Kotlin
|
0
| 0
|
c810c7b03c5f6fab590065f95f72dae5ce1eb7fe
| 2,965
|
openapi-processor-core
|
Apache License 2.0
|
agp-7.1.0-alpha01/tools/base/profgen/profgen/src/test/kotlin/com/android/tools/profgen/DexFileParserTest.kt
|
jomof
| 502,039,754
| true
|
{"Markdown": 63, "Java Properties": 56, "Shell": 31, "Batchfile": 12, "Proguard": 30, "CMake": 10, "Kotlin": 3443, "C++": 594, "Java": 4446, "HTML": 34, "Makefile": 14, "RenderScript": 22, "C": 30, "JavaScript": 2, "CSS": 3, "INI": 11, "Filterscript": 11, "Prolog": 1, "GLSL": 1, "Gradle Kotlin DSL": 5, "Python": 12, "Dockerfile": 2}
|
/*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.profgen
import com.android.testutils.TestUtils
import com.google.common.truth.Truth.assertThat
import org.junit.Test
private const val STRING = "Ljava/lang/String;"
private const val OBJECT = "Ljava/lang/Object;"
class DexFileParserTest {
private val PATH = "tools/base/profgen/profgen/testData/hello.jar"
@Test
fun test() {
val apk = Apk(TestUtils.resolveWorkspacePath(PATH).toFile())
assertThat(apk.dexes).hasSize(1)
val dex = apk.dexes[0]
// only one class `Hello` was defined in classes.jar
assertThat(dex.classDefPool).hasLength(1)
assertThat(dex.typePool[dex.classDefPool[0]]).isEqualTo("LHello;")
val voidMethod = DexMethod("LHello;", "voidMethod", DexPrototype("V", emptyList()))
val intMethod = DexMethod("LHello;", "method", DexPrototype("I", listOf(STRING)))
val strLength = DexMethod(STRING, "length", DexPrototype("I", emptyList()))
val objInit = DexMethod(OBJECT, "<init>", DexPrototype("V", emptyList()))
val helloInit = DexMethod("LHello;", "<init>", DexPrototype("V", emptyList()))
assertThat(dex.methodPool).isEqualTo(listOf(
helloInit, intMethod, voidMethod, objInit, strLength
))
}
@Test
fun testParseParams() {
assertThat(splitParameters("ILa/B;ZILa/C;J")).isEqualTo(
listOf("I", "La/B;", "Z", "I", "La/C;", "J")
)
assertThat(splitParameters("")).isEqualTo(emptyList<String>())
assertThat(splitParameters("IJ")).isEqualTo(listOf("I", "J"))
assertThat(splitParameters("La/C;")).isEqualTo(listOf("La/C;"))
assertThat(splitParameters("LB;La/C;")).isEqualTo(listOf("LB;", "La/C;"))
assertThat(splitParameters("[I[[La/B;IJ[B")).isEqualTo(
listOf("[I", "[[La/B;", "I", "J", "[B")
)
}
}
| 1
| null |
1
| 0
|
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
| 2,490
|
CppBuildCacheWorkInProgress
|
Apache License 2.0
|
reporter/src/main/kotlin/reporters/osCakeReporterModel/utils/IssueList.kt
|
telekom
| 383,432,709
| true
|
{"Kotlin": 4762997, "JavaScript": 293745, "Shell": 118824, "HTML": 118719, "Haskell": 30438, "CSS": 25056, "Python": 21317, "FreeMarker": 20565, "Batchfile": 9453, "Roff": 7585, "Dockerfile": 7005, "Scala": 6656, "Ruby": 4423, "ANTLR": 1883, "Go": 1673, "Java": 559, "Rust": 280, "Emacs Lisp": 191}
|
/*
* Copyright (C) 2021 Deutsche Telekom AG
*
* 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.reporter.reporters.osCakeReporterModel.utils
import com.fasterxml.jackson.annotation.JsonInclude
/**
* keeps lists for issues of type: ERROR, WARN and INFO
*/
@JsonInclude(JsonInclude.Include.NON_EMPTY)
data class IssueList(
val errors: MutableList<Issue> = mutableListOf(),
val warnings: MutableList<Issue> = mutableListOf(),
val infos: MutableList<Issue> = mutableListOf()
)
| 3
|
Kotlin
|
0
| 0
|
f6a9bd00ec3e9d371b211782d564b26318ff1c96
| 1,102
|
ort
|
Apache License 2.0
|
VersionPlugin/src/main/java/com/shuwen/versionplugin/DependencyManager.kt
|
shuwen-hh
| 581,745,693
| false
| null |
package com.shuwen.versionplugin
/**
* 配置和build相关的
*/
object BuildVersion {
const val compileSdkVersion = 33
const val buildToolsVersion = "29.0.2"
const val minSdkVersion = 21
const val targetSdkVersion = 33
const val versionCode = 1
const val versionName = "1.0"
}
const val koin_version= "3.3.2"
const val koin_android_version= "3.3.2"
const val koin_android_compose_version= "3.4.1"
/**
* 项目相关配置
*/
object BuildConfig {
//AndroidX
const val appcompat = "androidx.appcompat:appcompat:1.5.1"
const val constraintLayout = "androidx.constraintlayout:constraintlayout:2.1.4"
const val core_ktx = "androidx.core:core-ktx:1.9.0"
const val material = "com.google.android.material:material:1.7.0"
const val swiperefreshlayout = "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"
const val recyclerview = "androidx.recyclerview:recyclerview:1.1.0"
const val cardview = "androidx.cardview:cardview:1.0.0"
const val databinding = "androidx.databinding:databinding-runtime:7.3.1"
const val navigation_fragment = "androidx.navigation:navigation-fragment-ktx:2.5.3"
const val navigation_ktx = "androidx.navigation:navigation-ui-ktx:2.5.3"
const val junittest = "androidx.test.ext:junit:1.1.4"
// oKHttp
const val okhttp3 = "com.squareup.okhttp3:okhttp:4.9.0"
const val okhttp3_log = "com.squareup.okhttp3:logging-interceptor:4.9.0"
// retrofit
const val retrofit2 = "com.squareup.retrofit2:retrofit:2.9.0"
const val gson = "com.squareup.retrofit2:converter-gson:2.9.0"
//Depend
const val junit = "junit:junit:4.13.2"
const val espresso_core = "androidx.test.espresso:espresso-core:3.5.0"
const val guava = "com.google.guava:guava:24.1-jre"
const val commons = "org.apache.commons:commons-lang3:3.6"
const val zxing = "com.google.zxing:core:3.3.2"
const val smartRefreshLayout = "io.github.scwang90:refresh-layout-kernel:2.1.0"
const val refreshHeaderClassics = "io.github.scwang90:refresh-header-classics:2.1.0"
//leakcanary
const val leakcanary = "com.squareup.leakcanary:leakcanary-android:2.4"
//jetPack
const val room_runtime = "androidx.room:room-runtime:2.2.5"
const val room_compiler = "androidx.room:room-compiler:2.2.5"
const val room_rxjava2 = "androidx.room:room-rxjava2:2.2.5"
const val lifecycle_extensions = "android.arch.lifecycle:extensions:1.1.1"
const val lifecycle_compiler = "android.arch.lifecycle:compiler:1.1.1"
const val rxlifecycle = "com.trello.rxlifecycle3:rxlifecycle:3.1.0"
const val rxlifecycle_components = "com.trello.rxlifecycle3:rxlifecycle-components:3.1.0"
//Kotlin
const val kotlinx_coroutines_core = "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7"
// Koin for Kotlin
const val koin_core = "io.insert-koin:koin-core:$koin_version"
// Koin for Android
const val koin_android = "io.insert-koin:koin-android:$koin_android_version"
// Koin for jetPack
const val koin_jetpack = "io.insert-koin:koin-androidx-compose:$koin_android_compose_version"
// Glide
const val glide = "com.github.bumptech.glide:glide:4.14.2"
const val glide_compiler = "com.github.bumptech.glide:compiler:4.14.2"
// SwipeRefresh
const val swipe_refresh = "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"
// livedata
const val livedata_ktx = "androidx.lifecycle:lifecycle-livedata-ktx:2.5.1"
// viewModel
const val viewmodel_ktx = "androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1"
// youthBanner
const val youth_banner = "io.github.youth5201314:banner:2.2.2"
const val timber = "com.jakewharton.timber:timber:5.0.1"
}
| 0
|
Kotlin
|
0
| 1
|
f3eaab0da4110614bfbbc904657a8e5afe9f135b
| 3,697
|
swWanAndroid
|
Apache License 2.0
|
common_entities/src/main/java/com/shevelev/wizard_camera/common_entities/enums/Size.kt
|
AlShevelev
| 262,626,159
| false
| null |
package com.shevelev.wizard_camera.common_entities.enums
enum class Size {
SMALL,
NORMAL,
LARGE
}
| 0
|
Kotlin
|
4
| 40
|
ca008839fb157bac0f9b914243ef2a9d7c6a72fa
| 110
|
WizardCamera
|
Apache License 2.0
|
totaladapters/src/main/java/pl/arturborowy/TotalAdapters.kt
|
ArturBorowy
| 188,580,962
| false
| null |
package pl.arturborowy
import android.content.Context
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin
import org.koin.core.context.stopKoin
import org.koin.dsl.module
import pl.arturborowy.util.ViewInflater
import timber.log.Timber
object TotalAdapters {
// Needed to replace the component with a test specific one
internal var applicationModule = module { single { ViewInflater() } }
fun init(context: Context, isDebug: Boolean) {
val applicationContext = context.applicationContext
initLogger(isDebug)
initServiceLocator(applicationContext)
}
private fun initLogger(isDebug: Boolean) {
if (isDebug) {
Timber.plant(Timber.DebugTree())
}
}
private fun initServiceLocator(applicationContext: Context) {
startKoin {
androidLogger()
androidContext(applicationContext)
modules(applicationModule)
}
}
fun destroy() = destroyServiceLocator()
private fun destroyServiceLocator() = stopKoin()
}
| 0
|
Kotlin
|
0
| 5
|
d2090995f767d1c10fc8cdb1eca6cbc1df031ed6
| 1,125
|
total-adapters
|
MIT License
|
app/src/main/kotlin/su/katso/synonym/common/usecases/GetLoginParamsUseCase.kt
|
dakatso
| 158,115,410
| false
|
{"Kotlin": 57799}
|
package su.katso.synonym.common.usecases
import android.content.SharedPreferences
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import su.katso.synonym.auth.AuthController.LoginParams
import su.katso.synonym.common.arch.SingleUseCase
class GetLoginParamsUseCase(
private val preferences: SharedPreferences
) : SingleUseCase<LoginParams>() {
override val single: Single<LoginParams> = getParams()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
private fun getParams(): Single<LoginParams> {
return Single.fromCallable {
LoginParams(
preferences.getString(PREF_AUTH_INPUT_ADDRESS, "").orEmpty(),
preferences.getString(PREF_AUTH_INPUT_ACCOUNT, "").orEmpty(),
preferences.getString(PREF_AUTH_INPUT_PASSWORD, "").orEmpty()
)
}
}
companion object {
const val PREF_AUTH_INPUT_ADDRESS: String = "pref_auth_input_address"
const val PREF_AUTH_INPUT_ACCOUNT: String = "pref_auth_input_account"
const val PREF_AUTH_INPUT_PASSWORD: String = "<PASSWORD>"
}
}
| 0
|
Kotlin
|
0
| 1
|
38137f03e94d1c1c864d0faebaffd3cddac70ddc
| 1,208
|
Synonym
|
Apache License 2.0
|
app/src/main/java/tech/salroid/filmy/data/local/model/MovieData.kt
|
salRoid
| 64,316,425
| false
| null |
package tech.salroid.filmy.data.local.model
data class MovieData(var id: String, var movie: String? = null, var poster: String? = null)
| 1
|
Kotlin
|
180
| 733
|
c6ac0c3b47964e552b8d44a0b586e1ce3b418a9a
| 136
|
Filmy
|
Apache License 2.0
|
app/src/main/java/com/example/crud/NewWordActivity.kt
|
SawThanDar18
| 188,378,824
| false
| null |
package com.example.crud
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.widget.Button
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.room.Room
import kotlinx.android.synthetic.main.activity_new_word.view.*
import kotlinx.android.synthetic.main.recyclerview_item.*
import kotlin.concurrent.thread
class NewWordActivity : AppCompatActivity(){
private lateinit var editTitleView: EditText
private lateinit var editNoteView : EditText
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_new_word)
editTitleView = findViewById(R.id.edit_word)
editNoteView = findViewById(R.id.edit_note)
val button = findViewById<Button>(R.id.button_save)
button.setOnClickListener {
val replyIntent = Intent()
if (TextUtils.isEmpty(editTitleView.text) || TextUtils.isEmpty(editNoteView.text)) {
setResult(Activity.RESULT_CANCELED, replyIntent)
} else {
val word = editTitleView.text.toString()
val note = editNoteView.text.toString()
replyIntent.putExtra(TITLE, word)
replyIntent.putExtra(NOTES, note)
setResult(Activity.RESULT_OK, replyIntent)
}
finish()
}
}
companion object {
val TITLE = "title"
val NOTES = "notes"
}
}
| 0
|
Kotlin
|
0
| 0
|
83b2b2cb6809e426759bdd7ff1af044862d4e0a8
| 1,815
|
CRUD
|
Apache License 2.0
|
src/main/kotlin/tokyo/aieuo/mineflow/utils/Logger.kt
|
aieuo
| 364,472,156
| false
| null |
package tokyo.aieuo.mineflow.utils
import cn.nukkit.Player
import cn.nukkit.entity.Entity
import tokyo.aieuo.mineflow.Main
object Logger {
fun warning(message: String, player: Entity? = null) {
if (player is Player) {
player.sendMessage("§e$message")
} else {
Main.instance.logger?.warning(message)
}
}
fun info(message: String, player: Entity? = null) {
if (player is Player) {
player.sendMessage(message)
} else {
Main.instance.logger?.info(message)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
9c2ef7133d84c5d9b6f4336463d9e1d56442924a
| 574
|
Mineflow-Kotlin
|
MIT License
|
app/src/main/kotlin/batect/config/io/deserializers/IncludeSetSerializer.kt
|
hpcsc
| 252,945,272
| true
|
{"Gradle": 23, "INI": 2, "Markdown": 37, "YAML": 61, "Shell": 32, "Text": 6, "Ignore List": 2, "Batchfile": 8, "Git Attributes": 1, "EditorConfig": 1, "Kotlin": 588, "Dockerfile": 31, "HTML": 5, "Groovy": 4, "PowerShell": 3, "Java": 1, "Python": 3, "JSON": 1, "CSS": 2, "JavaScript": 1}
|
/*
Copyright 2017-2020 <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 batect.config.io.deserializers
import batect.config.io.ConfigurationException
import batect.os.PathResolutionResult
import batect.os.PathType
import com.charleskorn.kaml.YamlInput
import kotlinx.serialization.CompositeDecoder
import kotlinx.serialization.Decoder
import kotlinx.serialization.Encoder
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialDescriptor
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.builtins.set
import java.nio.file.Path
object IncludeSetSerializer : KSerializer<Set<Path>> {
private val elementSerializer = String.serializer()
private val elementDescriptor = elementSerializer.descriptor
override val descriptor: SerialDescriptor = elementSerializer.set.descriptor
override fun deserialize(decoder: Decoder): Set<Path> {
val input = decoder.beginStructure(descriptor, elementSerializer)
val result = read(input)
input.endStructure(descriptor)
return result
}
private fun read(input: CompositeDecoder): Set<Path> {
val soFar = mutableSetOf<Path>()
while (true) {
val currentIndex = input.decodeElementIndex(descriptor)
if (currentIndex == CompositeDecoder.READ_DONE) {
break
}
soFar.add(readSingle(input, currentIndex))
}
return soFar
}
private fun readSingle(input: CompositeDecoder, index: Int): Path {
val elementDeserializer = input.context.getContextual(PathResolutionResult::class)!!
val resolutionResult = input.decodeSerializableElement(elementDescriptor, index, elementDeserializer)
val location = (input as YamlInput).getCurrentLocation()
when (resolutionResult) {
is PathResolutionResult.Resolved -> when (resolutionResult.pathType) {
PathType.File -> return resolutionResult.absolutePath
PathType.DoesNotExist -> throw ConfigurationException("Included file '${resolutionResult.originalPath}' (resolved to '${resolutionResult.absolutePath}') does not exist.", location.line, location.column)
else -> throw ConfigurationException("'${resolutionResult.originalPath}' (resolved to '${resolutionResult.absolutePath}') is not a file.", location.line, location.column)
}
is PathResolutionResult.InvalidPath -> throw ConfigurationException("Include path '${resolutionResult.originalPath}' is not a valid path.", location.line, location.column)
}
}
override fun serialize(encoder: Encoder, value: Set<Path>) {
val output = encoder.beginCollection(descriptor, value.size)
value.forEachIndexed { index, path ->
output.encodeStringElement(elementDescriptor, index, path.toString())
}
output.endStructure(descriptor)
}
}
| 0
|
Kotlin
|
0
| 0
|
87fc5e91c9eee765a3a38b84a7d5be77fe391f1d
| 3,456
|
batect
|
Apache License 2.0
|
LudoCompose/app/src/main/java/hu/bme/aut/android/ludocompose/ui/model/ScoreUi.kt
|
Kis-Benjamin
| 693,261,151
| false
|
{"Kotlin": 358575, "Shell": 2693, "Dockerfile": 2134}
|
/*
* Copyright © 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package hu.bme.aut.android.ludocompose.ui.model
import hu.bme.aut.android.ludocompose.session.model.ScoreDTO
data class ScoreUi internal constructor(
val name: String = "",
val winCount: String = "",
)
fun ScoreDTO.toUiModel() = ScoreUi(
name = name,
winCount = winCount.toString()
)
| 0
|
Kotlin
|
0
| 0
|
731f304280ad30068c0149fdd04a94213ebea2e1
| 896
|
Ludo
|
Apache License 2.0
|
app/src/androidTest/java/com/vstorchevyi/codewars/server/MockServerTestRule.kt
|
LStudioO
| 653,597,932
| false
| null |
package com.vstorchevyi.codewars.server
import okhttp3.mockwebserver.Dispatcher
import okhttp3.mockwebserver.MockWebServer
import org.junit.rules.TestWatcher
import org.junit.runner.Description
class MockServerTestRule(
private val port: Int,
private val responseDispatcher: Dispatcher,
) : TestWatcher() {
private val server = MockWebServer().apply {
dispatcher = responseDispatcher
}
override fun starting(description: Description) {
server.start(port)
}
override fun finished(description: Description) {
server.shutdown()
}
fun setDispatcher(dispatcher: Dispatcher) {
server.dispatcher = dispatcher
}
}
| 0
|
Kotlin
|
0
| 2
|
4b7ad630dbd4838b66e560f463b025e79327bebd
| 683
|
CodeWarsChallengeViewer
|
Apache License 2.0
|
app/src/main/java/com/liuyuchuan/easymusic/utils/CheckableItemViewBinder.kt
|
SirLYC
| 133,898,818
| false
|
{"Kotlin": 135440}
|
package com.liuyuchuan.easymusic.utils
import android.support.v7.widget.AppCompatCheckBox
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CompoundButton
import com.liuyuchuan.easymusic.R
import kotlinx.android.synthetic.main.item_checkable.view.*
import me.drakeet.multitype.ItemViewBinder
/**
* Created by <NAME> on 2018/5/9.
*/
abstract class CheckableItemViewBinder<T, VH : RecyclerView.ViewHolder>(
private val onRealItemClickListener: OnRealItemClickListener<T>
) : ItemViewBinder<CheckableItem<T>, CheckableItemViewBinder.ViewHolder<T, VH>>() {
var enableCheck = false
set(value) {
val old = field
field = value
if (value xor old) {
adapter.items.forEachIndexed { index, item ->
if (item is CheckableItem<*>) {
adapter.notifyItemChanged(index)
}
}
}
}
override fun onCreateViewHolder(inflater: LayoutInflater, parent: ViewGroup): ViewHolder<T, VH> {
return inflater.inflate(R.layout.item_checkable, parent, false).let {
ViewHolder(it, onCreateRealView(inflater, it.container_real_item), onRealItemClickListener)
}
}
override fun onBindViewHolder(holder: ViewHolder<T, VH>, item: CheckableItem<T>) {
holder.bind(item, enableCheck)
onBindRealViewHolder(holder.realHolder, item.realItem)
}
abstract fun onCreateRealView(inflater: LayoutInflater, parent: ViewGroup): VH
abstract fun onBindRealViewHolder(holder: VH, item: T)
class ViewHolder<in T, out VH>(view: View,
val realHolder: VH,
private val onRealItemClickListener: OnRealItemClickListener<T>) : RecyclerView.ViewHolder(view),
CompoundButton.OnCheckedChangeListener, View.OnClickListener {
private val checkBox: AppCompatCheckBox = itemView.findViewById(R.id.accb_selectable_item)
private var checkableItem: CheckableItem<T>? = null
private var enableCheck = false
init {
checkBox.setOnCheckedChangeListener(this)
itemView.setOnClickListener(this)
}
fun bind(checkableItem: CheckableItem<T>, enableCheck: Boolean) {
this.checkableItem = checkableItem
this.enableCheck = enableCheck
if (checkableItem.checkable && enableCheck) {
checkBox.visibility = View.VISIBLE
checkBox.isChecked = checkableItem.isChecked
} else {
checkBox.visibility = View.GONE
checkBox.isChecked = false
checkableItem.isChecked = false
}
}
override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
checkableItem?.isChecked = isChecked
}
override fun onClick(v: View) {
when (v) {
itemView -> if (enableCheck) {
checkBox.performClick()
} else {
checkableItem?.realItem?.let(onRealItemClickListener::onCheckRealItemClicked)
}
}
}
}
fun isCheckAll(): Boolean {
if (!enableCheck) {
return false
}
adapter.items.forEach {
if (it is CheckableItem<*> && !it.isChecked) {
return false
}
}
return true
}
fun checkAll() {
if (!enableCheck) {
return
}
adapter.items.forEachIndexed { index, item ->
if (item is CheckableItem<*> && item.checkable) {
item.isChecked = true
adapter.notifyItemChanged(index)
}
}
}
fun uncheckAll() {
if (!enableCheck) {
return
}
adapter.items.forEachIndexed { index, item ->
if (item is CheckableItem<*> && item.checkable) {
item.isChecked = false
adapter.notifyItemChanged(index)
}
}
}
fun checkedItemList(): List<CheckableItem<T>> {
val list = mutableListOf<CheckableItem<T>>()
if (!enableCheck) {
return list
}
adapter.items.forEach { item ->
if (item is CheckableItem<*> && item.isChecked) {
@Suppress("UNCHECKED_CAST")
list.add(item as CheckableItem<T>)
}
}
return list
}
interface OnRealItemClickListener<in T> {
fun onCheckRealItemClicked(realItem: T)
}
}
| 0
|
Kotlin
|
0
| 2
|
bfa45de49d2ab6d26b29afa0d1fbd87b6ca1cc1f
| 4,685
|
EasyMusic
|
Apache License 2.0
|
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/covidcertificate/valueset/valuesets/ValueSetsStorage.kt
|
corona-warn-app
| 268,027,139
| false
| null |
package de.rki.coronawarnapp.covidcertificate.valueset.valuesets
import androidx.annotation.VisibleForTesting
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import com.google.gson.Gson
import dagger.Reusable
import de.rki.coronawarnapp.covidcertificate.valueset.ValueSetsDataStore
import de.rki.coronawarnapp.util.coroutine.AppScope
import de.rki.coronawarnapp.util.datastore.dataRecovering
import de.rki.coronawarnapp.util.datastore.distinctUntilChanged
import de.rki.coronawarnapp.util.datastore.trySetValue
import de.rki.coronawarnapp.util.serialization.BaseGson
import de.rki.coronawarnapp.util.serialization.fromJson
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import timber.log.Timber
import javax.inject.Inject
@Reusable
class ValueSetsStorage @Inject constructor(
@BaseGson private val gson: Gson,
@ValueSetsDataStore private val dataStore: DataStore<Preferences>,
@AppScope var appScope: CoroutineScope
) {
private val mutex = Mutex()
init {
appScope.launch {
migration23To24()
}
}
suspend fun load(): ValueSetsContainer = mutex.withLock {
Timber.tag(TAG).v("load()")
val valueSetString = dataStore.dataRecovering.distinctUntilChanged(
key = PKEY_VALUE_SETS_CONTAINER_PREFIX, defaultValue = ""
).first()
return when (valueSetString.isNotEmpty()) {
true -> gson.fromJson(valueSetString)
else -> emptyValueSetsContainer
}.also { loaded -> Timber.v("Loaded value sets container %s", loaded) }
}
suspend fun save(value: ValueSetsContainer) = mutex.withLock {
Timber.tag(TAG).v("save(value=%s)", value)
dataStore.trySetValue(
preferencesKey = PKEY_VALUE_SETS_CONTAINER_PREFIX,
value = gson.toJson(
value, ValueSetsContainer::class.java
)
)
}
// Migration from 2.3.x to 2.4.x: Support for more value sets
private suspend fun migration23To24() {
Timber.v("Checking for leftover and removing it")
dataStore.edit { prefs ->
if (prefs.contains(PKEY_VALUE_SETS_PREFIX)) {
prefs.remove(PKEY_VALUE_SETS_PREFIX)
}
}
}
companion object {
private const val TAG = "ValueSetsStorage"
@VisibleForTesting
val PKEY_VALUE_SETS_PREFIX = stringPreferencesKey("valueset")
@VisibleForTesting
val PKEY_VALUE_SETS_CONTAINER_PREFIX = stringPreferencesKey("valuesets_container")
}
}
| 35
|
Kotlin
|
504
| 2,486
|
7b0eee8d53a090ee0ca585c6a90c4cec570e51d6
| 2,820
|
cwa-app-android
|
Apache License 2.0
|
app/src/main/java/io/github/joaogouveia89/retedex/pokemon/domain/repository/PokemonRepository.kt
|
joaogouveia89
| 776,063,726
| false
|
{"Kotlin": 98910}
|
package io.github.joaogouveia89.retedex.pokemon.domain.repository
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import io.github.joaogouveia89.retedex.core.domain.model.Pokemon
import kotlinx.coroutines.flow.Flow
interface PokemonRepository {
fun getPokemons(pagingConfig: PagingConfig): Flow<PagingData<Pokemon>>
}
| 0
|
Kotlin
|
0
| 0
|
5bea4cd2ddd421cef80d12fc2647f9c8f2b8524e
| 345
|
Retedex
|
MIT License
|
model/src/main/kotlin/Language.kt
|
yole
| 277,303,975
| false
|
{"Kotlin": 300264, "JavaScript": 89708, "Dockerfile": 4260, "CSS": 1014}
|
package ru.yole.etymograph
import java.util.*
open class PhonemeClass(val name: String, var matchingPhonemes: List<String>) {
open fun matchesCurrent(it: PhonemeIterator): Boolean {
return it.current in matchingPhonemes
}
companion object {
val diphthong = object : PhonemeClass("diphthong", emptyList()) {
override fun matchesCurrent(it: PhonemeIterator): Boolean {
val next = it.atRelative(1)
return next != null && it.current + next in it.language.diphthongs
}
}
val specialPhonemeClasses = listOf(diphthong)
const val vowelClassName = "vowel"
}
}
class IntersectionPhonemeClass(name: String, val classList: List<PhonemeClass>)
: PhonemeClass(name, emptyList()) {
override fun matchesCurrent(it: PhonemeIterator): Boolean {
return classList.all { cls -> cls.matchesCurrent(it) }
}
}
class WordCategoryValue(val name: String, val abbreviation: String)
class WordCategory(var name: String, var pos: List<String>, var values: List<WordCategoryValue>)
class Phoneme(val graphemes: List<String>, val sound: String?, val classes: Set<String>)
class PhonemeLookup {
private var digraphs = mutableMapOf<String, Phoneme>()
private var singleGraphemes = mutableMapOf<Char, Phoneme>()
fun clear() {
digraphs.clear()
singleGraphemes.clear()
}
fun add(key: String, phoneme: Phoneme) {
if (key.length > 1) {
digraphs[key] = phoneme
}
else {
singleGraphemes[key[0]] = phoneme
}
}
fun iteratePhonemes(text: String, callback: (String, Phoneme?) -> Unit) {
var offset = 0
while (offset < text.length) {
val digraph = digraphs.keys.firstOrNull { text.startsWith(it, offset) }
if (digraph != null) {
callback(digraph, digraphs[digraph])
offset += digraph.length
}
else {
callback(text.substring(offset, offset + 1), singleGraphemes[text[offset]])
offset++
}
}
}
}
class Language(val name: String, val shortName: String) {
var phonemes = listOf<Phoneme>()
set(value) {
field = value
updatePhonemeClasses()
updateGraphemes()
}
var diphthongs: List<String> = emptyList()
var phonemeClasses = listOf<PhonemeClass>()
private set
var syllableStructures: List<String> = emptyList()
var stressRule: RuleRef? = null
var phonotacticsRule: RuleRef? = null
var orthographyRule: RuleRef? = null
var grammaticalCategories = mutableListOf<WordCategory>()
var wordClasses = mutableListOf<WordCategory>()
var orthoPhonemeLookup = PhonemeLookup()
var phonoPhonemeLookup = PhonemeLookup()
private fun updatePhonemeClasses() {
val phonemeClassMap = mutableMapOf<String, MutableList<String>>()
for (phoneme in phonemes) {
for (cls in phoneme.classes) {
phonemeClassMap.getOrPut(cls) { mutableListOf() }.add(phoneme.sound ?: phoneme.graphemes[0])
}
}
val oldPhonemeClasses = phonemeClasses
phonemeClasses = phonemeClassMap.map { (name, phonemes) ->
oldPhonemeClasses.find { it.name == name }?.also { it.matchingPhonemes = phonemes }
?: PhonemeClass(name, phonemes)
}
}
private fun updateGraphemes() {
orthoPhonemeLookup.clear()
phonoPhonemeLookup.clear()
for (phoneme in phonemes) {
for (g in phoneme.graphemes) {
orthoPhonemeLookup.add(g, phoneme)
}
phonoPhonemeLookup.add(phoneme.sound ?: phoneme.graphemes[0], phoneme)
}
}
fun phonemeClassByName(name: String): PhonemeClass? {
if (' ' in name) {
val subclassNames = name.split(' ')
val subclasses = subclassNames.map { phonemeClassByName(it) ?: return null }
return IntersectionPhonemeClass(name, subclasses)
}
return phonemeClasses.find { it.name == name } ?: PhonemeClass.specialPhonemeClasses.find { it.name == name }
}
fun normalizeWord(text: String): String {
return buildString {
orthoPhonemeLookup.iteratePhonemes(text.lowercase(Locale.FRANCE)) { s, phoneme ->
append(phoneme?.graphemes?.get(0) ?: s)
}
}.removeSuffix("-")
}
fun isNormalizedEqual(ruleProducedWord: Word, attestedWord: Word): Boolean {
return normalizeWord(ruleProducedWord.asOrthographic().text) == normalizeWord(attestedWord.asOrthographic().text)
}
fun findGrammaticalCategory(abbreviation: String): Pair<WordCategory, WordCategoryValue>? {
return findWordCategory(abbreviation, grammaticalCategories)
}
fun findWordClass(abbreviation: String): Pair<WordCategory, WordCategoryValue>? {
return findWordCategory(abbreviation, wordClasses)
}
private fun findWordCategory(abbreviation: String, wordCategories: List<WordCategory>): Pair<WordCategory, WordCategoryValue>? {
for (category in wordCategories) {
val gcValue = category.values.find { it.abbreviation == abbreviation }
if (gcValue != null) {
return category to gcValue
}
}
return null
}
fun findNumberPersonCategories(abbreviation: String): List<Pair<WordCategory, WordCategoryValue?>>? {
if (abbreviation.first().isDigit()) {
val personCatValue = findGrammaticalCategory(abbreviation.take(1)) ?: return null
val numberCatValue = findGrammaticalCategory(abbreviation.drop(1)) ?: return null
return listOf(personCatValue, numberCatValue)
}
return null
}
}
| 0
|
Kotlin
|
1
| 15
|
dcce8284bfd0d021c34b6d89c62b330dc594fb5f
| 5,863
|
etymograph
|
Apache License 2.0
|
base/src/main/java/ja/burhanrashid52/base/api/ApiConstants.kt
|
burhanrashid52
| 127,247,984
| false
| null |
package ja.burhanrashid52.base.api
/**
* Created by <NAME> on 3/1/2018.
*/
object ApiConstants {
internal const val HTTP_CONNECT_TIMEOUT = 60 * 1000
internal const val HTTP_READ_TIMEOUT = 60 * 1000
}
| 1
|
Kotlin
|
144
| 866
|
ae374a6e2dac3a11f9539213160aec7e9a671f14
| 210
|
YoutubeUX
|
Apache License 2.0
|
Kotlin/Code/Kotlin-Github/app/src/main/java/android/support/v7/widget/TintableToggleButton.kt
|
hiloWang
| 203,300,702
| false
| null |
package android.support.v7.widget
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.PorterDuff.Mode
import android.graphics.drawable.Drawable
import android.support.annotation.DrawableRes
import android.support.v4.view.TintableBackgroundView
import android.util.AttributeSet
import android.widget.ToggleButton
class TintableToggleButton
@JvmOverloads
constructor(context: Context, attrs: AttributeSet?= null, defStyleAttr: Int = 0)
: ToggleButton(TintContextWrapper.wrap(context), attrs, defStyleAttr), TintableBackgroundView {
private var backgroundTintHelper: AppCompatBackgroundHelper? = null
init {
backgroundTintHelper = AppCompatBackgroundHelper(this)
backgroundTintHelper?.loadFromAttributes(attrs, defStyleAttr)
}
override fun setSupportBackgroundTintList(tint: ColorStateList?) {
backgroundTintHelper?.supportBackgroundTintList = tint
}
override fun getSupportBackgroundTintMode() = backgroundTintHelper?.supportBackgroundTintMode
override fun setSupportBackgroundTintMode(tintMode: Mode?) {
backgroundTintHelper?.supportBackgroundTintMode = tintMode
}
override fun getSupportBackgroundTintList() = backgroundTintHelper?.supportBackgroundTintList
override fun setBackgroundResource(@DrawableRes resId: Int) {
super.setBackgroundResource(resId)
backgroundTintHelper?.onSetBackgroundResource(resId)
}
override fun setBackgroundDrawable(background: Drawable?) {
super.setBackgroundDrawable(background)
backgroundTintHelper?.onSetBackgroundDrawable(background)
}
}
| 1
| null |
15
| 4
|
64a637a86f734e4e80975f4aa93ab47e8d7e8b64
| 1,648
|
notes
|
Apache License 2.0
|
app/src/main/java/com/spundev/nezumi/service/DownloadService.kt
|
spun
| 264,310,960
| false
| null |
package com.spundev.nezumi.service
import android.app.IntentService
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.MediaStore
import androidx.core.app.NotificationCompat
import com.spundev.nezumi.R
import okhttp3.OkHttpClient
import okhttp3.Request
import okio.Source
import okio.buffer
import okio.sink
class DownloadService : IntentService("DownloadService") {
companion object {
const val DOWNLOAD_URL = "DOWNLOAD_URI"
const val DOWNLOADING_CHANNEL = "download_Channel"
}
private lateinit var client: OkHttpClient
override fun onCreate() {
super.onCreate()
client = OkHttpClient.Builder()
.addNetworkInterceptor { chain ->
val originalResponse = chain.proceed(chain.request())
originalResponse.newBuilder()
.body(ProgressResponseBody(originalResponse.body!!, progressListener))
.build()
}.build()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(
DOWNLOADING_CHANNEL,
getString(R.string.file_download_notification_channel_name),
NotificationManager.IMPORTANCE_LOW
)
.apply {
description = getString(R.string.file_download_notification_channel_description)
}
// Register the channel with the system
val notificationManager: NotificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(notificationChannel)
val notification = NotificationCompat.Builder(this, DOWNLOADING_CHANNEL)
.setContentTitle("Example IntentService")
.setContentText("Running...")
.setSmallIcon(R.drawable.ic_download_notification_24)
.setCategory(NotificationCompat.CATEGORY_SERVICE)
.build()
startForeground(1, notification)
}
}
override fun onHandleIntent(intent: Intent?) {
// Gets data from the incoming Intent
val downloadUrl = intent?.getStringExtra(DOWNLOAD_URL)
if (downloadUrl != null && downloadUrl != "")
prepareDownload(downloadUrl)
}
private fun prepareDownload(downloadUri: String) {
// Add a specific media item.
val resolver = applicationContext.contentResolver
// Find all audio files on the primary external storage device.
val audioCollection = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
} else {
// On API <= 28, use VOLUME_EXTERNAL instead.
MediaStore.Video.Media.EXTERNAL_CONTENT_URI
}
// Publish a new video.
val newVideoDetails = ContentValues().apply {
put(MediaStore.Video.Media.DISPLAY_NAME, "video")
put(
MediaStore.Video.Media.DATE_ADDED,
System.currentTimeMillis() / 1000
) // should be in unit of seconds
put(
MediaStore.Video.Media.DATE_MODIFIED,
System.currentTimeMillis() / 1000
) // should be in unit of seconds
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
put(MediaStore.Video.Media.IS_PENDING, 1)
}
}
// Keeps a handle to the new song's URI in case we need to modify it later.
val newVideoUri = resolver.insert(audioCollection, newVideoDetails)
val outputStream = resolver.openOutputStream(newVideoUri!!, "w")
val request = Request.Builder()
.url(downloadUri)
.build()
client.newCall(request).execute().use { response ->
// https://stackoverflow.com/a/29012988
val sink = outputStream!!.sink().buffer()
sink.writeAll(response.body?.source() as Source)
sink.close()
// Now that we're finished, release the "pending" status, and allow other apps
// to play the video.
newVideoDetails.apply {
clear()
put(MediaStore.Video.Media.SIZE, response.body!!.contentLength()) // should be in unit of bytes
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
put(MediaStore.Audio.Media.IS_PENDING, 0)
}
}.also { details ->
resolver.update(newVideoUri, details, null, null)
}
}
}
private val progressListener = object : ProgressResponseBody.ProgressListener {
override fun update(bytesRead: Long, contentLength: Long, done: Boolean) {
if (done) {
println("completed")
} else {
if (contentLength != -1L) {
println("completed" + ((100 * bytesRead) / contentLength))
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
a9615727c62e7533e18590cb6d4a0fc6cd38d0a1
| 5,272
|
android-nezumi-ref
|
MIT License
|
shared/core/src/wasmJsMain/kotlin/com/paligot/confily/core/agenda/FeaturesActivatedDaoSettings.kt
|
GerardPaligot
| 444,230,272
| false
|
{"Kotlin": 1063266, "Swift": 126158, "Shell": 1148, "Dockerfile": 576, "HTML": 338, "CSS": 102}
|
package com.paligot.confily.core.agenda
import com.paligot.confily.core.events.FeaturesActivatedQueries
import com.paligot.confily.core.schedules.SessionQueries
import com.paligot.confily.models.ui.ScaffoldConfigUi
import kotlinx.collections.immutable.toImmutableList
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flow
class FeaturesActivatedDaoSettings(
private val featuresActivatedQueries: FeaturesActivatedQueries,
private val sessionQueries: SessionQueries
) : FeaturesActivatedDao {
override fun fetchScaffoldConfig(eventId: String?): Flow<ScaffoldConfigUi> {
return if (eventId != null) {
fetchFeatures(eventId)
} else {
flow { ScaffoldConfigUi() }
}
}
private fun fetchFeatures(eventId: String): Flow<ScaffoldConfigUi> = combine(
featuresActivatedQueries.selectFeatures(eventId),
sessionQueries.selectDays(eventId),
transform = { features, days ->
ScaffoldConfigUi(
hasNetworking = false,
hasSpeakerList = true,
hasPartnerList = features?.hasPartnerList ?: false,
hasMenus = features?.hasMenus ?: false,
hasQAndA = features?.hasQanda ?: false,
hasBilletWebTicket = false,
hasProfile = false,
agendaTabs = days.toImmutableList(),
hasUsersInNetworking = false
)
}
)
}
| 8
|
Kotlin
|
6
| 142
|
7694571716b8cd67970d42f5cdd7fa8f3306ddd9
| 1,509
|
Confily
|
Apache License 2.0
|
Kotlin/src/main/kotlin/core/Builder3D.kt
|
tgrundtvig
| 322,026,545
| false
|
{"OpenSCAD": 155596, "Java": 96682, "Kotlin": 8414}
|
package core
interface Builder3D<Library>
{
fun build(lib : Library): Component3D
}
| 0
|
OpenSCAD
|
1
| 0
|
bab446f889af12908ceb368fdcf4ba6d57cb4f7e
| 87
|
OpenBuildSystem
|
MIT License
|
library-remoteservice-coroutines/src/main/java/ru/fabit/remoteservicecoroutines/remoteservice/RemoteServiceErrorHandler.kt
|
FabitMobile
| 457,807,988
| false
|
{"Kotlin": 14159, "Java": 275}
|
package ru.fabit.remoteservicecoroutines.remoteservice
import org.json.JSONObject
interface RemoteServiceErrorHandler {
fun getUserMessage(jsonObject: JSONObject): String
fun getCode(jsonObject: JSONObject): String
fun getErrorName(jsonObject: JSONObject): String
fun handleError(throwable: Throwable, requestPath: String?)
}
| 0
|
Kotlin
|
0
| 0
|
95b0bc3f952bbb8cd50f9251d45c183fe3e5e903
| 343
|
remoteservice-coroutines
|
MIT License
|
src/main/kotlin/sk/vildibald/polls/controller/PerformerTypeController.kt
|
softveroveinzinierstvo2016
| 180,311,268
| false
| null |
package sk.vildibald.polls.controller
import sk.vildibald.polls.payload.PerformerTypeResponse
import sk.vildibald.polls.security.UserPrincipal
interface PerformerTypeController {
fun allTypes():
List<PerformerTypeResponse>
}
| 1
| null |
1
| 1
|
8692b3cbca52004ae8c4f720c5b4bbb1b044bdab
| 243
|
AIS_projekt_BE
|
BSD Zero Clause License
|
src/test/kotlin/org/springdoc/openapi/gradle/plugin/OpenApiGradlePluginTest.kt
|
springdoc
| 236,890,806
| false
| null |
package org.springdoc.openapi.gradle.plugin
import com.beust.klaxon.JsonObject
import com.beust.klaxon.Parser
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import com.fasterxml.jackson.module.kotlin.KotlinModule
import org.gradle.internal.impldep.org.apache.commons.lang.RandomStringUtils
import org.gradle.testkit.runner.BuildResult
import org.gradle.testkit.runner.GradleRunner
import org.gradle.testkit.runner.TaskOutcome
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import java.io.File
import java.io.FileReader
import java.nio.file.Files
class OpenApiGradlePluginTest {
private val projectTestDir = Files.createTempDirectory("acceptance-project").toFile()
private val buildFile = File(projectTestDir, "build.gradle")
private val projectBuildDir = File(projectTestDir, "build")
private val pathsField = "paths"
private val openapiField = "openapi"
private val baseBuildGradle = """plugins {
id 'java'
id 'org.springframework.boot' version '2.7.6'
id 'io.spring.dependency-management' version '1.1.15.RELEASE'
id 'org.springdoc.openapi-gradle-plugin'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springdoc:springdoc-openapi-webmvc-core:1.6.13'
}
""".trimIndent()
@BeforeEach
fun createTemporaryAcceptanceProjectFromTemplate() {
File(javaClass.classLoader.getResource("acceptance-project")!!.path).copyRecursively(projectTestDir)
}
@Test
fun `default build no options`() {
buildFile.writeText(baseBuildGradle)
assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome)
assertOpenApiJsonFile(1)
}
@Test
fun `different output dir`() {
val specialOutputDir = File(projectTestDir, "specialDir")
specialOutputDir.mkdirs()
buildFile.writeText(
"""$baseBuildGradle
openApi{
outputDir = file("${specialOutputDir.toURI().path}")
}
""".trimMargin()
)
assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome)
assertOpenApiJsonFile(1, buildDir = specialOutputDir)
}
@Test
fun `different output file name`() {
val specialOutputJsonFileName = RandomStringUtils.randomAlphanumeric(15)
buildFile.writeText(
"""$baseBuildGradle
openApi{
outputFileName = "$specialOutputJsonFileName"
}
""".trimMargin()
)
assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome)
assertOpenApiJsonFile(1, specialOutputJsonFileName)
}
@Test
fun `using properties`() {
buildFile.writeText(
"""$baseBuildGradle
bootRun {
args = ["--spring.profiles.active=multiple-endpoints", "--some.second.property=someValue"]
}
""".trimMargin()
)
assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome)
assertOpenApiJsonFile(3)
}
@Test
fun `using forked properties via System properties`() {
buildFile.writeText(
"""$baseBuildGradle
bootRun {
systemProperties = System.properties
}
""".trimMargin()
)
assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild("-Dspring.profiles.active=multiple-endpoints")).outcome)
assertOpenApiJsonFile(2)
}
@Test
fun `using forked properties via System properties with customBootRun`() {
buildFile.writeText(
"""$baseBuildGradle
openApi {
customBootRun {
systemProperties = System.properties
}
}
""".trimMargin()
)
assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild("-Dspring.profiles.active=multiple-endpoints")).outcome)
assertOpenApiJsonFile(2)
}
@Test
fun `configurable wait time`() {
buildFile.writeText(
"""$baseBuildGradle
bootRun {
args = ["--spring.profiles.active=slower"]
}
openApi{
waitTimeInSeconds = 60
}
""".trimMargin()
)
assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome)
assertOpenApiJsonFile(1)
}
@Test
fun `using different api url`() {
buildFile.writeText(
"""$baseBuildGradle
bootRun {
args = ["--spring.profiles.active=different-url"]
}
openApi{
apiDocsUrl = "http://localhost:8080/secret-api-docs"
}
""".trimMargin()
)
assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome)
assertOpenApiJsonFile(1)
}
@Test
fun `using different api url via customBootRun`() {
buildFile.writeText(
"""$baseBuildGradle
openApi{
apiDocsUrl = "http://localhost:8080/secret-api-docs"
customBootRun {
args = ["--spring.profiles.active=different-url"]
}
}
""".trimMargin()
)
assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome)
assertOpenApiJsonFile(1)
}
@Test
fun `yaml generation`() {
val outputYamlFileName = "openapi.yaml"
buildFile.writeText(
"""$baseBuildGradle
openApi{
apiDocsUrl = "http://localhost:8080/v3/api-docs.yaml"
outputFileName = "$outputYamlFileName"
}
""".trimMargin()
)
assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome)
assertOpenApiYamlFile(1, outputYamlFileName)
}
@Test
fun `using multiple grouped apis`() {
val outputJsonFileNameGroupA = "openapi-groupA.json"
val outputJsonFileNameGroupB = "openapi-groupB.json"
buildFile.writeText(
"""$baseBuildGradle
bootRun {
args = ["--spring.profiles.active=multiple-grouped-apis"]
}
openApi{
groupedApiMappings = ["http://localhost:8080/v3/api-docs/groupA": "$outputJsonFileNameGroupA",
"http://localhost:8080/v3/api-docs/groupB": "$outputJsonFileNameGroupB"]
}
""".trimMargin()
)
assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome)
assertOpenApiJsonFile(1, outputJsonFileNameGroupA)
assertOpenApiJsonFile(2, outputJsonFileNameGroupB)
}
@Test
fun `using multiple grouped apis with yaml`() {
val outputYamlFileNameGroupA = "openapi-groupA.yaml"
val outputYamlFileNameGroupB = "openapi-groupB.yaml"
buildFile.writeText(
"""$baseBuildGradle
bootRun {
args = ["--spring.profiles.active=multiple-grouped-apis"]
}
openApi{
groupedApiMappings = ["http://localhost:8080/v3/api-docs.yaml/groupA": "$outputYamlFileNameGroupA",
"http://localhost:8080/v3/api-docs.yaml/groupB": "$outputYamlFileNameGroupB"]
}
""".trimMargin()
)
assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome)
assertOpenApiYamlFile(1, outputYamlFileNameGroupA)
assertOpenApiYamlFile(2, outputYamlFileNameGroupB)
}
@Test
fun `using multiple grouped apis should ignore single api properties`() {
val outputJsonFileNameSingleGroupA = "openapi-single-groupA.json"
val outputJsonFileNameGroupA = "openapi-groupA.json"
val outputJsonFileNameGroupB = "openapi-groupB.json"
buildFile.writeText(
"""$baseBuildGradle
bootRun {
args = ["--spring.profiles.active=multiple-grouped-apis"]
}
openApi{
apiDocsUrl = "http://localhost:8080/v3/api-docs/groupA"
outputFileName = "$outputJsonFileNameSingleGroupA"
groupedApiMappings = ["http://localhost:8080/v3/api-docs/groupA": "$outputJsonFileNameGroupA",
"http://localhost:8080/v3/api-docs/groupB": "$outputJsonFileNameGroupB"]
}
""".trimMargin()
)
assertEquals(TaskOutcome.SUCCESS, openApiDocsTask(runTheBuild()).outcome)
assertFalse(File(projectBuildDir, outputJsonFileNameSingleGroupA).exists())
assertOpenApiJsonFile(1, outputJsonFileNameGroupA)
assertOpenApiJsonFile(2, outputJsonFileNameGroupB)
}
private fun runTheBuild(vararg additionalArguments: String = emptyArray()) = GradleRunner.create()
.withProjectDir(projectTestDir)
.withArguments("clean", "generateOpenApiDocs", *additionalArguments)
.withPluginClasspath()
.build()
private fun assertOpenApiJsonFile(
expectedPathCount: Int,
outputJsonFileName: String = DEFAULT_OPEN_API_FILE_NAME,
buildDir: File = projectBuildDir
) {
val openApiJson = getOpenApiJsonAtLocation(File(buildDir, outputJsonFileName))
assertEquals("3.0.1", openApiJson.string(openapiField))
assertEquals(expectedPathCount, openApiJson.obj(pathsField)!!.size)
}
private fun getOpenApiJsonAtLocation(path: File) = Parser.default().parse(FileReader(path)) as JsonObject
private fun assertOpenApiYamlFile(
expectedPathCount: Int,
outputJsonFileName: String = DEFAULT_OPEN_API_FILE_NAME,
buildDir: File = projectBuildDir
) {
val mapper = ObjectMapper(YAMLFactory())
mapper.registerModule(KotlinModule.Builder().build())
val node = mapper.readTree(File(buildDir, outputJsonFileName))
assertEquals("3.0.1", node.get(openapiField).asText())
assertEquals(expectedPathCount, node.get(pathsField)!!.size())
}
private fun openApiDocsTask(result: BuildResult) = result.tasks.find { it.path.contains("generateOpenApiDocs") }!!
}
| 8
|
Kotlin
|
31
| 96
|
bb1a68af9598629716bca7a3fc3b1cc577bfd8b1
| 10,677
|
springdoc-openapi-gradle-plugin
|
Apache License 2.0
|
feature/home/src/main/java/com/lighthouse/android/home/viewmodel/HomeViewModel.kt
|
soma-lighthouse
| 658,620,687
| false
| null |
package com.lighthouse.android.home.viewmodel
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lighthouse.android.common_ui.util.UiState
import com.lighthouse.domain.constriant.Resource
import com.lighthouse.domain.entity.response.vo.ProfileVO
import com.lighthouse.domain.usecase.GetMatchedUserUseCase
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import javax.inject.Inject
@HiltViewModel
class HomeViewModel @Inject constructor(
private val getMatchedUserUseCase: GetMatchedUserUseCase,
) : ViewModel() {
private val _page: MutableStateFlow<Int> = MutableStateFlow(1)
val page: StateFlow<Int>
get() = _page
private var userProfiles = listOf<ProfileVO>()
var loading = MutableLiveData<Boolean>()
private var next: Int? = null
fun fetchNextPage(
userId: String,
pageSize: Int? = null,
): Flow<UiState> {
return getMatchedUserUseCase.invoke(userId, next, pageSize)
.map {
when (it) {
is Resource.Success -> {
if (it.data!!.nextId == -1) {
Log.d("PAGING", "enter")
_page.value = -1
} else {
next = it.data!!.nextId
}
UiState.Success(it.data!!.profile)
}
is Resource.Error -> UiState.Error(it.message ?: "Error Occurred")
}
}
.stateIn(
scope = viewModelScope,
initialValue = UiState.Loading,
started = SharingStarted.WhileSubscribed(5000)
)
}
fun saveUserProfiles(profiles: List<ProfileVO>) {
userProfiles = profiles
}
fun getUserProfiles() = userProfiles
}
| 3
|
Kotlin
|
0
| 0
|
be614af85c7e21bd36131faf8bfab4bcebdad108
| 2,174
|
FE-lingo-swap
|
Apache License 2.0
|
compiler/testData/psi/recovery/ForWithoutRange.kt
|
JakeWharton
| 99,388,807
| false
| null |
fun test() {
for (some)
bar()
}
| 179
| null |
5640
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 40
|
kotlin
|
Apache License 2.0
|
app/src/main/java/me/zama/itunes_most_played/ui/screens/playlist/PlayListGridItem.kt
|
giacomozama
| 491,690,434
| false
| null |
package me.zama.itunes_most_played.ui.screens.playlist
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import coil.compose.AsyncImage
import coil.request.ImageRequest
import me.zama.itunes_most_played.R
const val PLAY_LIST_GRID_ITEM_TEST_TAG = "play_list_grid_item"
@Composable
fun PlayListGridItem(
modifier: Modifier = Modifier,
artistName: String,
songName: String,
releaseDate: String,
artworkUrl: String,
onClick: () -> Unit
) {
Surface(
modifier = modifier
.testTag(PLAY_LIST_GRID_ITEM_TEST_TAG)
.heightIn(min = dimensionResource(id = R.dimen.play_list_grid_item_height)),
onClick = onClick
) {
Column(
modifier = Modifier.padding(dimensionResource(id = R.dimen.play_list_grid_item_padding)),
horizontalAlignment = Alignment.CenterHorizontally
) {
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(artworkUrl)
.size(100)
.crossfade(true)
.build(),
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f)
.clip(RoundedCornerShape(dimensionResource(id = R.dimen.item_song_cover_corner_radius))),
contentDescription = stringResource(R.string.artwork_for_template, songName)
)
Spacer(modifier = Modifier.height(dimensionResource(id = R.dimen.play_list_grid_item_line_spacing)))
Text(
text = artistName,
style = MaterialTheme.typography.h5,
textAlign = TextAlign.Center,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
Text(
text = songName,
style = MaterialTheme.typography.body1,
textAlign = TextAlign.Center,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
Text(
text = releaseDate,
style = MaterialTheme.typography.body2,
textAlign = TextAlign.Center,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
ce78060399e9ab0a7ec5f668e3494ea457059c09
| 2,914
|
itunes-most-played
|
MIT License
|
TabCommon/Customize/src/main/java/com/nextzy/tabcustomize/template/mvvm/adapter/KotlinMvvmCustomIndividualAdapterViewModel.kt
|
Nextzy
| 105,441,969
| false
| null |
package com.nextzy.tabcustomize.template.mvvm.adapter
import com.nextzy.tabcustomize.base.adapter.CustomAdapterViewModel
/**
* Created by「 <NAME> 」on 18 Sep 2017 :)
*/
class KotlinMvvmCustomIndividualAdapterViewModel
: CustomAdapterViewModel(){
}
| 1
| null |
1
| 4
|
64c38c1078f952ff01eadebc45458530352eb798
| 254
|
nextdroid-architecture
|
Apache License 2.0
|
src/Day08.kt
|
ShuffleZZZ
| 572,630,279
| false
|
{"Kotlin": 29686}
|
private fun getGrid(input: List<String>) = input.map { it.map(Char::digitToInt).toTypedArray() }.toTypedArray()
private fun observeLines(grid: Array<Array<Int>>, res: Array<BooleanArray>, lineInds: IntRange, rowInds: IntProgression) {
val maxRowInd = if (rowInds.isRange()) 0 else grid.first().size - 1
for (i in lineInds) {
var max = grid[i + 1][maxRowInd]
for (j in rowInds) {
if (grid[i + 1][j + 1] > max) {
res[i][j] = true
max = grid[i + 1][j + 1]
}
}
}
if (rowInds.isRange()) observeLines(grid, res, lineInds, rowInds.reversed())
}
private fun observeRows(grid: Array<Array<Int>>, res: Array<BooleanArray>, lineInds: IntProgression, rowInds: IntRange) {
val maxLineInd = if (lineInds.isRange()) 0 else grid.size - 1
for (j in rowInds) {
var max = grid[maxLineInd][j + 1]
for (i in lineInds) {
if (grid[i + 1][j + 1] > max) {
res[i][j] = true
max = grid[i + 1][j + 1]
}
}
}
if (lineInds.isRange()) observeRows(grid, res, lineInds.reversed(), rowInds)
}
private fun scenicScore(grid: Array<Array<Int>>, spot: Pair<Int, Int>) =
neighbours().map { observeTree(grid, spot, it) }.reduce(Int::times)
private fun observeTree(grid: Array<Array<Int>>, spot: Pair<Int, Int>, shift: Pair<Int, Int>): Int {
var dist = 0
var indexes = spot + shift
while (indexes.first in grid.indices && indexes.second in grid.first().indices) {
dist++
if (grid[indexes.first][indexes.second] >= grid[spot.first][spot.second]) break
indexes += shift
}
return dist
}
fun main() {
fun part1(input: List<String>): Int {
val grid = getGrid(input)
val n = grid.size
val m = grid.first().size
val res = Array(n - 2) { BooleanArray(m - 2) { false } }
observeLines(grid, res, res.indices, res.first().indices)
observeRows(grid, res, res.indices, res.first().indices)
return res.sumOf { it.count { e -> e } } + 2 * (n + m - 2)
}
fun part2(input: List<String>): Int {
val grid = getGrid(input)
val res = Array(grid.size - 2) { IntArray(grid.first().size - 2) { 0 } }
for (i in res.indices) {
for (j in res.indices) {
res[i][j] = scenicScore(grid, i + 1 to j + 1)
}
}
return res.maxOf { it.max() }
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day08_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput("Day08")
println(part1(input))
println(part2(input))
}
| 0
|
Kotlin
|
0
| 0
|
5a3cff1b7cfb1497a65bdfb41a2fe384ae4cf82e
| 2,750
|
advent-of-code-kotlin
|
Apache License 2.0
|
shared/src/commonMain/kotlin/link/socket/kore/model/agent/bundled/GenerateSubagentAgent.kt
|
socket-link
| 724,331,833
| false
|
{"Kotlin": 84576, "Swift": 580, "Shell": 228}
|
package link.socket.kore.model.agent.bundled
import com.aallam.openai.client.OpenAI
import kotlinx.coroutines.CoroutineScope
import link.socket.kore.model.agent.KoreAgent
import link.socket.kore.ui.conversation.selector.AgentInput
data class GenerateSubagentAgent(
override val openAI: OpenAI,
override val scope: CoroutineScope,
) : KoreAgent.HumanAndLLMAssisted(scope) {
private lateinit var description: String
companion object {
const val NAME = "Delegate Tasks"
private val descriptionArg = AgentInput.StringArg(
key = "Code Description",
value = "",
)
private fun instructionsFrom(): String {
// TODO: Get code from files
val generateCodeAgentContent = ""
val saveFileAgentContent = ""
return "You are a helpful assistant that is an expert programmer in Kotlin and at delegating Subagent LLM Agents.\n" +
"\n\n" +
"A Subagent can generate information from an LLM like this:\n" +
"$generateCodeAgentContent\n" +
"\n" +
"Or a Subagent can perform a particular task like this:\n" +
"$saveFileAgentContent\n" +
"\n\n" +
"A Subagent has an execute method, and initialize method that takes input, a " +
"result function that describes the expected output from the LLM (if it is using LLM " +
"assistance) and a prompt that may or may not use the input.\n" +
"The LLMAssisted interface has a generateString method that takes the prompt and result " +
"function and sends it to an LLM for processing\n" +
"The HumanAssisted interface presents the string to a human for verification and " +
"potential modification."
}
private fun initialPromptFrom(description: String): String =
"You need to build a new Sub-agent agent that does the following:\n" +
"$description\n\n" +
"Plan your solution step-by-step to ensure work is appropriately delegated to Subagents before you start."
}
override val name: String = NAME
override val instructions: String by lazy { instructionsFrom() }
override val initialPrompt: String by lazy { initialPromptFrom(description) }
override val neededInputs: List<AgentInput> = listOf(descriptionArg)
override fun parseNeededInputs(inputs: Map<String, AgentInput>) {
description = inputs[descriptionArg.key]?.value ?: ""
}
override suspend fun executeHumanAssistance(): String {
// TODO: Implement human verification
return "Test"
}
}
| 1
|
Kotlin
|
0
| 1
|
fb5655d3758da434cd459b41ea13623904a57811
| 2,732
|
kore-ai
|
Apache License 2.0
|
core/src/commonMain/kotlin/pro/respawn/flowmvi/dsl/StorePluginBuilder.kt
|
respawn-app
| 477,143,989
| false
|
{"Kotlin": 422243}
|
package pro.respawn.flowmvi.dsl
import pro.respawn.flowmvi.api.FlowMVIDSL
import pro.respawn.flowmvi.api.MVIAction
import pro.respawn.flowmvi.api.MVIIntent
import pro.respawn.flowmvi.api.MVIState
import pro.respawn.flowmvi.api.PipelineContext
import pro.respawn.flowmvi.api.StorePlugin
import pro.respawn.flowmvi.util.setOnce
/**
* A class that builds a new [StorePlugin]
* For more documentation, see [StorePlugin]
*
* Builder methods will throw [IllegalArgumentException] if they are assigned multiple times. Each plugin can only
* have **one** block per each type of [StorePlugin] callback.
*/
@FlowMVIDSL
public open class StorePluginBuilder<S : MVIState, I : MVIIntent, A : MVIAction> @PublishedApi internal constructor() {
private var intent: (suspend PipelineContext<S, I, A>.(I) -> I?)? = null
private var state: (suspend PipelineContext<S, I, A>.(old: S, new: S) -> S?)? = null
private var action: (suspend PipelineContext<S, I, A>.(A) -> A?)? = null
private var exception: (suspend PipelineContext<S, I, A>.(e: Exception) -> Exception?)? = null
private var start: (suspend PipelineContext<S, I, A>.() -> Unit)? = null
private var subscribe: (suspend PipelineContext<S, I, A>.(subscriberCount: Int) -> Unit)? = null
private var unsubscribe: (suspend PipelineContext<S, I, A>.(subscriberCount: Int) -> Unit)? = null
private var stop: ((e: Exception?) -> Unit)? = null
/**
* @see [StorePlugin.name]
*/
@FlowMVIDSL
public var name: String? = null
/**
* @see [StorePlugin.onIntent]
*/
@FlowMVIDSL
public fun onIntent(block: suspend PipelineContext<S, I, A>.(intent: I) -> I?): Unit = setOnce(::intent, block)
/**
* @see [StorePlugin.onState]
*/
@FlowMVIDSL
public fun onState(block: suspend PipelineContext<S, I, A>.(old: S, new: S) -> S?): Unit = setOnce(::state, block)
/**
* @see [StorePlugin.onStart]
*/
@FlowMVIDSL
public fun onStart(block: suspend PipelineContext<S, I, A>.() -> Unit): Unit = setOnce(::start, block)
/**
* @see [StorePlugin.onStop]
*/
@FlowMVIDSL
public fun onStop(block: (e: Exception?) -> Unit): Unit = setOnce(::stop, block)
/**
* @see [StorePlugin.onException]
*/
@FlowMVIDSL
public fun onException(
block: suspend PipelineContext<S, I, A>.(e: Exception) -> Exception?
): Unit = setOnce(::exception, block)
/**
* @see [StorePlugin.onAction]
*/
@FlowMVIDSL
public fun onAction(block: suspend PipelineContext<S, I, A>.(action: A) -> A?): Unit = setOnce(::action, block)
/**
* @see [StorePlugin.onSubscribe]
*/
@FlowMVIDSL
public fun onSubscribe(
block: suspend PipelineContext<S, I, A>.(subscriberCount: Int) -> Unit
): Unit = setOnce(::subscribe, block)
/**
* @see StorePlugin.onUnsubscribe
*/
@FlowMVIDSL
public fun onUnsubscribe(
block: suspend PipelineContext<S, I, A>.(subscriberCount: Int) -> Unit
): Unit = setOnce(::unsubscribe, block)
@FlowMVIDSL
@PublishedApi
internal fun build(): StorePlugin<S, I, A> = object : StorePlugin<S, I, A> {
override val name = this@StorePluginBuilder.name
override suspend fun PipelineContext<S, I, A>.onStart() {
this@StorePluginBuilder.start?.invoke(this)
}
override suspend fun PipelineContext<S, I, A>.onState(old: S, new: S): S? {
val block = this@StorePluginBuilder.state ?: return new
return block(old, new)
}
override suspend fun PipelineContext<S, I, A>.onIntent(intent: I): I? {
val block = this@StorePluginBuilder.intent ?: return intent
return block(intent)
}
override suspend fun PipelineContext<S, I, A>.onAction(action: A): A? {
val block = this@StorePluginBuilder.action ?: return action
return block(action)
}
override suspend fun PipelineContext<S, I, A>.onException(e: Exception): Exception? {
val block = this@StorePluginBuilder.exception ?: return e
return block(e)
}
override suspend fun PipelineContext<S, I, A>.onSubscribe(subscriberCount: Int) {
this@StorePluginBuilder.subscribe?.invoke(this, subscriberCount)
}
override suspend fun PipelineContext<S, I, A>.onUnsubscribe(subscriberCount: Int) {
this@StorePluginBuilder.unsubscribe?.invoke(this, subscriberCount)
}
override fun onStop(e: Exception?) {
stop?.invoke(e)
}
override fun toString(): String = name?.let { "StorePlugin \"$it\"" } ?: super.toString()
override fun hashCode(): Int = name?.hashCode() ?: super.hashCode()
override fun equals(other: Any?): Boolean = when {
other !is StorePlugin<*, *, *> -> false
other.name == null && name == null -> this === other
else -> name == other.name
}
}
}
/**
* Build a new [StorePlugin] using [StorePluginBuilder].
* See [StoreBuilder.install] to install the plugin automatically.
* @see [StorePlugin]
*/
@FlowMVIDSL
public inline fun <S : MVIState, I : MVIIntent, A : MVIAction> plugin(
@BuilderInference builder: StorePluginBuilder<S, I, A>.() -> Unit,
): StorePlugin<S, I, A> = StorePluginBuilder<S, I, A>().apply(builder).build()
| 5
|
Kotlin
|
8
| 228
|
1fe10a726fb7a3e28c5d1e39dca83e67665219cb
| 5,398
|
FlowMVI
|
Apache License 2.0
|
app/src/main/java/www/spikeysanju/flashnews/db/Converters.kt
|
Spikeysanju
| 262,249,672
| false
| null |
package www.spikeysanju.flashnews.db
import androidx.room.TypeConverter
import javax.xml.transform.Source
class Converters {
@TypeConverter
fun fromSource(source: www.spikeysanju.flashnews.model.Source):String {
return source.name
}
@TypeConverter
fun toSource(name:String):www.spikeysanju.flashnews.model.Source {
return www.spikeysanju.flashnews.model.Source(name,name)
}
}
| 2
|
Kotlin
|
0
| 7
|
72e98d1df0f9599244db8ff7037387a775734db7
| 424
|
FlashNews-MVVM
|
The Unlicense
|
libs/virtual-node/virtual-node-datamodel/src/integrationTest/kotlin/net/corda/libs/configuration/datamodel/tests/VNodeTestUtils.kt
|
corda
| 346,070,752
| false
| null |
package net.corda.libs.configuration.datamodel.tests
import java.time.Instant
import java.util.UUID
import javax.persistence.EntityManagerFactory
import net.corda.db.core.DbPrivilege
import net.corda.libs.configuration.datamodel.DbConnectionConfig
import net.corda.libs.cpi.datamodel.repository.CpiMetadataRepository
import net.corda.libs.packaging.core.CpiIdentifier
import net.corda.libs.virtualnode.datamodel.entities.HoldingIdentityEntity
import net.corda.libs.virtualnode.datamodel.entities.OperationType
import net.corda.libs.virtualnode.datamodel.entities.VirtualNodeEntity
import net.corda.libs.virtualnode.datamodel.entities.VirtualNodeOperationEntity
import net.corda.libs.virtualnode.datamodel.entities.VirtualNodeOperationState
import net.corda.orm.utils.transaction
import net.corda.test.util.TestRandom
import net.corda.v5.base.types.MemberX500Name
import net.corda.v5.crypto.SecureHash
import net.corda.virtualnode.HoldingIdentity
internal object VNodeTestUtils {
fun newVNode(
entityManagerFactory: EntityManagerFactory,
cpiName: String,
cpiVersion: String,
cpiSignerSummaryHash: SecureHash,
virtualNodeOperationEntity: VirtualNodeOperationEntity? = null,
holdingIdentityEntity: HoldingIdentityEntity? = null,
externalMessagingRouteConfig: String?,
cpiMetadataRepository: CpiMetadataRepository
): VirtualNodeEntity {
println("Creating VNode for testing: $cpiName, $cpiVersion, $cpiSignerSummaryHash")
val holdingIdentity = holdingIdentityEntity ?: newHoldingIdentityEntity(cpiName)
val virtualNode = VirtualNodeEntity(
holdingIdentity.holdingIdentityShortHash,
holdingIdentity,
cpiName,
cpiVersion,
cpiSignerSummaryHash.toString(),
UUID.randomUUID(),
UUID.randomUUID(),
UUID.randomUUID(),
UUID.randomUUID(),
UUID.randomUUID(),
UUID.randomUUID(),
operationInProgress = virtualNodeOperationEntity,
externalMessagingRouteConfig = externalMessagingRouteConfig
)
entityManagerFactory.createEntityManager().transaction { em ->
em.persist(newDbConnection(virtualNode.cryptoDDLConnectionId!!, DbPrivilege.DDL))
em.persist(newDbConnection(virtualNode.cryptoDMLConnectionId!!, DbPrivilege.DML))
em.persist(newDbConnection(virtualNode.vaultDDLConnectionId!!, DbPrivilege.DDL))
em.persist(newDbConnection(virtualNode.vaultDMLConnectionId!!, DbPrivilege.DML))
em.persist(newDbConnection(virtualNode.uniquenessDDLConnectionId!!, DbPrivilege.DDL))
em.persist(newDbConnection(virtualNode.uniquenessDMLConnectionId!!, DbPrivilege.DML))
}
entityManagerFactory.createEntityManager().transaction { em ->
cpiMetadataRepository.put(
em,
CpiIdentifier(cpiName, cpiVersion, cpiSignerSummaryHash),
cpiFileName = "file",
fileChecksum = TestRandom.secureHash(24),
groupPolicy = "group policy",
groupId = "group ID",
fileUploadRequestId = "request ID",
cpks = emptySet()
)
}
entityManagerFactory.createEntityManager().transaction { em -> return em.merge(virtualNode) }
}
fun newVNodeOperation(
entityManagerFactory: EntityManagerFactory,
requestId: String,
data: String,
state: VirtualNodeOperationState,
operationType: OperationType
) {
val operation = VirtualNodeOperationEntity(
UUID.randomUUID().toString(),
requestId,
data,
state,
operationType,
Instant.now(),
Instant.now(),
Instant.now(),
null
)
entityManagerFactory.createEntityManager().transaction { em -> em.persist(operation) }
}
fun newDbConnection(connectionId: UUID, privilege: DbPrivilege) =
DbConnectionConfig(
connectionId,
"c-$connectionId",
privilege,
Instant.now(),
"test",
"test connection",
"{}")
fun newHoldingIdentityEntity(id: String): HoldingIdentityEntity {
val hi = HoldingIdentity(
MemberX500Name.parse("C=GB,L=London,O=$id"),
"dummy")
return HoldingIdentityEntity(
holdingIdentityShortHash = hi.shortHash.value,
holdingIdentityFullHash = hi.fullHash,
x500Name = hi.x500Name.toString(),
mgmGroupId = hi.groupId,
hsmConnectionId = UUID.randomUUID()
)
}
}
| 141
| null |
27
| 69
|
d478e119ab288af663910f9a2df42a7a7b9f5bce
| 4,756
|
corda-runtime-os
|
Apache License 2.0
|
app/src/main/java/com/example/androidweatherapp/models/Model.kt
|
RamziJabali
| 381,178,725
| false
| null |
package com.example.androidweatherapp.models
class Model{
companion object{
var londonWOEID: Int = 44418
var sanfranWOEID: Int = 2487956
var australiaWOEID: Int = 23424748
var empty: String = ""
}
}
| 0
|
Kotlin
|
0
| 0
|
30a8079e7a63d7a9a041aa644888b2c04299e081
| 240
|
weather-app-android
|
The Unlicense
|
library/query/src/commonMain/kotlin/com/attafitamim/kabin/query/SQLiteQueryDirection.kt
|
tamimattafi
| 702,197,843
| false
|
{"Kotlin": 340835}
|
package com.attafitamim.kabin.query
enum class SQLiteQueryDirection(val rawValue: String) {
ASCENDING("ASC"),
DESCENDING("DESC")
}
| 0
|
Kotlin
|
3
| 50
|
b35fd487f1342b354c89dc3557a0e1cfd613d6bf
| 140
|
kabin
|
Apache License 2.0
|
money-transfers-api/src/test/java/validator/TransferRequestValidatorTest.kt
|
DimaPhil
| 238,275,894
| false
| null |
package validator
import exception.UserDataValidationException
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertDoesNotThrow
import request.TransferRequest
import java.math.BigDecimal
class TransferRequestValidatorTest {
private val transferRequestValidator = TransferRequestValidator()
@Test
fun `should not validate requests with incorrect from or to account ids or incorrect amount`() {
val requestNegativeAmount = TransferRequest(from = 4, to = 5, amount = BigDecimal("-0.00000001"))
val requestZeroAmount = TransferRequest(from = 4, to = 5, amount = BigDecimal.ZERO)
val requestZeroFromAccountId = TransferRequest(from = 0, to = 5, amount = BigDecimal("2.39"))
val requestZeroToAccountId = TransferRequest(from = 5, to = 0, amount = BigDecimal("2.39"))
Assertions.assertThrows(UserDataValidationException::class.java) { transferRequestValidator.validate(requestNegativeAmount) }
Assertions.assertThrows(UserDataValidationException::class.java) { transferRequestValidator.validate(requestZeroAmount) }
Assertions.assertThrows(UserDataValidationException::class.java) { transferRequestValidator.validate(requestZeroFromAccountId) }
Assertions.assertThrows(UserDataValidationException::class.java) { transferRequestValidator.validate(requestZeroToAccountId) }
}
@Test
fun `should validate requests with correct from and to account id, and amount`() {
val request = TransferRequest(from = 4, to = 5, amount = BigDecimal("2.39"))
assertDoesNotThrow("Validation should pass on correct requests") { transferRequestValidator.validate(request) }
}
}
| 1
|
Kotlin
|
0
| 0
|
6be9c6aeaafe6fa6b3e45dd3f8cef7b75e6a6ee6
| 1,718
|
money-transfers
|
MIT License
|
app/src/test/kotlin/com/jameskbride/codemashcompanion/speakers/detail/SpeakerDetailActivityImplTest.kt
|
jameskbride
| 111,301,835
| false
| null |
package com.jameskbride.codemashcompanion.speakers.detail
import android.content.Intent
import androidx.annotation.IdRes
import androidx.fragment.app.FragmentManager
import androidx.viewpager.widget.ViewPager
import androidx.appcompat.app.ActionBar
import androidx.appcompat.widget.Toolbar
import android.view.MenuItem
import com.jameskbride.codemashcompanion.R
import com.jameskbride.codemashcompanion.data.model.FullSpeaker
import com.jameskbride.codemashcompanion.framework.BaseActivityImpl.Companion.PARAMETER_BLOCK
import com.jameskbride.codemashcompanion.utils.test.buildDefaultFullSpeakers
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import org.junit.Assert
import org.junit.Assert.assertSame
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations.initMocks
class SpeakerDetailActivityImplTest {
@Mock private lateinit var qtn: SpeakerDetailActivity
@Mock private lateinit var supportFragmentManager: androidx.fragment.app.FragmentManager
@Mock private lateinit var speakerPager: androidx.viewpager.widget.ViewPager
@Mock private lateinit var speakerPagerAdapter:SpeakerPagerAdapter
@Mock private lateinit var speakerPagerAdapterFactory:SpeakerPagerAdapterFactory
@Mock private lateinit var intent:Intent
@Mock private lateinit var actionBar:ActionBar
@Mock private lateinit var toolbar:Toolbar
private lateinit var subject: SpeakerDetailActivityImpl
private lateinit var speakers:Array<FullSpeaker>
private lateinit var speakerDetailParams: SpeakersParams
@Before
fun setUp() {
initMocks(this)
speakers = buildDefaultFullSpeakers()
speakerDetailParams = SpeakersParams(speakers, 0)
intent = mock()
subject = SpeakerDetailActivityImpl(speakerPagerAdapterFactory)
whenever(qtn.intent).thenReturn(intent)
whenever(intent.getSerializableExtra(PARAMETER_BLOCK)).thenReturn(speakerDetailParams)
whenever(speakerPagerAdapterFactory.make(supportFragmentManager)).thenReturn(speakerPagerAdapter)
whenever(qtn.findViewById<androidx.viewpager.widget.ViewPager>(R.id.speaker_pager)).thenReturn(speakerPager)
whenever(qtn.findViewById<Toolbar>(R.id.toolbar)).thenReturn(toolbar)
whenever(qtn.supportActionBar).thenReturn(actionBar)
whenever(qtn.supportFragmentManager).thenReturn(supportFragmentManager)
}
@Test
fun onCreateSetsTheContentView() {
subject.onCreate(null, qtn)
verify(qtn).setContentView(R.layout.activity_speaker_detail)
}
@Test
fun onCreateSetsTheTitle() {
subject.onCreate(null, qtn)
verify(toolbar).setTitle(R.string.speaker_detail)
}
@Test
fun onCreateConfiguresTheViewPager() {
subject.onCreate(null, qtn)
assertSame(speakerPagerAdapter, subject.speakerDetailPagerAdapter)
verify(speakerPagerAdapter).updateSpeakers(speakers)
verify(speakerPager).setAdapter(subject.speakerDetailPagerAdapter)
verify(speakerPager).setCurrentItem(speakerDetailParams.index)
}
@Test
fun onCreateConfiguresTheUpNavigation() {
whenever(qtn.supportActionBar).thenReturn(actionBar)
subject.onCreate(null, qtn)
verify(qtn).setSupportActionBar(toolbar)
verify(actionBar).setDisplayHomeAsUpEnabled(true)
}
@Test
fun itCanNavigateUpWhenHomeIsSelected() {
val menuItem = mock<MenuItem>()
whenever(menuItem.itemId).thenReturn(android.R.id.home)
val result = subject.onOptionsItemSelected(menuItem, qtn)
Assert.assertTrue(result)
verify(qtn).onBackPressed()
}
@Test
fun itNavigatesAccordingToSuperWhenHomeIsNotSelected() {
val menuItem = mock<MenuItem>()
@IdRes val someInt = 42
whenever(menuItem.itemId).thenReturn(someInt)
subject.onOptionsItemSelected(menuItem, qtn)
verify(qtn).callSuperOnOptionsItemSelected(menuItem)
}
}
| 1
|
Kotlin
|
0
| 1
|
5700a3828ae8dfd45c2049736d55343974dab137
| 4,074
|
codemash-companion
|
MIT License
|
webview-jsbridge/src/main/java/me/reezy/cosmo/jsbridge/internal/JSModule.kt
|
czy1121
| 732,022,452
| false
|
{"Kotlin": 37703, "HTML": 608}
|
package me.reezy.cosmo.jsbridge.internal
import me.reezy.cosmo.jsbridge.JSBridgeMethod
import me.reezy.cosmo.jsbridge.JSBridgeModule
import me.reezy.cosmo.jsbridge.argument.JSCallback
import me.reezy.cosmo.jsbridge.argument.JSMap
import org.json.JSONArray
import org.json.JSONObject
import java.lang.reflect.Modifier
internal class JSModule(val instance: JSBridgeModule) {
val methods: Map<String, JSMethod> = getMethods(instance)
private fun getMethods(module: JSBridgeModule): Map<String, JSMethod> {
val methods = mutableMapOf<String, JSMethod>()
module.javaClass.declaredMethods.forEach {
val modifiers = it.modifiers
if (Modifier.isAbstract(modifiers) || Modifier.isStatic(modifiers)) {
return@forEach
}
val annotation = it.getAnnotation(JSBridgeMethod::class.java) ?: return@forEach
val name = if (annotation.name.isEmpty()) it.name else annotation.name
val mainThread = annotation.mainThread
val hasReturn = "void" != it.returnType.name
// var hasContext = false
val parameters = it.parameterTypes.toList()
val argumentTypes: List<Int> = when {
parameters.isEmpty() -> emptyList()
// parameters[0] == JSContext::class.java -> {
// hasContext = true
// parameters.subList(1, parameters.size).map(this::getType)
// }
else -> parameters.map(this::getType)
}
methods[name] = JSMethod(module, it, name, hasReturn, argumentTypes, mainThread)
}
return methods
}
private fun getType(clazz: Class<*>): Int = when (clazz) {
Boolean::class.java -> JSType.TYPE_BOOL
Int::class.java -> JSType.TYPE_INT
Long::class.java -> JSType.TYPE_LONG
Float::class.java -> JSType.TYPE_FLOAT
Double::class.java -> JSType.TYPE_DOUBLE
String::class.java -> JSType.TYPE_STRING
JSONObject::class.java -> JSType.TYPE_OBJECT
JSONArray::class.java -> JSType.TYPE_ARRAY
JSMap::class.java -> JSType.TYPE_MAP
JSCallback::class.java -> JSType.TYPE_CALLBACK
else -> JSType.TYPE_UNDEFINED
}
}
| 0
|
Kotlin
|
0
| 1
|
bf28f130248d8854e8734d9122a4592448d2b154
| 2,266
|
webview
|
Apache License 2.0
|
application/src/androidMain/kotlin/io/github/gmvalentino8/application/AppPlatform.kt
|
wasabi-muffin
| 457,416,965
| false
|
{"Kotlin": 55509}
|
package io.github.gmvalentino8.application
import android.content.Context
import android.os.Build.MANUFACTURER
import android.os.Build.MODEL
import android.os.Build.VERSION
actual class AppPlatform(
val context: Context,
) : Platform {
actual override val osName: String = "android"
actual override val osVersion: String = VERSION.RELEASE
actual override val device: String = "$MANUFACTURER $MODEL"
}
| 1
|
Kotlin
|
0
| 0
|
56f14f334670e691775f4028c97b3e76d947fb3a
| 419
|
Cyclone-Modular-Template-KMM
|
MIT License
|
plugin-datastore-clickhouse/src/main/kotlin/idlab/obelisk/plugins/datastore/clickhouse/impl/utils/CHField.kt
|
idlab-discover
| 495,291,260
| false
|
{"Kotlin": 993529, "TypeScript": 611538, "HTML": 424943, "SCSS": 73991, "Smarty": 38291, "JavaScript": 8320, "Mustache": 5714, "CSS": 2879, "Shell": 2379, "Dockerfile": 382, "Batchfile": 41}
|
package idlab.obelisk.plugins.datastore.clickhouse.impl.utils
import idlab.obelisk.definitions.EventField
import idlab.obelisk.definitions.Field
import idlab.obelisk.definitions.MetricName
import idlab.obelisk.definitions.MetricType
import idlab.obelisk.definitions.data.DataQuery
import idlab.obelisk.definitions.data.IndexField
import idlab.obelisk.definitions.data.StatsField
import idlab.obelisk.definitions.data.StatsQuery
import idlab.obelisk.utils.service.utils.toMus
import idlab.obelisk.definitions.data.DurationUnit
internal enum class CHField(
val generated: Boolean = false,
// We use an additional parameter CHField for the lambda, to avoid 'this' issues in this context
private val expr: (CHField, DataQuery) -> String = { f, _ -> f.toString() }
) {
timestamp, // The timestamp, represented in CH as a DateTime64 (used for timerange filters)
timestampMus(generated = true, expr = { _, q -> // Processed timestamp (used for returning in the results)
if (q is StatsQuery) {
if (q.groupBy?.time != null) {
val groupByTime = q.groupBy!!.time!!
val intervalUnit = when (groupByTime.intervalUnit) {
DurationUnit.hours -> "hour"
DurationUnit.days -> "day"
DurationUnit.minutes -> "minute"
DurationUnit.seconds -> "second"
}
val offsetMus = groupByTime.offset.toLong().toMus(sourceUnit = groupByTime.offsetUnit.unit)
"(toUnixTimestamp(toStartOfInterval(${timestamp}, INTERVAL ${groupByTime.interval} ${intervalUnit})) * 1000 * 1000) + $offsetMus as $timestampMus"
} else {
"NULL as $timestampMus"
}
} else {
"toUnixTimestamp64Micro(${timestamp}) as $timestampMus"
}
}),
tsReceived(expr = { _, _ -> "toUnixTimestamp64Milli(${tsReceived})" }),
dataset,
metric_type,
metric_name,
value_string(expr = ::valueSelector),
value_number(expr = ::valueSelector),
value_number_array(expr = ::valueSelector),
value_bool(expr = ::valueSelector),
user,
client,
source,
tags,
lat(expr = ::replaceNaNWithNullExpr),
lng(expr = ::replaceNaNWithNullExpr),
elevation(expr = ::replaceNaNWithNullExpr),
geohash(generated = true, { _, q ->
val precision = if (q is StatsQuery && q.groupBy?.fields?.contains(IndexField.geohash) == true) {
if (q.groupBy!!.geohashPrecision in GROUP_BY_GEOHASH_RANGE) {
q.groupBy!!.geohashPrecision
} else {
throw IllegalArgumentException("Geohash precision for groupBy must be in the following range: $GROUP_BY_GEOHASH_RANGE")
}
} else {
12
}
"if(NOT isNaN(${lat}), geohashEncode($lng, $lat, $precision), NULL) as $geohash"
}),
min(generated = true, expr = { _, q -> "min(${value_number.expr(q)}) as $min" }),
max(generated = true, expr = { _, q -> "max(${value_number.expr(q)}) as $max" }),
mean(generated = true, expr = { _, q -> "avg(${value_number.expr(q)}) as $mean" }),
stddev(generated = true, expr = { _, q -> "stddevPop(${value_number.expr(q)}) as $stddev" }),
count(generated = true, expr = { _, _ -> "count(${value_number}) as $count" }),
countSources(generated = true, expr = { _, _ -> "count(distinct(${source})) as $countSources" }),
sum(generated = true, expr = { _, q -> "sum(${value_number.expr(q)}) as $sum" });
fun expr(q: DataQuery): String {
return expr.invoke(this, q)
}
companion object {
// Fields that define the timeseries.
fun timeSeriesIdFields(): List<CHField> {
return listOf(dataset, metric_type, metric_name, user, client, source)
}
fun valueHolder(type: MetricType): CHField {
return when (type) {
MetricType.BOOL -> value_bool
MetricType.STRING, MetricType.JSON -> value_string
MetricType.NUMBER_ARRAY -> value_number_array
MetricType.NUMBER -> value_number
}
}
fun from(field: EventField, q: DataQuery): List<CHField> {
return when (field) {
EventField.timestamp -> listOf(timestampMus)
EventField.metric -> listOf(metric_name, metric_type)
EventField.location -> listOf(lat, lng)
EventField.producer -> listOf(user, client)
EventField.value -> q.dataRange.metrics.map { it.type }.distinct().map { valueHolder(it) }
else -> listOf(valueOf(field.toString()))
}
}
fun from(field: StatsField): List<CHField> {
return when (field) {
StatsField.metric -> listOf(metric_name, metric_type)
StatsField.producer -> listOf(user, client)
else -> listOf(valueOf(field.toString()))
}
}
fun from(field: IndexField): List<CHField> {
return when (field) {
IndexField.timestamp -> listOf(timestampMus)
IndexField.metric -> listOf(metric_name, metric_type)
IndexField.producer -> listOf(user, client)
else -> listOf(valueOf(field.toString()))
}
}
fun jsonLookup(path: List<String>, type: MetricType): String {
val operator = when (type) {
MetricType.NUMBER -> "JSONExtractFloat"
MetricType.STRING -> "JSONExtractString"
MetricType.BOOL -> "JSONExtractBool"
else -> throw IllegalArgumentException("Invalid datatype for FilterExpression field comparison operator!")
}
return "$operator($value_string, ${jsonLookupPathToCH(path)})"
}
}
}
private fun replaceNaNWithNullExpr(field: CHField, q: DataQuery): String =
"if(NOT isNaN($field), $field, NULL) as $field"
private fun valueSelector(field: CHField, q: DataQuery): String = if (q.dataRange.metrics.any { it.isDerived() }) {
// The query uses derived metrics, which require a different approach to value extraction
q.dataRange.metrics.filter { it.isDerived() }.distinct()
.joinToString(prefix = "multiIf(", postfix = ", $field) as $field") {
"${CHField.metric_type} = '${MetricType.JSON.typeSuffix}' AND ${CHField.metric_name} = '${it.getParent()!!.name}', ${
extractJson(
it.getDerived()!!
)
}"
}
} else {
// No special treatment required
field.toString()
}
private fun jsonLookupPathToCH(path: List<String>): String {
return path.joinToString(",") {
if (Field.isArrayIndex(it)) {
"${Field.decodeArrayIndex(it) + 1}"
} else {
"'$it'"
}
}
}
private fun extractJson(
derivedMetric: MetricName
): String {
val jsonPath = jsonLookupPathToCH(derivedMetric.name.split("->"))
return when (derivedMetric.type) {
MetricType.JSON -> "JSONExtractRaw(${CHField.value_string},$jsonPath)"
MetricType.STRING -> "JSONExtractString(${CHField.value_string}, $jsonPath)"
MetricType.BOOL -> "JSONExtractUInt(${CHField.value_string}, $jsonPath)"
MetricType.NUMBER -> "JSONExtractFloat(${CHField.value_string}, $jsonPath)"
MetricType.NUMBER_ARRAY -> "JSONExtract(${CHField.value_string}, $jsonPath, 'Array(Float64)')"
}
}
| 25
|
Kotlin
|
0
| 6
|
793c8ec906f0dcad4b5da93d0aaa9e2d645f256b
| 7,507
|
obelisk
|
Apache License 2.0
|
src/main/kotlin/Util.kt
|
Reversean
| 448,974,094
| false
|
{"Kotlin": 1927}
|
// Args
const val EXIT = "exit"
const val CURRENT = "current-status"
// Msg
const val WELCOME = "Type one of the following command:"
const val INCORRECT_INPUT = "Incorrect input"
const val ON_EXIT = "Shut down service"
val commandHelp = mapOf(
"current-status" to "Get current CPU load",
"exit" to "Shut down service"
)
fun printHelp() {
println(commandHelp.entries.joinToString("\n") { "\t" + it.key + " – " + it.value })
}
| 0
|
Kotlin
|
0
| 0
|
4c727ace580d556089cd5b40abf449a97bd11eff
| 440
|
pc-monitoring
|
MIT License
|
apps/student/src/main/java/com/instructure/student/features/people/list/PeopleListRepository.kt
|
instructure
| 179,290,947
| false
|
{"Kotlin": 16415961, "Dart": 4454406, "HTML": 185120, "Ruby": 35686, "Java": 24752, "Shell": 19157, "Groovy": 11717, "JavaScript": 9505, "Objective-C": 7431, "Python": 2438, "CSS": 1356, "Swift": 807, "Dockerfile": 112}
|
/*
* Copyright (C) 2023 - present Instructure, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.instructure.student.features.people.list
import com.instructure.canvasapi2.models.CanvasContext
import com.instructure.canvasapi2.models.User
import com.instructure.canvasapi2.utils.DataResult
import com.instructure.pandautils.repository.Repository
import com.instructure.pandautils.utils.FeatureFlagProvider
import com.instructure.pandautils.utils.NetworkStateProvider
class PeopleListRepository(
peopleListLocalDataSource: PeopleListLocalDataSource,
peopleListNetworkDataSource: PeopleListNetworkDataSource,
networkStateProvider: NetworkStateProvider,
featureFlagProvider: FeatureFlagProvider
) : Repository<PeopleListDataSource>(peopleListLocalDataSource, peopleListNetworkDataSource, networkStateProvider, featureFlagProvider) {
suspend fun loadFirstPagePeople(canvasContext: CanvasContext, forceNetwork: Boolean): DataResult<List<User>> {
return dataSource().loadFirstPagePeople(canvasContext, forceNetwork)
}
suspend fun loadNextPagePeople(canvasContext: CanvasContext, forceNetwork: Boolean, nextUrl: String = ""): DataResult<List<User>> {
return dataSource().loadNextPagePeople(canvasContext, forceNetwork, nextUrl)
}
suspend fun loadTeachers(canvasContext: CanvasContext, forceNetwork: Boolean): DataResult<List<User>> {
return dataSource().loadTeachers(canvasContext, forceNetwork)
}
suspend fun loadTAs(canvasContext: CanvasContext, forceNetwork: Boolean): DataResult<List<User>> {
return dataSource().loadTAs(canvasContext, forceNetwork)
}
}
| 7
|
Kotlin
|
102
| 127
|
ca6e2aeaeedb851003af5497e64c22e02dbf0db8
| 2,218
|
canvas-android
|
Apache License 2.0
|
archive/design1/webserver/src/main/kotlin/com/tempstorage/tempfiledrop/webserver/service/filestorage/FileStorageController.kt
|
awarenessxz
| 363,068,047
| false
| null |
package com.tempstorage.tempfiledrop.webserver.service.filestorage
import com.fasterxml.jackson.databind.ObjectMapper
import com.tempstorage.tempfiledrop.webserver.exception.ApiException
import com.tempstorage.tempfiledrop.webserver.exception.ErrorCode
import com.tempstorage.tempfiledrop.webserver.exception.ErrorResponse
import com.tempstorage.tempfiledrop.webserver.service.storagesvcclient.StorageInfoResponse
import com.tempstorage.tempfiledrop.webserver.service.storagesvcclient.StorageSvcClientImpl
import com.tempstorage.tempfiledrop.webserver.service.storagesvcclient.StorageUploadRequest
import com.tempstorage.tempfiledrop.webserver.service.useruploads.UserUploadInfo
import com.tempstorage.tempfiledrop.webserver.service.useruploads.UserUploadInfoService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.client.HttpStatusCodeException
import org.springframework.web.multipart.MultipartFile
import javax.servlet.http.HttpServletResponse
@RestController
@RequestMapping("/api/files")
class FileStorageController(
@Value("\${tempfiledrop.webserver.bucket-name}") private val tempfiledropBucket: String,
private val uploadedFilesRecordService: UserUploadInfoService,
private val storageSvcClient: StorageSvcClientImpl
) {
companion object {
private val logger = LoggerFactory.getLogger(FileStorageController::class.java)
private const val ANONYMOUS_FOLDER = "anonymous"
}
@PostMapping("/upload", consumes = [MediaType.MULTIPART_FORM_DATA_VALUE])
fun uploadFiles(
@RequestPart("files", required = true) files: List<MultipartFile>,
@RequestPart("metadata", required = true) metadata: FileUploadInfoRequest
): ResponseEntity<FileUploadInfoResponse> {
val storagePath = if (metadata.username.trim().isEmpty()) ANONYMOUS_FOLDER else metadata.username
logger.info("Received Request to store ${files.size} files in $tempfiledropBucket/$storagePath")
try {
// Forward to Storage Service to store file
val storageRequest = StorageUploadRequest(tempfiledropBucket, storagePath, metadata.maxDownloads, metadata.expiryPeriod)
val storageSvcResponse = storageSvcClient.uploadToStorageSvc(files, storageRequest)
val fileStorageResponse = storageSvcResponse.body
if (!storageSvcResponse.statusCode.is2xxSuccessful || fileStorageResponse == null) {
throw ApiException("Uploading Failed!", ErrorCode.UPLOAD_FAILED, HttpStatus.INTERNAL_SERVER_ERROR)
}
// store the storage information into database
logger.info("Adding user upload record to database -- ${fileStorageResponse.storageId}")
uploadedFilesRecordService.addUploadedFilesRecord(UserUploadInfo(null, storagePath, fileStorageResponse.storageId))
// process response & return results
return if (storageSvcResponse.statusCode.is2xxSuccessful) {
logger.info("Upload is successful!")
ResponseEntity(FileUploadInfoResponse("Upload Successful", fileStorageResponse.storageId), HttpStatus.OK)
} else {
logger.info("Upload Failed!")
throw ApiException("Could not upload the files!", ErrorCode.UPLOAD_FAILED, HttpStatus.INTERNAL_SERVER_ERROR)
}
} catch (e: HttpStatusCodeException) {
logger.info("ERROR -- ${e.message}")
throw ApiException("Uploading Failed!", ErrorCode.UPLOAD_FAILED, HttpStatus.INTERNAL_SERVER_ERROR)
}
}
@GetMapping("/download/{storageId}")
fun downloadFiles(@PathVariable("storageId") storageId: String, response: HttpServletResponse) {
logger.info("Receiving request to download files from $storageId")
storageSvcClient.downloadFromStorageSvc(tempfiledropBucket, storageId, response)
}
@GetMapping("/download-info/{storageId}")
fun getStorageInformationForDownload(@PathVariable("storageId") storageId: String): ResponseEntity<StorageInfoResponse> {
logger.info("Receiving request to get download information for $storageId")
// verify if files exists on server
try {
val storageSvcResponse = storageSvcClient.getStorageInfoByStorageId(tempfiledropBucket, storageId)
val storageInfoResponse = storageSvcResponse.body
if (!storageSvcResponse.statusCode.is2xxSuccessful || storageInfoResponse === null) {
throw ApiException("Fail to retrieve download information for $storageId", ErrorCode.NO_MATCHING_RECORD, HttpStatus.BAD_REQUEST)
}
val response = StorageInfoResponse(storageInfoResponse.storageId, storageInfoResponse.downloadLink, storageInfoResponse.filenames, storageInfoResponse.numOfDownloadsLeft, storageInfoResponse.expiryDatetime)
return ResponseEntity(response, HttpStatus.OK)
} catch (e: HttpStatusCodeException) {
logger.error(e.responseBodyAsString)
val objectMapper = ObjectMapper()
val errorResponse = objectMapper.readValue(e.responseBodyAsString, ErrorResponse::class.java)
if (errorResponse.errorCode === ErrorCode.FILE_NOT_FOUND) {
// delete messages
logger.info("Deleting User Uploaded Record for $storageId....")
uploadedFilesRecordService.deleteUploadedFilesRecordByStorageId(storageId)
}
throw ApiException("Fail to retrieve download information for $storageId", ErrorCode.NO_MATCHING_RECORD, HttpStatus.BAD_REQUEST)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
7461984eec1effc91abc78206a9971cdfbd7df4d
| 5,844
|
TempFileDrop
|
Apache License 2.0
|
src/commonMain/kotlin/models/CallbackQuery.kt
|
dragneelfps
| 297,047,080
| false
| null |
package io.github.dragneelfps.kbot.models
import kotlinx.serialization.Serializable
/**
* [https://core.telegram.org/bots/api#callbackquery]
*/
@Serializable
data class CallbackQuery(
val id: String,
val user: User,
val message: Message? = null,
val inline_message_id: String? = null,
val chat_instance: String? = null,
val data: String? = null,
val game_short_name: String? = null,
)
| 5
|
Kotlin
|
2
| 8
|
ffd954dd6b28c96cd1c8e5c846f55079bbaa07af
| 417
|
telegram-bot.kt
|
MIT License
|
app/src/main/java/io/github/wulkanowy/data/repositories/HomeworkRepository.kt
|
v0idzz
| 267,255,870
| true
|
{"Kotlin": 1212916, "HTML": 1949, "Shell": 220}
|
package io.github.wulkanowy.data.repositories
import io.github.wulkanowy.data.db.dao.HomeworkDao
import io.github.wulkanowy.data.db.entities.Homework
import io.github.wulkanowy.data.db.entities.Semester
import io.github.wulkanowy.data.db.entities.Student
import io.github.wulkanowy.data.mappers.mapToEntities
import io.github.wulkanowy.sdk.Sdk
import io.github.wulkanowy.utils.AutoRefreshHelper
import io.github.wulkanowy.utils.getRefreshKey
import io.github.wulkanowy.utils.init
import io.github.wulkanowy.utils.monday
import io.github.wulkanowy.utils.networkBoundResource
import io.github.wulkanowy.utils.sunday
import io.github.wulkanowy.utils.uniqueSubtract
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.sync.Mutex
import java.time.LocalDate
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class HomeworkRepository @Inject constructor(
private val homeworkDb: HomeworkDao,
private val sdk: Sdk,
private val refreshHelper: AutoRefreshHelper,
) {
private val saveFetchResultMutex = Mutex()
private val cacheKey = "homework"
fun getHomework(
student: Student,
semester: Semester,
start: LocalDate,
end: LocalDate,
forceRefresh: Boolean,
notify: Boolean = false
) = networkBoundResource(
mutex = saveFetchResultMutex,
shouldFetch = {
it.isEmpty() || forceRefresh ||
refreshHelper.isShouldBeRefreshed(getRefreshKey(cacheKey, semester, start, end))
},
query = {
homeworkDb.loadAll(
semesterId = semester.semesterId,
studentId = semester.studentId,
from = start.monday,
end = end.sunday
)
},
fetch = {
sdk.init(student).switchDiary(semester.diaryId, semester.schoolYear)
.getHomework(start.monday, end.sunday)
.mapToEntities(semester)
},
saveFetchResult = { old, new ->
val homeWorkToSave = (new uniqueSubtract old).onEach {
if (notify) it.isNotified = false
}
homeworkDb.deleteAll(old uniqueSubtract new)
homeworkDb.insertAll(homeWorkToSave)
refreshHelper.updateLastRefreshTimestamp(getRefreshKey(cacheKey, semester, start, end))
}
)
suspend fun toggleDone(homework: Homework) {
homeworkDb.updateAll(listOf(homework.apply {
isDone = !isDone
}))
}
fun getNotNotifiedHomework(
semester: Semester,
start: LocalDate,
end: LocalDate
) = homeworkDb.loadAll(semester.semesterId, semester.studentId, start.monday, end.sunday)
.map {
it.filter { homework -> !homework.isNotified }
}
suspend fun updateHomework(homework: List<Homework>) = homeworkDb.updateAll(homework)
}
| 10
|
Kotlin
|
0
| 1
|
085158721e13230fa2bf5c56ec104121060e27f4
| 2,892
|
wulkanowy
|
Apache License 2.0
|
app/src/main/java/com/example/nbagameready/ui/adapters/TwitterAdapter.kt
|
nba-game-ready
| 451,234,866
| false
|
{"CSS": 72161, "Kotlin": 57072, "SCSS": 56546, "HTML": 22172, "JavaScript": 14234}
|
package com.example.nbagameready.ui.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.nbagameready.R
import com.example.nbagameready.network.twitterapi.Tweets
import com.example.nbagameready.network.twitterapi.User
import org.w3c.dom.Text
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
class TwitterAdapter (private val tweets: Tweets) :
RecyclerView.Adapter<TwitterAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TwitterAdapter.ViewHolder {
val inflater = LayoutInflater.from(parent.context)
val view = inflater.inflate(R.layout.twitter_list, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: TwitterAdapter.ViewHolder, position: Int) {
return holder.bindView(tweets)
}
override fun getItemCount(): Int {
return tweets.data?.size
}
// Clean all elements of the recycler
fun clear() {
tweets.data.toMutableList().clear()
notifyDataSetChanged()
}
// Add a list of items -- change to type used
fun addAll(tweetList: Tweets) {
tweets.data.toMutableList().addAll(tweetList.data)
notifyDataSetChanged()
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val userTweet: TextView = itemView.findViewById(R.id.tweet)
val userName: TextView = itemView.findViewById(R.id.userName)
val fullName: TextView = itemView.findViewById(R.id.fullName)
val time: TextView = itemView.findViewById(R.id.time)
val profileImage: ImageView = itemView.findViewById(R.id.profileImage)
fun bindView(tweets: Tweets) {
userTweet.text = tweets.data.get(bindingAdapterPosition).text
userName.text = tweets.includes?.users?.get(bindingAdapterPosition)?.username
fullName.text = tweets.includes?.users?.get(bindingAdapterPosition)?.name
time.text = fmtDateTime(tweets.data.get(bindingAdapterPosition).created_at)
Glide.with(itemView.context)
.load(tweets.includes.users.get(bindingAdapterPosition).profile_image_url)
.circleCrop()
.into(profileImage)
}
}
fun fmtDateTime(datetime: String): String? {
val inDF: DateFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
inDF.timeZone = TimeZone.getTimeZone("UTC")
val aDate = inDF.parse(datetime)
val outDF: DateFormat = SimpleDateFormat("hh:mm a")
outDF.timeZone = TimeZone.getDefault()
return outDF.format(aDate)
}
}
| 0
|
CSS
|
2
| 0
|
fbe549821103994c6f69580d29d3f157b1d87973
| 2,848
|
nba-game-ready
|
Creative Commons Attribution 3.0 Unported
|
app/src/main/java/com/waseem/libroom/feature/book/domain/Book.kt
|
waseemabbas8
| 629,653,320
| false
|
{"Kotlin": 167358}
|
package com.waseem.libroom.feature.book.domain
data class Book(
val id: String,
val title: String,
val cover: String,
val authorName: String
)
| 0
|
Kotlin
|
1
| 7
|
7d5264b3515d3e91a2a6ef5566191c6461b52a84
| 160
|
libroom-android
|
MIT License
|
app/src/main/java/quizzo/app/data/repository/QuizzoRepositoryImpl.kt
|
ibtesam123
| 271,865,081
| false
|
{"Kotlin": 99034}
|
package quizzo.app.data.repository
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.GoogleAuthProvider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.tasks.asDeferred
import quizzo.app.data.database.dao.HistoryDao
import quizzo.app.data.database.dao.UserDao
import quizzo.app.data.database.entity.History
import quizzo.app.data.database.entity.User
import quizzo.app.data.database.typeconvertors.DateConverter
import quizzo.app.data.network.NetworkDataSource
import quizzo.app.data.network.response.multiplayer.Match
import quizzo.app.data.network.response.multiplayer.Player
import quizzo.app.data.network.response.question.Question
import quizzo.app.util.category.Category
import quizzo.app.util.category.getAllCategories
import quizzo.app.util.loading.Loading
import quizzo.app.util.loading.LoadingState
class QuizzoRepositoryImpl(
private val networkSource: NetworkDataSource,
private val historyDao: HistoryDao,
private val userDao: UserDao
) : QuizzoRepository {
private val mutableQuestionList = MutableLiveData<List<Question>>()
private val mutableLoading = MutableLiveData<Loading>()
private val mutableHistoryList = MutableLiveData<List<History>>()
private val mutableUser = MutableLiveData<User>()
private var catList: List<Category>
private var anonymousSignIn: Boolean = false
private val auth: FirebaseAuth by lazy {
FirebaseAuth.getInstance()
}
init {
networkSource.questionList.observeForever { questionList ->
mutableQuestionList.postValue(questionList) //TODO: improve
}
networkSource.historyList.observeForever { historyList ->
GlobalScope.launch(Dispatchers.IO) {
val newHistoryList = historyList.distinctBy { it.date.toString() }
historyDao.addAllHistory(newHistoryList)
mutableHistoryList.postValue(newHistoryList)
}
}
networkSource.user.observeForever { user ->
GlobalScope.launch(Dispatchers.IO) {
userDao.upsertUser(user)
mutableUser.postValue(user)
}
}
catList = getAllCategories()
}
override val loading: LiveData<Loading>
get() = mutableLoading
override val questionList: LiveData<List<Question>>
get() = mutableQuestionList
override val historyList: LiveData<List<History>>
get() = mutableHistoryList
override val categoryList: List<Category>
get() = catList
override val user: LiveData<User>
get() = mutableUser
override val isAnonymousSignIn: Boolean
get() = anonymousSignIn
override val match: LiveData<Match>
get() = networkSource.match
override fun resetLoading() {
mutableLoading.postValue(Loading(-1, LoadingState.IDLE))
}
override fun getAllQuestions() {
GlobalScope.launch(Dispatchers.IO) {
mutableLoading.postValue(Loading(1, LoadingState.LOADING))
networkSource.getAllQuestions()
mutableLoading.postValue(Loading(1, LoadingState.COMPLETED))
}
}
override fun getQuestionByCategory(category: String) {
GlobalScope.launch(Dispatchers.IO) {
mutableLoading.postValue(Loading(1, LoadingState.LOADING))
networkSource.getQuestionByCategory(category)
mutableLoading.postValue(Loading(1, LoadingState.COMPLETED))
}
}
override fun getAllHistory() {
GlobalScope.launch(Dispatchers.IO) {
val historyList = historyDao.getAllHistory()
mutableHistoryList.postValue(historyList)
}
}
override fun addMatchToHistory(history: History) {
GlobalScope.launch(Dispatchers.IO) {
val his = historyDao.getSingleHistory(DateConverter().fromDate(history.date))
mutableQuestionList.postValue(null)
networkSource.resetMatchMaking()
if (his == null) {
historyDao.addHistory(history)
if (user.value != null)
networkSource.postHistory(history, user.value!!.email)
}
}
}
override fun signInUser(googleSignInAccount: GoogleSignInAccount) {
GlobalScope.launch(Dispatchers.IO) {
mutableLoading.postValue(Loading(2, LoadingState.LOADING))
auth.signInWithCredential(
GoogleAuthProvider.getCredential(
googleSignInAccount.idToken!!,
null
)
).asDeferred().await()
networkSource.createUser(
auth.uid!!,
googleSignInAccount.displayName!!,
googleSignInAccount.email!!,
googleSignInAccount.photoUrl!!.toString()
)
anonymousSignIn = false
mutableLoading.postValue(Loading(2, LoadingState.COMPLETED))
}
}
override fun signInAnonymously() {
anonymousSignIn = true
}
override fun getUser() {
GlobalScope.launch(Dispatchers.IO) {
if (auth.currentUser == null) {
mutableUser.postValue(null)
} else {
val userInfo = userDao.getUserByID(auth.currentUser!!.uid)
mutableUser.postValue(userInfo)
}
}
}
override fun logout() {
GlobalScope.launch(Dispatchers.IO) {
historyDao.deleteAllHistory()
userDao.deleteUser()
auth.signOut()
mutableHistoryList.postValue(null)
mutableUser.postValue(null)
}
}
override fun findMatch() {
networkSource.initMatchMakingSocket(user.value!!.id)
networkSource.findMatch(user.value!!.username, user.value!!.imageURL, user.value!!.id)
}
override fun findMatchBot() = networkSource.findMatchBot()
override fun destroyMatchMakingSocket() = networkSource.destroyMatchMakingSocket()
override fun initMatch() = networkSource.initMatchSocket(user.value!!.id)
override fun matchComplete(score: Int) {
networkSource.matchComplete(
Player(
user.value!!.id,
user.value!!.username,
user.value!!.imageURL,
score
)
)
}
override fun destroyMatchSocket() = networkSource.destroyMatchSocket()
}
| 2
|
Kotlin
|
13
| 35
|
d4449a7e7a97cfcd0e4a57f2ec7b300aeb9abcdf
| 6,645
|
Quizzo
|
MIT License
|
core/src/test/kotlin/in/specmatic/core/pattern/UUIDPatternTest.kt
|
znsio
| 247,710,440
| false
| null |
package `in`.specmatic.core.pattern
import `in`.specmatic.core.Resolver
import `in`.specmatic.core.Result
import `in`.specmatic.core.value.StringValue
import `in`.specmatic.shouldMatch
import `in`.specmatic.shouldNotMatch
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import java.util.UUID
internal class UUIDPatternTest {
@Test
fun `should parse a valid UUIDvalue`() {
val uuidString = UUID.randomUUID().toString()
val uuidValue = UUIDPattern.parse(uuidString, Resolver())
assertEquals(uuidString, uuidValue.string)
}
@Test
fun `should generate a UUIDvalue which can be parsed`() {
val valueGenerated = UUIDPattern.generate(Resolver())
val valueParsed = UUIDPattern.parse(valueGenerated.string, Resolver())
assertEquals(valueGenerated, valueParsed)
}
@Test
fun `should match a valid UUIDvalue`() {
val valueGenerated = UUIDPattern.generate(Resolver())
valueGenerated shouldMatch UUIDPattern
}
@Test
fun `should fail to match an invalid UUIDvalue`() {
val valueGenerated = StringValue("this is not a UUID value")
valueGenerated shouldNotMatch UUIDPattern
}
@Test
fun `should return itself when generating a new pattern based on a row`() {
val uuidPatterns = UUIDPattern.newBasedOn(Row(), Resolver())
assertEquals(1, uuidPatterns.size)
assertEquals(UUIDPattern, uuidPatterns.first())
}
@Test
fun `should match this UUIDtime format`() {
val uuid1 = StringValue("cfb64879-6e10-47f6-a824-a7606a36d423")
val uuid2 = StringValue("3b45392f-3e4d-440e-b680-2ab673a197a6")
assertThat(UUIDPattern.matches(uuid1, Resolver())).isInstanceOf(Result.Success::class.java)
assertThat(UUIDPattern.matches(uuid2, Resolver())).isInstanceOf(Result.Success::class.java)
}
}
| 46
|
Kotlin
|
32
| 92
|
b3eb9b6e0f7d42bde35d95b83ea187cd1d6aa3bc
| 1,960
|
specmatic
|
MIT License
|
app/src/main/java/com/example/demoh264/MainActivity.kt
|
ruojinghong
| 626,412,786
| false
| null |
package com.example.demoh264
import android.Manifest
import android.app.Activity
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Build.VERSION
import android.os.Bundle
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceHolder.Callback
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.example.demoh264.databinding.ActivityMainBinding
import com.example.demoh264.service.CaptureScreenService
import com.example.demoh264.utils.CodecUtils
import com.example.demoh264.utils.H264Decode
import com.example.demoh264.utils.H264Encode
import java.io.File
import java.io.FileInputStream
class MainActivity : AppCompatActivity() {
// 抽取aac音频文件
// ffmpeg -i douyin.MP4 -acodec copy -vn douyin.aac
// 抽取H264视频文件
// ffmpeg -i douyin.MP4 -c:v copy -bsf:v h264_mp4toannexb -an douyin.h264
var byteeArray: ByteArray? = null
// var path = "/storage/emulated/0/DCIM/Video/RadagonOfTheGoldenOrder.mp4"
// var path = "/storage/emulated/0/DCIM/Video/douyin.mp4"
var path = "douyin.h264"
private lateinit var surfaceHolder: SurfaceHolder
private lateinit var mediaProjectionManager:MediaProjectionManager
init {
val TAG = "H264"
}
private lateinit var binding: ActivityMainBinding
private lateinit var registerForActivityResult :ActivityResultLauncher<Intent>
private var encodeThread:H264Encode? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
byteeArray = assets.open(path).readBytes()
Log.i("vedio size", "${byteeArray?.size}")
// Example of a call to a native method
// binding.sampleText.text = stringFromJNI()
CodecUtils.getSupportCodeC()
checkPermission()
initSurface(720,1080)
mediaProjectionManager = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
initLisener()
}
private fun initLisener() {
binding.startRecord.setOnClickListener{
startRecord()
}
binding.stopRecord.setOnClickListener{
stopRecord()
}
registerForActivityResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if(it.resultCode == Activity.RESULT_OK){
val mediaProject = mediaProjectionManager.getMediaProjection(it.resultCode,it.data!!)
val path= getExternalFilesDir(null)?.path+"/screen.h264"
encodeThread = H264Encode(mediaProject,path!!)
encodeThread?.startEncode()
}
}
binding.goToSocket.setOnClickListener{
startActivity(Intent(this,SocketActivity::class.java))
}
binding.goToNewDecoder.setOnClickListener {
startActivity(Intent(this,DecoderActivity::class.java))
}
binding.goToNewOpengl.setOnClickListener {
startActivity(Intent(this,SimpleRenderActivity::class.java))
}
}
@RequiresApi(Build.VERSION_CODES.O)
fun startRecord(){
startForegroundService(Intent(this,CaptureScreenService::class.java))
registerForActivityResult.launch(mediaProjectionManager.createScreenCaptureIntent())
}
fun stopRecord(){
encodeThread?.stopEncode()
}
override fun onDestroy() {
super.onDestroy()
encodeThread?.stopEncode()
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
}
}
/**
* A native method that is implemented by the 'demoh264' native library,
* which is packaged with this application.
*/
external fun stringFromJNI(): String
companion object {
// Used to load the 'demoh264' library on application startup.
// init {
// System.loadLibrary("demoh264")
// }
}
private fun decodeSplitNalu(){
}
fun play(view: View){
H264Decode( FileInputStream(File(getExternalFilesDir(null)?.path+"/screen.h264")).readBytes(),720,1080,surfaceHolder.surface).start()
}
private fun checkPermission() {
// 简单处理下权限
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(
Manifest.permission.WRITE_EXTERNAL_STORAGE
) != PackageManager.PERMISSION_GRANTED
) {
val permissions = arrayOf(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
)
requestPermissions(permissions, 1)
}
}
private fun initSurface(width:Int,h:Int){
binding.surface.holder.addCallback(object :Callback{
override fun surfaceCreated(holder: SurfaceHolder) {
surfaceHolder = holder
}
override fun surfaceChanged(
holder: SurfaceHolder,
format: Int,
width: Int,
height: Int
) {
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
}
})
}
}
| 0
|
Kotlin
|
0
| 0
|
1cd5c774d238c81b27fcbab7fd7619ab53eb15f4
| 5,255
|
H264Demo
|
Apache License 2.0
|
app/src/main/java/com/revolgenx/anilib/ui/presenter/media/MediaCharacterPresenter.kt
|
rev0lgenX
| 244,410,204
| false
| null |
package com.revolgenx.anilib.ui.presenter.media
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import com.otaliastudios.elements.Element
import com.otaliastudios.elements.Page
import com.revolgenx.anilib.R
import com.revolgenx.anilib.data.model.media_info.MediaCharacterModel
import com.revolgenx.anilib.databinding.AnimeCharacterPresenterLayoutBinding
import com.revolgenx.anilib.databinding.MangaCharacterPresenterLayoutBinding
import com.revolgenx.anilib.infrastructure.event.OpenCharacterEvent
import com.revolgenx.anilib.infrastructure.event.OpenStaffEvent
import com.revolgenx.anilib.ui.presenter.BasePresenter
class MediaCharacterPresenter(context: Context) :
BasePresenter<ViewBinding, MediaCharacterModel>(context) {
override val elementTypes: Collection<Int>
get() = listOf(0, 1)
private val characterRoles by lazy {
context.resources.getStringArray(R.array.character_role)
}
private val staffLanguages by lazy {
context.resources.getStringArray(R.array.staff_language)
}
override fun bindView(
inflater: LayoutInflater,
parent: ViewGroup?,
elementType: Int
): ViewBinding {
return when (elementType) {
1 -> {
MangaCharacterPresenterLayoutBinding.inflate(inflater, parent, false)
}
else -> {
AnimeCharacterPresenterLayoutBinding.inflate(inflater, parent, false)
}
}
}
override fun onBind(page: Page, holder: Holder, element: Element<MediaCharacterModel>) {
super.onBind(page, holder, element)
val item = element.data ?: return
val binding = holder.getBinding() ?: return
when (holder.elementType) {
0 -> {
(binding as AnimeCharacterPresenterLayoutBinding).apply {
characterImageView.setImageURI(item.image?.image)
characterNameTv.text = item.name?.full
characterRoleTv.text = item.role?.let { characterRoles[it] }
characterLayoutContainer.setOnClickListener {
OpenCharacterEvent(
item.id!!
).postEvent
}
item.voiceActor?.let { actorModel ->
voiceActorLayoutContainer
voiceActorImageView.setImageURI(actorModel.voiceActorImageModel?.image)
voiceActorNameTv.text = actorModel.name
voiceActorLanguage.text =
actorModel.language?.let { staffLanguages[it] }
voiceActorLayoutContainer.setOnClickListener {
OpenStaffEvent(
actorModel.actorId!!,
).postEvent
}
}
}
}
1 -> {
(binding as MangaCharacterPresenterLayoutBinding).apply {
mangaCharacterImageView.setImageURI(item.image?.image)
mangaCharacterNameTv.text = item.name?.full
mangaCharacterRoleTv.text = item.role?.let { characterRoles[it] }
mangaCharacterContainer.setOnClickListener {
OpenCharacterEvent(
item.id!!
).postEvent
}
}
}
}
}
}
| 3
|
Kotlin
|
1
| 24
|
355d2b5510682d869f18e0113453237af8a1f1cc
| 3,588
|
AniLib
|
Apache License 2.0
|
app/src/main/java/com/annas/playground/data/repository/city/CityRepository.kt
|
annasta13
| 826,067,757
| false
|
{"Kotlin": 230187}
|
package com.annas.playground.data.repository.city
interface CityRepository {
suspend fun getCity(): List<String>
}
| 0
|
Kotlin
|
0
| 1
|
a8fa4467421d9c40ff9945c07b60f3108120cd9b
| 120
|
playground
|
Apache License 2.0
|
server/src/main/kotlin/org/kryptonmc/krypton/util/crypto/SignatureUpdater.kt
|
KryptonMC
| 255,582,002
| false
| null |
/*
* This file is part of the Krypton project, licensed under the Apache License v2.0
*
* Copyright (C) 2021-2023 KryptonMC and the contributors of the Krypton project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kryptonmc.krypton.util.crypto
fun interface SignatureUpdater {
fun update(output: Output)
fun interface Output {
fun update(signature: ByteArray)
}
}
| 27
|
Kotlin
|
11
| 233
|
a9eff5463328f34072cdaf37aae3e77b14fcac93
| 919
|
Krypton
|
Apache License 2.0
|
app/src/main/java/com/gerardbradshaw/fairday/retrofit/OneCallWeatherFile.kt
|
GerardBradshaw
| 313,461,379
| false
|
{"Gradle": 5, "Shell": 1, "Text": 5, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "INI": 2, "Proguard": 3, "XML": 67, "Kotlin": 62, "Java Properties": 1, "Java": 2}
|
package com.gerardbradshaw.fairday.retrofit
import com.google.gson.annotations.SerializedName
class OneCallWeatherFile {
var lat: Float? = null
var lon: Float? = null
var timezone: String? = null
@SerializedName("timezone_offset") var timezoneOffset: Long? = null
var current: Current? = null
@SerializedName("minutely") var minutelyList: List<Minutely>? = null
@SerializedName("hourly") var hourlyList: List<Hourly>? = null
@SerializedName("daily") var dailyList: List<Daily>? = null
@SerializedName("alerts") var alertsList: List<Alerts>? = null
class Current {
var dt: Long? = null
var sunrise: Long? = null
var sunset: Long? = null
var temp: Float? = null
@SerializedName("feels_like") var feelsLike: Float? = null
var pressure: Float? = null
var humidity: Float? = null
@SerializedName("dew_point") var dewPoint: Float? = null
var clouds: Float? = null
var uvi: Float? = null
var visibility: Int? = null
@SerializedName("wind_speed") var windSpeed: Float? = null
@SerializedName("wind_gust") var windGust: Float? = null
@SerializedName("wind_deg") var windDirection: Float? = null
var rain: Rain? = null
var snow: Snow? = null
@SerializedName("weather") var weatherList: List<Weather>? = null
}
class Hourly {
var dt: Long? = null
var temp: Float? = null
@SerializedName("feels_like") var feelsLike: Float? = null
var pressure: Float? = null
var humidity: Float? = null
@SerializedName("dew_point") var dewPoint: Float? = null
var uvi: Float? = null
var clouds: Float? = null
var visibility: Int? = null
@SerializedName("wind_speed") var windSpeed: Float? = null
@SerializedName("wind_gust") var windGust: Float? = null
@SerializedName("wind_deg") var windDirection: Float? = null
@SerializedName("pop") var probabilityOfPrecipitation: Float? = null
var rain: Rain? = null
var snow: Snow? = null
@SerializedName("weather") var weatherList: List<Weather>? = null
}
class Daily {
var dt: Long? = null
var sunrise: Long? = null
var sunset: Long? = null
var temp: Temp? = null
@SerializedName("feels_like") var feelsLike: FeelsLike? = null
var pressure: Float? = null
var humidity: Float? = null
@SerializedName("dew_point") var dewPoint: Float? = null
@SerializedName("wind_speed") var windSpeed: Float? = null
@SerializedName("wind_gust") var windGust: Float? = null
@SerializedName("wind_deg") var windDirection: Float? = null
var clouds: Float? = null
var uvi: Float? = null
@SerializedName("pop") var probabilityOfPrecipitation: Float? = null
var rain: Float? = null
var snow: Float? = null
@SerializedName("weather") var weatherList: List<Weather>? = null
}
class Alerts {
@SerializedName("sender_name") var senderName: String? = null
var event: String? = null
var start: Long? = null
var end: Long? = null
var description: String? = null
}
class Rain {
@SerializedName("1h") var rainLastHour: Float? = null
}
class Snow {
@SerializedName("1h") var snowLastHour: Float? = null
}
class Weather {
var id: Int? = null
var main: String? = null
var description: String? = null
var icon: String? = null
}
class Minutely {
var dt: Long? = null
var precipitation: Float? = null
}
class Temp {
var morn: Float? = null
var day: Float? = null
var eve: Float? = null
var night: Float? = null
var min: Float? = null
var max: Float? = null
}
class FeelsLike {
var morn: Float? = null
var day: Float? = null
var eve: Float? = null
var night: Float? = null
}
}
| 0
|
Kotlin
|
1
| 3
|
b4dbbd87b01040e5086a5df674aac382f889a647
| 3,714
|
FairDay
|
Apache License 2.0
|
samples/standalone/src/main/kotlin/org/jetbrains/jewel/samples/standalone/viewmodel/ViewInfo.kt
|
JetBrains
| 440,164,967
| false
|
{"Kotlin": 1567144, "Java": 22778, "Shell": 361}
|
package org.jetbrains.jewel.samples.standalone.viewmodel
import androidx.compose.runtime.Composable
import org.jetbrains.jewel.ui.icon.IconKey
data class ViewInfo(
val title: String,
val iconKey: IconKey,
val content: @Composable () -> Unit,
)
| 81
|
Kotlin
|
34
| 659
|
dca6945b4014fe931b4a10504293531996672909
| 258
|
jewel
|
Apache License 2.0
|
Employee/src/main/kotlin/rs/rbt/internship/employee/controller/EmployeeController.kt
|
nemanjaandjelkovic
| 580,776,849
| false
| null |
package rs.rbt.internship.employee.controller
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.web.bind.annotation.*
import rs.rbt.internship.database.model.UsedVacation
import rs.rbt.internship.employee.service.EmployeeBusinessService
import org.springframework.security.core.*
@RestController
@RequestMapping("/employee")
class EmployeeController {
@Autowired
lateinit var employeeBusinessService: EmployeeBusinessService
@GetMapping("/listVacation")
@ResponseBody
fun listOfVacationDates(
@RequestParam
dateStart: String,
@RequestParam
dateEnd: String
): MutableList<UsedVacation> {
val auth: Authentication = SecurityContextHolder.getContext().authentication
return employeeBusinessService.showListRecordsOfUsedVacation(dateStart, dateEnd, auth.name)
}
@PostMapping("/addVacation")
fun addVacation(
@RequestParam
dateStart: String,
@RequestParam
dateEnd: String
) {
val auth: Authentication = SecurityContextHolder.getContext().authentication
employeeBusinessService.addVacation(dateStart, dateEnd, auth.name)
}
@GetMapping("")
fun employeeInfo(year:String): MutableMap<String, MutableList<Int>> {
val auth: Authentication = SecurityContextHolder.getContext().authentication
return employeeBusinessService.employeeInfo(auth.name,year)
}
}
| 1
|
Kotlin
|
0
| 0
|
c3c7a69c3e7a7e64f564f53e149a90eba35894bf
| 1,529
|
rbt-intership-project
|
Apache License 2.0
|
src/main/kotlin/com/rhseung/wiw/WhatIWantClient.kt
|
minecraft-stuffs
| 843,806,058
| false
|
{"Kotlin": 15052, "Java": 1477}
|
package com.rhseung.wiw
import com.google.common.math.IntMath.pow
import com.rhseung.wiw.init.ModItems
import com.rhseung.wiw.item.ModularToolItem
import com.rhseung.wiw.util.Color
import net.fabricmc.api.ClientModInitializer
import net.fabricmc.api.EnvType
import net.fabricmc.api.Environment
import net.fabricmc.fabric.api.client.rendering.v1.ColorProviderRegistry
import net.minecraft.client.MinecraftClient
import net.minecraft.client.color.item.ItemColorProvider
import net.minecraft.item.ItemStack
object WhatIWantClient : ClientModInitializer {
override fun onInitializeClient() {
ColorProviderRegistry.ITEM.register(ItemColorProvider { stack, tintIndex ->
Color.materialToColor((stack.item as ModularToolItem).tools[tintIndex].material).toInt() - pow(16, 6)
}, *ModItems.MODULAR_PICKAXES);
}
}
| 0
|
Kotlin
|
0
| 0
|
4ed7d6f6168974338fe95261179e6159b2732183
| 839
|
particle-tint-1.21.1
|
Creative Commons Zero v1.0 Universal
|
app/src/main/java/com/example/sims/LoginActivity.kt
|
rykieldc
| 854,313,740
| false
|
{"Kotlin": 49736}
|
package com.example.sims
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class LoginActivity : AppCompatActivity() {
private lateinit var usernameEditText: EditText
private lateinit var passwordEditText: EditText
private lateinit var loginButton: Button
private lateinit var contactAdminTextView: TextView
private lateinit var firebaseHelper: FirebaseDatabaseHelper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
installSplashScreen()
enableEdgeToEdge()
setContentView(R.layout.activity_login)
usernameEditText = findViewById(R.id.username)
passwordEditText = findViewById(R.id.password)
loginButton = findViewById(R.id.loginButton)
contactAdminTextView = findViewById(R.id.contactAdmin)
firebaseHelper = FirebaseDatabaseHelper()
loginButton.setOnClickListener {
val username = usernameEditText.text.toString().trim()
val password = passwordEditText.text.toString().trim()
if (username.isEmpty() || password.isEmpty()) {
Toast.makeText(this, "Please enter a username and password", Toast.LENGTH_SHORT)
.show()
} else {
// Check user credentials in Firebase
firebaseHelper.checkUser(username, password) { isUserValid ->
if (isUserValid) {
firebaseHelper.checkUserData(username) { user ->
val intent = Intent(this, MainActivity::class.java)
intent.putExtra("name", user.name)
intent.putExtra("username", user.username)
intent.putExtra("role", user.role)
startActivity(intent)
finish()
}
} else {
Toast.makeText(
this,
"Invalid username or password",
Toast.LENGTH_SHORT
).show()
}
}
}
}
contactAdminTextView.setOnClickListener {
val phoneNumber = "09280990649"
val phoneIntent = Intent(Intent.ACTION_DIAL).apply {
data = Uri.parse("tel:$phoneNumber")
}
startActivity(phoneIntent)
}
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
}
}
| 1
|
Kotlin
|
0
| 0
|
76d8a7aaabbab1e7689b0ba9295aa1f878193165
| 3,184
|
cc17-3k-uti
|
Apache License 2.0
|
src/main/kotlin/me/argraur/railgun/command/impls/admin/Prefix.kt
|
argraur
| 262,636,637
| false
| null |
/*
* Copyright (C) 2020 <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 me.argraur.railgun.command.impls.admin
import me.argraur.railgun.Railgun
import me.argraur.railgun.command.Command
import me.argraur.railgun.utils.Embed
import me.argraur.railgun.utils.Format
import me.argraur.railgun.utils.Level
import net.dv8tion.jda.api.entities.Message
class Prefix: Command {
private val name = "prefix"
private val usage = "$name <prefix>"
private val desc = "Sets new command prefix for this guild"
private val level = Level.ADMIN
override fun exec(message: Message) {
val content = Format.stripCommand(message)
when {
(content == "") -> message.channel.sendMessage(Embed().fastCreate("Current prefix", Format.shellYellow(Railgun.prefix.getPrefix(message)))).queue()
else -> {
Railgun.prefix.setPrefix(message, content)
message.channel.sendMessage(Embed().fastCreate("Set new prefix", Format.shellYellow(Railgun.prefix.getPrefix(message)))).queue()
}
}
}
override fun getName(): String {
return name
}
override fun getUsage(): String {
return usage
}
override fun getDesc(): String {
return desc
}
override fun getLevel(): Level {
return level
}
}
| 0
|
Kotlin
|
1
| 1
|
14444288a62b9ddca903d49af633ebd373c131c0
| 1,862
|
RailgunKT
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.