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
core/network/src/main/kotlin/org/michaelbel/movies/network/TmdbConfig.kt
michaelbel
115,437,864
false
null
package org.michaelbel.movies.network const val TMDB_URL = "https://themoviedb.org" const val TMDB_TERMS_OF_USE = "https://themoviedb.org/documentation/website/terms-of-use" const val TMDB_PRIVACY_POLICY = "https://themoviedb.org/privacy-policy" const val TMDB_REGISTER = "https://themoviedb.org/signup" const val TMDB_RESET_PASSWORD = "https://themoviedb.org/reset-password" const val TMDB_MOVIE_URL = "https://themoviedb.org/movie/%d" private val tmdbApiKey: String get() = BuildConfig.TMDB_API_KEY val isTmdbApiKeyEmpty: Boolean get() = tmdbApiKey.isEmpty() || tmdbApiKey == "null"
6
null
30
167
5658a87850a52944f9b9dd60e8d66fa5a1b00e40
595
movies
Apache License 2.0
Entrega/app/src/main/java/com/jjmorillo/ladespensademicasa/models/Producto.kt
jjmorleo
356,499,729
false
null
package com.jjmorillo.ladespensademicasa.models data class Producto(val nombre: String, val marca: String, val descripcion: String, val imagen: String, val precio_unidad: Double, val precio: Double) { var id: Long = -1 constructor(id: Long, nombre: String, marca: String, descripcion: String, imagen: String, precio_unidad: Double, precio: Double): this(nombre, marca, descripcion, imagen, precio_unidad, precio){ this.id = id } override fun toString(): String { return "Producto(id=$id, nombre=$nombre, marca=$marca, descripcion=$descripcion, imagen=$imagen, precio_unidad=$precio_unidad, precio=$precio, id=$id)" } }
0
Kotlin
0
0
1f555d30c298501215655317578de2c8cc3ea465
661
la-despensa-de-mi-casa
MIT License
client/src/jvmMain/kotlin/com/monkopedia/imdex/Style.kt
Monkopedia
305,151,965
false
{"Kotlin": 381076, "JavaScript": 1289, "HTML": 912}
/* * Copyright 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.monkopedia.imdex import com.googlecode.lanterna.SGR import com.googlecode.lanterna.TextColor import com.googlecode.lanterna.graphics.DefaultMutableThemeStyle import com.googlecode.lanterna.graphics.ThemeStyle import com.monkopedia.lanterna.Lanterna.gui object Style { val markdownStyle by lazy { gui.theme.getDefinition(Style::class.java) } const val LINK_STYLE_NAME = "LINK" val DEFAULT_LINK_STYLE: ThemeStyle = DefaultMutableThemeStyle( TextColor.Factory.fromString("#81c754"), TextColor.Factory.fromString("#282828"), SGR.BOLD ) val linkStyle by lazy { markdownStyle.getCustom(LINK_STYLE_NAME, DEFAULT_LINK_STYLE) } const val SELECTED_LINK_STYLE_NAME = "LINK_SELECTED" val DEFAULT_SELECTED_LINK_STYLE: ThemeStyle = DefaultMutableThemeStyle( TextColor.Factory.fromString("#282828"), TextColor.Factory.fromString("#81c754"), SGR.BOLD ) val selectedLinkStyle by lazy { markdownStyle.getCustom(SELECTED_LINK_STYLE_NAME, DEFAULT_SELECTED_LINK_STYLE) } const val CODE_STYLE_NAME = "CODE_BLOCK" val DEFAULT_CODE_STYLE: ThemeStyle by lazy { DefaultMutableThemeStyle( gui.theme.defaultDefinition.normal.foreground, TextColor.Factory.fromString("#282828"), *gui.theme.defaultDefinition.normal.sgRs.toTypedArray() ) } val codeStyle by lazy { markdownStyle.getCustom(CODE_STYLE_NAME, DEFAULT_CODE_STYLE) } const val ASCII_FONTS_NAME = "ASCII_FONTS" const val ASCII_FONTS_DEFAULT = true val asciiFontsEnabled by lazy { markdownStyle.getBooleanProperty(ASCII_FONTS_NAME, ASCII_FONTS_DEFAULT) } const val HEADER_PRIMARY_NAME = "HEADER_PRIMARY" val DEFAULT_HEADER_PRIMARY: ThemeStyle by lazy { DefaultMutableThemeStyle( markdownStyle.normal.foreground, markdownStyle.normal.background, SGR.UNDERLINE, SGR.BOLD ) } val headerPrimaryStyle by lazy { markdownStyle.getCustom(HEADER_PRIMARY_NAME, DEFAULT_HEADER_PRIMARY) } const val HEADER_SECONDARY_NAME = "HEADER_SECONDARY" val DEFAULT_HEADER_SECONDARY: ThemeStyle by lazy { DefaultMutableThemeStyle( markdownStyle.normal.foreground, markdownStyle.normal.background, SGR.UNDERLINE ) } val headerSecondaryStyle by lazy { markdownStyle.getCustom(HEADER_SECONDARY_NAME, DEFAULT_HEADER_SECONDARY) } }
0
Kotlin
0
0
c6f6a460e00af6b8ffc98b8e39cbad509549bc9f
3,144
imdex
Apache License 2.0
server/src/main/kotlin/com/sortinghat/backend/server/SystemControllerAdvice.kt
the-sortinghat
529,660,037
false
null
package com.sortinghat.backend.server import com.sortinghat.backend.data_collector.exceptions.EntityAlreadyExistsException import com.sortinghat.backend.data_collector.exceptions.UnableToConvertDataException import com.sortinghat.backend.data_collector.exceptions.UnableToFetchDataException import com.sortinghat.backend.data_collector.exceptions.UnableToParseDataException import com.sortinghat.backend.domain.exceptions.EntityNotFoundException import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler @ControllerAdvice class SystemControllerAdvice { @ExceptionHandler(value = [UnableToFetchDataException::class]) fun exception(e: UnableToFetchDataException) = ResponseEntity<Any>(mapOf("error" to e.message), HttpStatus.NOT_FOUND) @ExceptionHandler(value = [UnableToParseDataException::class]) fun exception(e: UnableToParseDataException) = ResponseEntity<Any>(mapOf("error" to e.message), HttpStatus.BAD_REQUEST) @ExceptionHandler(value = [UnableToConvertDataException::class]) fun exception(e: UnableToConvertDataException) = ResponseEntity<Any>(mapOf("error" to e.message), HttpStatus.BAD_REQUEST) @ExceptionHandler(value = [EntityAlreadyExistsException::class]) fun exception(e: EntityAlreadyExistsException) = ResponseEntity<Any>(mapOf("error" to e.message), HttpStatus.CONFLICT) @ExceptionHandler(value = [EntityNotFoundException::class]) fun exception(e: EntityNotFoundException) = ResponseEntity<Any>(mapOf("error" to e.message), HttpStatus.NOT_FOUND) }
0
Kotlin
0
0
95695a1808e477ce67d8257891f4fa9be21f8cce
1,712
backend
MIT License
app/src/main/java/com/herdal/moviehouse/ui/movies_by_genre/MoviesByGenreFragment.kt
herdal06
579,902,398
false
{"Kotlin": 167133}
package com.herdal.moviehouse.ui.movies_by_genre import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.herdal.moviehouse.databinding.FragmentMoviesByGenreBinding import com.herdal.moviehouse.domain.uimodel.genre.GenreUiModel import com.herdal.moviehouse.ui.home.adapter.movie.MovieAdapter import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch import timber.log.Timber @AndroidEntryPoint class MoviesByGenreFragment : Fragment() { private var _binding: FragmentMoviesByGenreBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! private val viewModel: MoviesByGenreViewModel by viewModels() private val moviesByGenreAdapter: MovieAdapter by lazy { MovieAdapter(::onClickMovie) } private val navigationArgs: MoviesByGenreFragmentArgs by navArgs() private fun getArgs() = navigationArgs.genre override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentMoviesByGenreBinding.inflate(inflater, container, false) val view = binding.root setupRecyclerView() getArgs().name?.let { setToolBarTitle(it) } observeMovies(getArgs()) return view } private fun setupRecyclerView() = binding.apply { rvMoviesByGenre.adapter = moviesByGenreAdapter } private fun observeMovies(genre: GenreUiModel) = lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { genre.id?.let { viewModel.getMoviesByGenre(it).observe(viewLifecycleOwner) { moviesByGenreAdapter.submitData(lifecycle, it) Timber.d("$it") } } } } private fun setToolBarTitle(genreName: String) { (activity as AppCompatActivity).supportActionBar?.title = genreName } private fun onClickMovie(movieId: Int) { val action = MoviesByGenreFragmentDirections.actionMoviesByGenreFragmentToMovieDetailsFragment( movieId ) findNavController().navigate(action) } override fun onDestroyView() { super.onDestroyView() _binding = null } }
0
Kotlin
0
5
24211bea52cd378353be854bbd78eed1c86b879d
2,746
HekMovie
Apache License 2.0
browser-kotlin/src/jsMain/kotlin/web/rtc/RTCTrackEvent.types.kt
karakum-team
393,199,102
false
null
// Automatically generated - do not modify! @file:Suppress( "NON_ABSTRACT_MEMBER_OF_EXTERNAL_INTERFACE", ) package web.rtc import seskar.js.JsValue import web.events.EventType sealed external interface RTCTrackEventTypes { @JsValue("track") val TRACK: EventType<RTCTrackEvent> get() = definedExternally }
0
null
6
28
664781d7bdaf5f4aca206e11990b1d304fd45212
329
types-kotlin
Apache License 2.0
opencola-server/cli/src/main/kotlin/Entity.kt
johnmidgley
441,008,781
false
{"Kotlin": 1130580, "Java": 851281, "Dart": 181759, "Clojure": 111662, "CSS": 61393, "HTML": 42666, "Shell": 17124, "Swift": 14391, "JavaScript": 10218, "PowerShell": 8360, "Ruby": 1586, "Dockerfile": 654, "Objective-C": 38}
/* * Copyright 2024 OpenCola * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package io.opencola.cli import io.opencola.security.MockKeyStore import io.opencola.security.hash.Hash import io.opencola.storage.entitystore.EntityStore import io.opencola.storage.ExposedEntityStoreContext import java.nio.file.Path import kotlin.io.path.createDirectory fun entityStoreContext(storagePath: Path, passwordHash: Hash? = null): ExposedEntityStoreContext { return if(passwordHash != null) ExposedEntityStoreContext(storagePath, passwordHash) else ExposedEntityStoreContext(storagePath, keyStore = MockKeyStore()) } fun rebuildEntityStore(sourcePath: Path, passwordHash: Hash, destPath: Path) { if(!destPath.toFile().exists()) { destPath.createDirectory() } val sourceContext = ExposedEntityStoreContext(sourcePath, passwordHash) val destContext = ExposedEntityStoreContext( destPath, sourceContext.password, sourceContext.keyStore, sourceContext.signator, sourceContext.addressBook ) println("Rebuilding entities from ${sourceContext.storagePath} in ${destContext.storagePath}") sourceContext.entityStore.getAllSignedTransactions().forEach { transaction -> println("+ ${transaction.transaction.id}") destContext.entityStore.addSignedTransactions(listOf(transaction)) } } fun compareEntityStores(entityStore1: EntityStore, entityStore2: EntityStore) { val entityStore1Size = entityStore1.getEntities(emptySet(), emptySet()).size val entityStore2Size = entityStore2.getEntities(emptySet(), emptySet()).size if(entityStore1Size != entityStore2Size) { println("Entity store sizes differ: $entityStore1Size vs $entityStore2Size") } entityStore1.getEntities(emptySet(), emptySet()).forEach { entity1 -> entityStore2.getEntity(entity1.authorityId, entity1.entityId)?.let { entity2 -> if(entity1 != entity2) { println("Entity ${entity1.authorityId}:${entity1.entityId} differs") val diffs = entity1.diff(entity2) diffs.forEach { (fact1, fact2) -> println("E1: $fact1") println("E2: $fact2") } } } ?: println("Entity ${entity1.entityId} not found in entityStore2") } } fun cat(storagePath: Path, entityIdString: String) { val context = entityStoreContext(storagePath) val (authorityIds, entityIds) = parseEntityIdString(entityIdString) context.entityStore.getEntities(authorityIds, entityIds).forEach { it.getCurrentFacts().forEach { fact -> println(fact.toString().replace("\n", "\\n")) } } } fun ls(storagePath: Path) { val context = entityStoreContext(storagePath) context.entityStore.getEntities(emptySet(), emptySet()).forEach { println("${it.authorityId}:${it.entityId}") } } fun entity(storagePath: Path, entityCommand: EntityCommand, getPasswordHash: () -> Hash) { if(entityCommand.cat != null) { cat(storagePath, entityCommand.cat!!) } else if (entityCommand.ls == true) { ls(storagePath) } else if(entityCommand.rebuild != null) { rebuildEntityStore(storagePath, getPasswordHash(), storagePath.resolve("entity-rebuild-${System.currentTimeMillis()}")) } else if(entityCommand.cmp != null) { val entityStore1 = entityStoreContext(storagePath).entityStore val entityStore2 = entityStoreContext(Path.of(entityCommand.cmp!!)).entityStore compareEntityStores(entityStore1, entityStore2) } }
16
Kotlin
1
3
2fd637c1e17db537aae3ba3852ddc09e1d1e6387
4,123
opencola
Apache License 2.0
feature_profile/src/main/kotlin/com/igorwojda/showcase/profile/ProfileKoinModule.kt
igorwojda
158,460,787
false
{"Kotlin": 106132}
package com.igorwojda.showcase.profile import com.igorwojda.showcase.profile.data.dataModule import com.igorwojda.showcase.profile.domain.domainModule import com.igorwojda.showcase.profile.presentation.presentationModule val featureProfilesModules = listOf( presentationModule, domainModule, dataModule, )
15
Kotlin
897
6,503
de16176f6f4457c11a87bb085aa237d8231c8357
320
android-showcase
MIT License
feature/movie/src/main/kotlin/com/azizutku/movie/feature/movie/data/repository/datasourceImpl/MovieRemoteDataSourceImpl.kt
azizutku
579,143,942
false
{"Kotlin": 265966, "Shell": 647}
package com.azizutku.movie.feature.movie.data.repository.datasourceImpl import com.azizutku.movie.feature.movie.data.remote.MovieApiService import com.azizutku.movie.feature.movie.data.remote.dto.MovieDto import com.azizutku.movie.feature.movie.data.repository.datasource.MovieRemoteDataSource import javax.inject.Inject class MovieRemoteDataSourceImpl @Inject constructor( private val service: MovieApiService, ) : MovieRemoteDataSource { override suspend fun getMovie(movieId: Int): Result<MovieDto> = service.getMovie(movieId) }
0
Kotlin
4
36
d6e8a01a41d1f61fc1b233cb32e17505c0707a20
543
Modular-Clean-Arch-Movie-App
MIT License
src/main/java/dev/rishon/sync/jedis/packet/ChatPacket.kt
Rishon
796,842,972
false
{"Kotlin": 89825}
package dev.rishon.sync.jedis.packet import dev.rishon.sync.utils.LoggerUtil import net.kyori.adventure.text.serializer.json.JSONComponentSerializer import org.bukkit.Bukkit class ChatPacket(private val playerName: String, private val json: String) : IPacket { override fun onReceive() { LoggerUtil.debug("Received chat packet for $playerName") val player = Bukkit.getPlayer(playerName) if (player != null) return // Don't send the message to the same server as player val server = Bukkit.getServer() val component = JSONComponentSerializer.json().deserialize(json); server.sendMessage(component) } }
0
Kotlin
0
1
8093eadafcbd4e5a3130b0cdae93329b502346a6
660
sync
MIT License
wear/src/main/java/audio/omgsoundboard/presentation/ui/sounds/SoundsScreen.kt
OMGSoundboard
72,438,238
false
{"Kotlin": 219247, "HTML": 30981, "Dockerfile": 709}
package audio.omgsoundboard.presentation.ui.sounds import android.widget.Toast import androidx.compose.foundation.gestures.scrollBy import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.input.rotary.onRotaryScrollEvent import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.wear.compose.foundation.lazy.ScalingLazyColumn import androidx.wear.compose.foundation.lazy.items import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState import androidx.wear.compose.material.Button import androidx.wear.compose.material.Card import androidx.wear.compose.material.Icon import androidx.wear.compose.material.PositionIndicator import androidx.wear.compose.material.Scaffold import androidx.wear.compose.material.Text import audio.omgsoundboard.core.R import audio.omgsoundboard.core.domain.models.PlayableSound import kotlinx.coroutines.launch @Composable fun SoundsScreen( categoryId: Int, viewModel: SoundsScreenViewModel = hiltViewModel(), ) { LaunchedEffect(Unit) { viewModel.onEvent(SoundsEvents.OnSetCategoryId(categoryId)) } val context = LocalContext.current val scalingLazyListState = rememberScalingLazyListState() val state by viewModel.state.collectAsState() val coroutineScope = rememberCoroutineScope() Scaffold( positionIndicator = { PositionIndicator(scalingLazyListState = scalingLazyListState) }, ){ ScalingLazyColumn( modifier = Modifier .fillMaxSize() .onRotaryScrollEvent { coroutineScope.launch { scalingLazyListState.scrollBy(it.verticalScrollPixels) } true }, verticalArrangement = Arrangement.Top, state = scalingLazyListState ) { item { if (state.sounds.isEmpty()) { Text(text = stringResource(id = R.string.no_sounds_here_yet)) } } items(state.sounds, key = { it.id }) { sound -> SoundItem( item = sound, onPlay = { viewModel.onEvent(SoundsEvents.OnPlaySound(sound.id, sound.resId, sound.uri)) }, onFav = { Toast.makeText( context, context.resources.getString(if (!sound.isFav) R.string.added_to_fav else R.string.remove_from_fav), Toast.LENGTH_SHORT ).show() viewModel.onEvent(SoundsEvents.OnToggleFav(sound.id)) } ) } } } } @Composable fun SoundItem( item: PlayableSound, onPlay: () -> Unit, onFav: () -> Unit, ) { Card(modifier = Modifier.padding(vertical = 2.dp), onClick = onPlay) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text( text = item.title, textAlign = TextAlign.Start ) Button(onClick = onFav) { Icon( painter = painterResource( id = if (item.isFav) { R.drawable.fav } else { R.drawable.fav_outlined } ), contentDescription = null, ) } } } }
3
Kotlin
4
21
d7b1a5f24db1135d344676eecad8a46d9470bcac
4,439
android-app
Apache License 2.0
src/test/java/com/kotlinspirit/ExactCharRuleTest.kt
tiksem
494,746,133
false
{"Kotlin": 465350, "HTML": 2017}
package com.kotlinspirit import com.kotlinspirit.core.ParseCode import com.kotlinspirit.core.Rules.char import org.junit.Assert import org.junit.Test class ExactCharRuleTest { @Test fun test1() { val r = char('a').compile() Assert.assertEquals(r.tryParse("abcdef"), 1) Assert.assertEquals(r.parse("").errorCode, ParseCode.EOF) Assert.assertEquals(r.parse("bcdaaef").errorCode, ParseCode.CHAR_PREDICATE_FAILED) } @Test fun noTest() { val r = (!char('a')).compile() Assert.assertEquals(r.tryParse("abcdef"), null) Assert.assertEquals(r.tryParse(""), 0) Assert.assertEquals(r.tryParse("bcdaaef"), 1) } @Test fun diff() { val r = (char - 'a').compile() Assert.assertEquals(r.tryParse("abcdef"), null) Assert.assertEquals(r.tryParse(""), null) Assert.assertEquals(r.tryParse("bcdaaef"), 1) } @Test fun diff2() { val r = (char('a'..'z') - char('e'..'g')).compile() Assert.assertEquals(r.tryParse("abcdef"), 1) Assert.assertEquals(r.tryParse("edfdfdf33"), null) Assert.assertEquals(r.tryParse(""), null) } @Test fun diff3() { val r = (char('a'..'z') - char('e', 'z', 'g')).compile() Assert.assertEquals(r.tryParse("kbcdef"), 1) Assert.assertEquals(r.tryParse("edfdfdf33"), null) Assert.assertEquals(r.tryParse("zdfdfdf33"), null) Assert.assertEquals(r.tryParse("gdfdfdf33"), null) Assert.assertEquals(r.tryParse(""), null) } }
0
Kotlin
0
2
783fdb0655608e8260c0e0a368a99af468f08d29
1,561
KotlinSpirit
MIT License
vk-api/src/main/kotlin/name/alatushkin/api/vk/generated/ads/RejectReason.kt
alatushkin
156,866,851
false
null
package name.alatushkin.api.vk.generated.ads open class RejectReason( val comment: String? = null, val rules: Array<Rules>? = null )
2
Kotlin
3
10
123bd61b24be70f9bbf044328b98a3901523cb1b
142
kotlin-vk-api
MIT License
app/src/main/java/com/example/antheia_plant_manager/nav_routes/AddPlant.kt
MegaBreadbox
814,871,131
false
{"Kotlin": 148263}
package com.example.antheia_plant_manager.nav_routes import android.view.animation.Animation import androidx.compose.material3.windowsizeclass.WindowWidthSizeClass import androidx.compose.runtime.Composable import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable import com.example.antheia_plant_manager.nav_routes.util.AnimationConstants import com.example.antheia_plant_manager.screens.add_plant.AddPlantScreen import kotlinx.serialization.Serializable @Serializable object AddPlant fun NavGraphBuilder.addPlant( windowSize: WindowWidthSizeClass, navigateBack: () -> Unit ) { composable<AddPlant>( enterTransition = { AnimationConstants.fadeInAnimation() }, exitTransition = { AnimationConstants.fadeOutAnimation() } ) { AddPlantScreen( windowSize = windowSize, navigateBack = navigateBack ) } }
0
Kotlin
0
0
c018dd3c2f8cef91c2ab257fcae0d3ca1755ebce
949
Antheia
Apache License 2.0
live/src/main/java/com/pbj/sdk/domain/authentication/UserRepository.kt
pbj-apps
360,147,915
false
null
package com.pbj.sdk.domain.authentication import com.pbj.sdk.concreteImplementation.authentication.model.JsonRegisterRequest import com.pbj.sdk.domain.Result import com.pbj.sdk.domain.authentication.model.User import com.pbj.sdk.domain.vod.model.ProfileImage import java.io.File internal interface UserRepository { suspend fun login(email: String, password: String): Result<User> suspend fun register(registerRequest: JsonRegisterRequest): Result<User> suspend fun getUser(): Result<User> suspend fun getLocallySavedUser(): Result<User> suspend fun updateUser(firstname: String, lastname: String): Result<Any> suspend fun uploadProfilePicture(image: File): Result<ProfileImage> suspend fun changePassword(currentPassword: String, newPassword: String): Result<Any> suspend fun logout(): Result<Any> suspend fun saveUser(user: User): Result<Any> suspend fun getUserToken(): Result<String> suspend fun saveToken(token: String?): Result<Any> suspend fun removeToken(): Result<Any> suspend fun isLoggedInAsGuest(): Result<Boolean> suspend fun saveIsLoggedInAsGuest(isGuest: Boolean): Result<Any> suspend fun updateDeviceRegistrationToken(token: String): Result<Any> }
1
Kotlin
0
0
01dbcb1919045fd0249dd6c008edd6a5a218d2be
1,239
Live-android-sdk
MIT License
app/src/main/java/com/aldikitta/jetmvvmmovie/navigation/DrawerNavItems.kt
Aldikitta
504,072,554
false
{"Kotlin": 104945}
package com.aldikitta.jetmvvmmovie.navigation import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.* import com.aldikitta.jetmvvmmovie.data.model.NavItem val DrawerNavItems = listOf( NavItem( label = DrawerItem.Profile.title, icon = Icons.Filled.Person, route = DrawerItem.Profile.route ), NavItem( label = DrawerItem.Preferences.title, icon = Icons.Filled.Assistant, route = DrawerItem.Preferences.route ),NavItem( label = DrawerItem.Settings.title, icon = Icons.Filled.Settings, route = DrawerItem.Settings.route ),NavItem( label = DrawerItem.Help.title, icon = Icons.Filled.Help, route = DrawerItem.Help.route ), )
0
Kotlin
0
6
5bfdca0dda294adff4ab3fda225a5e27c2b81d8b
777
Movplay
Apache License 2.0
app/src/main/java/pw/wpam/polityper/models/Tournament.kt
kubasikora
310,674,873
false
null
package pw.wpam.polityper.models data class Team( val id: Int, val name: String, val sport: String ) { }
8
Kotlin
0
1
cc5ff40b7fbb92f0281a7cde591f4d4b5cc828aa
129
WPAM-Projekt-Aplikacja
MIT License
vanillaplacepicker/src/main/java/com/vanillaplacepicker/data/SearchAddressResponse.kt
pratikmi
178,327,466
true
{"Kotlin": 75572, "Java": 1121}
package com.vanillaplacepicker.data import com.google.gson.annotations.SerializedName import java.io.Serializable class SearchAddressResponse : Serializable { @SerializedName("html_attributions") var htmlAttributions: Array<String>? = null @SerializedName("results") var results: ArrayList<Results> = ArrayList() @SerializedName("status") var status: String = "" @SerializedName("error_message") var errorMessage: String = "" inner class Results : Serializable { @SerializedName("formatted_address") var formattedAddress: String? = null @SerializedName("geometry") var geometry: Geometry? = null @SerializedName("icon") var icon: String? = null @SerializedName("id") var id: String? = null @SerializedName("name") var name: String? = null @SerializedName("opening_hours") var openingHours: OpeningHours? = null @SerializedName("photos") var photos: ArrayList<Photos> = ArrayList() @SerializedName("place_id") var placeId: String? = null @SerializedName("scope") var scope: String? = null @SerializedName("alt_ids") var alternativeIds: ArrayList<AlternativeIds> = ArrayList() @SerializedName("rating") var rating: Double? = null @SerializedName("reference") var reference: String? = null @SerializedName("types") var types: Array<String>? = null @SerializedName("user_ratings_total") var userRatingsTotal: String? = null } inner class Geometry : Serializable { @SerializedName("location") var location: Location? = null @SerializedName("viewport") var viewport: Viewport? = null } inner class Location : Serializable { @SerializedName("lat") var lat: Double? = null @SerializedName("lng") var lng: Double? = null } inner class Viewport : Serializable { @SerializedName("northeast") var northEast: Location? = null @SerializedName("southwest") var southWest: Location? = null } inner class OpeningHours : Serializable { @SerializedName("open_now") var openNow: Boolean? = null } inner class Photos : Serializable { @SerializedName("height") var height: Int? = null @SerializedName("html_attributions") var htmlAttributions: Array<String>? = null @SerializedName("photo_reference") var photoReference: String? = null @SerializedName("width") var width: Int? = null } inner class AlternativeIds : Serializable { @SerializedName("place_id") var placeId: String? = null @SerializedName("scope") var scope: String? = null } }
0
Kotlin
0
1
a649e454989fe3cb4de23a0485a61ed1612b8bbd
2,871
VanillaPlacePicker
MIT License
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/data/domains/history/HistoryRepository.kt
Waboodoo
34,525,124
false
{"Kotlin": 1970466, "HTML": 200869, "CSS": 2316, "Python": 1548}
package ch.rmy.android.http_shortcuts.data.domains.history import ch.rmy.android.framework.data.BaseRepository import ch.rmy.android.framework.data.RealmFactory import ch.rmy.android.framework.utils.UUIDUtils.newUUID import ch.rmy.android.http_shortcuts.data.domains.getHistoryEvents import ch.rmy.android.http_shortcuts.data.domains.getHistoryEventsNewerThan import ch.rmy.android.http_shortcuts.data.domains.getHistoryEventsOlderThan import ch.rmy.android.http_shortcuts.data.enums.HistoryEventType import ch.rmy.android.http_shortcuts.data.models.HistoryEvent import kotlinx.coroutines.flow.Flow import javax.inject.Inject import kotlin.time.Duration class HistoryRepository @Inject constructor( realmFactory: RealmFactory, ) : BaseRepository(realmFactory) { fun getObservableHistory(maxAge: Duration): Flow<List<HistoryEvent>> = observeQuery { getHistoryEventsNewerThan(maxAge) } suspend fun deleteHistory() { commitTransaction { getHistoryEvents().deleteAll() } } suspend fun deleteOldEvents(maxAge: Duration) { commitTransaction { getHistoryEventsOlderThan(maxAge).deleteAll() } } suspend fun storeHistoryEvent(type: HistoryEventType, data: Any?) { commitTransaction { copy( HistoryEvent(id = newUUID(), eventType = type, eventData = data) ) } } }
26
Kotlin
105
999
34ec1652d431d581c3c275335eb4dbcf24ced9f5
1,432
HTTP-Shortcuts
MIT License
sange-datasource/src/main/java/zlc/season/sange/datasource/DataSource.kt
ssseasonnn
189,573,304
false
{"Kotlin": 34563}
package zlc.season.sange.datasource import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.MainScope import kotlinx.coroutines.launch import java.util.concurrent.atomic.AtomicBoolean abstract class DataSource<T : Any>(coroutineScope: CoroutineScope = MainScope()) : BaseDataSource<T>(coroutineScope) { private val fetchStateHolder = FetchStateHolder() private val invalid = AtomicBoolean(false) private var retryFunc: () -> Unit = {} /** * Retry fetching. */ fun retry() { ensureMainThread { retryFunc() } } /** * Invalidate the current data source. */ fun invalidate(clear: Boolean = true) { ensureMainThread { if (invalid.compareAndSet(false, true)) { dispatchLoadInitial(clear) } } } private fun dispatchLoadInitial(clear: Boolean) { if (clear) { clearAll(delay = true) } launch { val result = loadInitial() onLoadResult(result) invalid.compareAndSet(true, false) if (result == null) { retryFunc = { dispatchLoadInitial(clear) } } onLoadInitialFinished(getFetchState()) } } protected fun dispatchLoadAround(position: Int) { if (isInvalid()) return if (shouldLoadAfter(position)) { if (fetchStateHolder.isNotReady()) { return } scheduleLoadAfter() } } private fun scheduleLoadAfter() { changeFetchState(FetchState.Fetching) launch { val result = loadAfter() if (isInvalid()) return@launch onLoadResult(result) if (result == null) { retryFunc = { scheduleLoadAfter() } } onLoadAfterFinished(getFetchState()) } } private fun onLoadResult(data: List<T>?) { if (data != null) { if (data.isEmpty()) { changeFetchState(FetchState.DoneFetching) } else { addItems(data, delay = true) notifySubmitList() changeFetchState(FetchState.ReadyToFetch) } } else { changeFetchState(FetchState.FetchingError) } } private fun isInvalid(): Boolean { return invalid.get() } private fun changeFetchState(newState: FetchState) { fetchStateHolder.setState(newState) onFetchStateChanged(newState) } open suspend fun loadInitial(): List<T>? = emptyList() open suspend fun loadAfter(): List<T>? = emptyList() open fun shouldLoadAfter(position: Int): Boolean { return position == totalSize() - 1 } fun getFetchState() = fetchStateHolder.getState() /** * Call on state changed. * @param newState May be these values: * [FetchState.Fetching], [FetchState.FetchingError], * [FetchState.DoneFetching], [FetchState.ReadyToFetch] */ protected open fun onFetchStateChanged(newState: FetchState) {} /** * Call on load initial finish */ protected open fun onLoadInitialFinished(currentState: FetchState) {} /** * Call on load after finish */ protected open fun onLoadAfterFinished(currentState: FetchState) {} }
0
Kotlin
4
37
33d2fc5943ab239ab89903b52e7f7684f75928b1
3,382
Sange
Apache License 2.0
feature/detail/src/main/java/jp/co/yumemi/droidtraining/feature/detail/DetailScreen.kt
matsumo0922
842,734,172
false
{"Kotlin": 77361}
package jp.co.yumemi.droidtraining.feature.detail import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import org.koin.androidx.compose.koinViewModel @Suppress("UnusedParameter", "EmptyFunctionBlock") @Composable internal fun DetailScreen( modifier: Modifier = Modifier, viewModel: DetailViewModel = koinViewModel(), ) { }
15
Kotlin
0
0
fdf39ffbd77e97236780e3661bfd257f8e203740
359
android-training-template
Apache License 2.0
data/RF01428/rnartist.kts
fjossinet
449,239,232
false
{"Kotlin": 8214424}
import io.github.fjossinet.rnartist.core.* rnartist { ss { rfam { id = "RF01428" name = "consensus" use alignment numbering } } theme { details { value = 3 } color { location { 2 to 4 98 to 100 } value = "#c0c2f3" } color { location { 5 to 97 } value = "#c8bf62" } color { location { 1 to 1 } value = "#ead2c5" } color { location { 101 to 101 } value = "#30f704" } } }
0
Kotlin
0
0
3016050675602d506a0e308f07d071abf1524b67
782
Rfam-for-RNArtist
MIT License
agent/src/test/kotlin/org/nessus/didcomm/test/model/dcv2/Fixtures.kt
tdiesler
578,916,709
false
null
/*- * #%L * Nessus DIDComm :: Core * %% * Copyright (C) 2022 Nessus * %% * 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. * #L% */ package org.nessus.didcomm.test.model.dcv2 import org.nessus.didcomm.util.trimJson class OutOfBand { companion object { const val ALICE_DID = "did:example:alice" const val FABER_DID = "did:example:faber" val FABER_OUT_OF_BAND_INVITATION = """ { "type": "https://didcomm.org/out-of-band/2.0/invitation", "id": "1234567890", "from": "did:example:faber", "body": { "goal_code": "issue-vc", "goal": "To issue a Faber College Graduate credential", "accept": [ "didcomm/v2", "didcomm/aip2;env=rfc587" ] }, "attachments": [ { "id": "request-0", "media_type": "application/json", "data": { "json": {"protocol message": "content"} } } ] } """.trimJson() val FABER_OUT_OF_BAND_INVITATION_WRAPPED = """ { "type": "https://didcomm.org/out-of-band/2.0/invitation", "id": "1234567890", "from": "did:example:faber", "body": { "goal_code": "issue-vc", "goal": "To issue a Faber College Graduate credential", "accept": [ "didcomm/v2", "didcomm/aip2;env=rfc587" ] }, "attachments": [ { "id": "0fa20500-2677-4e72-a8b3-dfff26ae2044", "media_type": "application/json", "data": { "json": { "invitation": { "@type": "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/out-of-band/1.1/invitation", "@id": "0fa20500-2677-4e72-a8b3-dfff26ae2044", "label": "Aries Cloud Agent", "services": [ { "id": "#inline", "type": "did-communication", "recipientKeys": [ "did:key:<KEY>" ], "serviceEndpoint": "http://localhost:8030" } ], "handshake_protocols": [ "did:sov:BzCbsNYhMrjHiqZDTUASHg;spec/didexchange/1.0" ] }, "state": "initial", "oob_id": "f2f24452-f43c-4a08-bf5c-5e6734d3f0db", "invi_msg_id": "0fa20500-2677-4e72-a8b3-dfff26ae2044" } } } ] } """.trimJson() val ALICE_OUT_OF_BAND_INVITATION = """ { "type": "https://didcomm.org/out-of-band/2.0/invitation", "id": "69212a3a-d068-4f9d-a2dd-4741bca89af3", "from": "did:example:alice", "body": { "goal_code": "", "goal": "" }, "attachments": [ { "id": "request-0", "media_type": "application/json", "data": { "base64": "qwerty" } } ] } """.trimJson() } }
11
Kotlin
0
3
80841110386491e3ff206330f45e16c28e3637c5
4,047
nessus-didcomm
Apache License 2.0
core/src/main/kotlin/com/snapwise/security/bff/authorization/UserSessionInfo.kt
Snapwise
589,004,796
false
null
/* * * * Copyright 2022 the original author or authors. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * https://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * */ package com.snapwise.security.bff.authorization import com.fasterxml.jackson.annotation.JsonProperty import java.io.Serializable import java.util.* /** * A representation of a bff user session info linked to the client's session id. * * Structure outline: https://datatracker.ietf.org/doc/html/draft-bertocci-oauth2-tmi-bff-01#section-5.2 * * @since 0.0.1 */ data class UserSessionInfo( /** * @return the identifier for the user's unique identifier. */ @JsonProperty("sub") val sub: String, /** * @return the user's given name. */ @JsonProperty("given_name") val givenName: String, /** * @return the user's family name. */ @JsonProperty("family_name") val familyName: String, /** * @return the user's email. */ @JsonProperty("email_verified") val emailVerified: String, /** * @return the user's preferred username. */ @JsonProperty("preferred_username") val preferredUsername: String, /** * OAuth2 issuer identifier. * * @return the authorization issuer identifier. */ @JsonProperty("iss") val iss: String, /** * Timestamp when the user session was created. * * @return created timestamp. */ @JsonProperty("auth_time") val authTime: Long, /** * Timestamp when the user session will expire. * * @return expiring timestamp. */ @JsonProperty("exp") val exp: Long, ): Serializable { /** * A builder for [UserSessionInfo]. */ class Builder : Serializable { private var sub: String? = null private var givenName: String? = null private var familyName: String? = null private var emailVerified: String? = null private var preferredUsername: String? = null private var iss: String? = null private var authTime: Long? = null private var exp: Long? = null /** * Sets the session info user identifier. * * @param sub the identifier for the session's user. * @return the [Builder] */ fun sub(sub: String): Builder { this.sub = sub return this } /** * Sets the session info user given name. * * @param givenName user's given name. * @return the [Builder] */ fun givenName(givenName: String): Builder { this.givenName = givenName return this } /** * Sets the session info user family name. * * @param givenName user's family name. * @return the [Builder] */ fun familyName(familyName: String): Builder { this.familyName = familyName return this } /** * Sets the session info user email. * * @param emailVerified user's email. * @return the [Builder] */ fun emailVerified(emailVerified: String): Builder { this.emailVerified = emailVerified return this } /** * Sets the session info user preferred username. * * @param preferredUsername user's preferred username. * @return the [Builder] */ fun preferredUsername(preferredUsername: String): Builder { this.preferredUsername = preferredUsername return this } /** * Sets the session info oauth2 issuer. * * @param iss authorization issuer identifier. * @return the [Builder] */ fun iss(iss: String): Builder { this.iss = iss return this } /** * Sets the session info's session created timestamp. * * @param authTime created timestamp. * @return the [Builder] */ fun authTime(authTime: Long): Builder { this.authTime = authTime return this } /** * Sets the session info's session expiration timestamp. * * @param exp expiring timestamp. * @return the [Builder] */ fun expTime(exp: Long): Builder { this.exp = exp return this } /** * Builds a new [UserSessionInfo]. * * @return the [UserSessionInfo] */ fun build(): UserSessionInfo { return UserSessionInfo( sub = sub!!, givenName = givenName!!, familyName = familyName!!, emailVerified = emailVerified!!, preferredUsername = preferredUsername!!, iss = iss!!, authTime = authTime!!, exp = exp!! ) } } }
0
Kotlin
0
0
4e4529037c69ca3527c0796780feff6d1a40a090
5,512
spring-bff-authorization
Apache License 2.0
composeApp/src/commonMain/kotlin/com.example/composeApp/presentation/detail/DefaultDetailComponent.kt
mygomii
852,664,777
false
{"Kotlin": 29477, "Swift": 1487}
package com.example.composeApp.presentation.detail import com.arkivanov.decompose.ComponentContext import com.arkivanov.decompose.value.MutableValue import com.arkivanov.decompose.value.Value import com.example.composeApp.models.Post class DefaultDetailComponent( componentContext: ComponentContext, post: Post, private val onFinished: () -> Unit, ) : DetailComponent, ComponentContext by componentContext { override val model: Value<Post> = MutableValue(post) override fun onBackPressed() = onFinished() }
0
Kotlin
0
0
8aef9c957fdffe01b32563c6d5aa763509753e83
531
decompose-sample
Apache License 2.0
src/commonMain/kotlin/com/jeffpdavidson/kotwords/formats/unidecode/x5b.kt
jpd236
143,651,464
false
{"Kotlin": 4427197, "HTML": 41941, "Rouge": 3731, "Perl": 1705, "Shell": 744, "JavaScript": 618}
package com.jeffpdavidson.kotwords.formats.unidecode internal val x5b = arrayOf( // 0x5b00: 嬀 => Gui "\u0047\u0075\u0069\u0020", // 0x5b01: 嬁 => Deng "\u0044\u0065\u006e\u0067\u0020", // 0x5b02: 嬂 => Zhi "\u005a\u0068\u0069\u0020", // 0x5b03: 嬃 => Xu "\u0058\u0075\u0020", // 0x5b04: 嬄 => Yi "\u0059\u0069\u0020", // 0x5b05: 嬅 => Hua "\u0048\u0075\u0061\u0020", // 0x5b06: 嬆 => Xi "\u0058\u0069\u0020", // 0x5b07: 嬇 => Hui "\u0048\u0075\u0069\u0020", // 0x5b08: 嬈 => Rao "\u0052\u0061\u006f\u0020", // 0x5b09: 嬉 => Xi "\u0058\u0069\u0020", // 0x5b0a: 嬊 => Yan "\u0059\u0061\u006e\u0020", // 0x5b0b: 嬋 => Chan "\u0043\u0068\u0061\u006e\u0020", // 0x5b0c: 嬌 => Jiao "\u004a\u0069\u0061\u006f\u0020", // 0x5b0d: 嬍 => Mei "\u004d\u0065\u0069\u0020", // 0x5b0e: 嬎 => Fan "\u0046\u0061\u006e\u0020", // 0x5b0f: 嬏 => Fan "\u0046\u0061\u006e\u0020", // 0x5b10: 嬐 => Xian "\u0058\u0069\u0061\u006e\u0020", // 0x5b11: 嬑 => Yi "\u0059\u0069\u0020", // 0x5b12: 嬒 => Wei "\u0057\u0065\u0069\u0020", // 0x5b13: 嬓 => Jiao "\u004a\u0069\u0061\u006f\u0020", // 0x5b14: 嬔 => Fu "\u0046\u0075\u0020", // 0x5b15: 嬕 => Shi "\u0053\u0068\u0069\u0020", // 0x5b16: 嬖 => Bi "\u0042\u0069\u0020", // 0x5b17: 嬗 => Shan "\u0053\u0068\u0061\u006e\u0020", // 0x5b18: 嬘 => Sui "\u0053\u0075\u0069\u0020", // 0x5b19: 嬙 => Qiang "\u0051\u0069\u0061\u006e\u0067\u0020", // 0x5b1a: 嬚 => Lian "\u004c\u0069\u0061\u006e\u0020", // 0x5b1b: 嬛 => Huan "\u0048\u0075\u0061\u006e\u0020", // 0x5b1c: 嬜 => Xin "\u0058\u0069\u006e\u0020", // 0x5b1d: 嬝 => Niao "\u004e\u0069\u0061\u006f\u0020", // 0x5b1e: 嬞 => Dong "\u0044\u006f\u006e\u0067\u0020", // 0x5b1f: 嬟 => Yi "\u0059\u0069\u0020", // 0x5b20: 嬠 => Can "\u0043\u0061\u006e\u0020", // 0x5b21: 嬡 => Ai "\u0041\u0069\u0020", // 0x5b22: 嬢 => Niang "\u004e\u0069\u0061\u006e\u0067\u0020", // 0x5b23: 嬣 => Neng "\u004e\u0065\u006e\u0067\u0020", // 0x5b24: 嬤 => Ma "\u004d\u0061\u0020", // 0x5b25: 嬥 => Tiao "\u0054\u0069\u0061\u006f\u0020", // 0x5b26: 嬦 => Chou "\u0043\u0068\u006f\u0075\u0020", // 0x5b27: 嬧 => Jin "\u004a\u0069\u006e\u0020", // 0x5b28: 嬨 => Ci "\u0043\u0069\u0020", // 0x5b29: 嬩 => Yu "\u0059\u0075\u0020", // 0x5b2a: 嬪 => Pin "\u0050\u0069\u006e\u0020", // 0x5b2b: 嬫 => Yong "\u0059\u006f\u006e\u0067\u0020", // 0x5b2c: 嬬 => Xu "\u0058\u0075\u0020", // 0x5b2d: 嬭 => Nai "\u004e\u0061\u0069\u0020", // 0x5b2e: 嬮 => Yan "\u0059\u0061\u006e\u0020", // 0x5b2f: 嬯 => Tai "\u0054\u0061\u0069\u0020", // 0x5b30: 嬰 => Ying "\u0059\u0069\u006e\u0067\u0020", // 0x5b31: 嬱 => Can "\u0043\u0061\u006e\u0020", // 0x5b32: 嬲 => Niao "\u004e\u0069\u0061\u006f\u0020", // 0x5b33: 嬳 => Wo "\u0057\u006f\u0020", // 0x5b34: 嬴 => Ying "\u0059\u0069\u006e\u0067\u0020", // 0x5b35: 嬵 => Mian "\u004d\u0069\u0061\u006e\u0020", // 0x5b36: 嬶 => Kaka "\u004b\u0061\u006b\u0061\u0020", // 0x5b37: 嬷 => Ma "\u004d\u0061\u0020", // 0x5b38: 嬸 => Shen "\u0053\u0068\u0065\u006e\u0020", // 0x5b39: 嬹 => Xing "\u0058\u0069\u006e\u0067\u0020", // 0x5b3a: 嬺 => Ni "\u004e\u0069\u0020", // 0x5b3b: 嬻 => Du "\u0044\u0075\u0020", // 0x5b3c: 嬼 => Liu "\u004c\u0069\u0075\u0020", // 0x5b3d: 嬽 => Yuan "\u0059\u0075\u0061\u006e\u0020", // 0x5b3e: 嬾 => Lan "\u004c\u0061\u006e\u0020", // 0x5b3f: 嬿 => Yan "\u0059\u0061\u006e\u0020", // 0x5b40: 孀 => Shuang "\u0053\u0068\u0075\u0061\u006e\u0067\u0020", // 0x5b41: 孁 => Ling "\u004c\u0069\u006e\u0067\u0020", // 0x5b42: 孂 => Jiao "\u004a\u0069\u0061\u006f\u0020", // 0x5b43: 孃 => Niang "\u004e\u0069\u0061\u006e\u0067\u0020", // 0x5b44: 孄 => Lan "\u004c\u0061\u006e\u0020", // 0x5b45: 孅 => Xian "\u0058\u0069\u0061\u006e\u0020", // 0x5b46: 孆 => Ying "\u0059\u0069\u006e\u0067\u0020", // 0x5b47: 孇 => Shuang "\u0053\u0068\u0075\u0061\u006e\u0067\u0020", // 0x5b48: 孈 => Shuai "\u0053\u0068\u0075\u0061\u0069\u0020", // 0x5b49: 孉 => Quan "\u0051\u0075\u0061\u006e\u0020", // 0x5b4a: 孊 => Mi "\u004d\u0069\u0020", // 0x5b4b: 孋 => Li "\u004c\u0069\u0020", // 0x5b4c: 孌 => Luan "\u004c\u0075\u0061\u006e\u0020", // 0x5b4d: 孍 => Yan "\u0059\u0061\u006e\u0020", // 0x5b4e: 孎 => Zhu "\u005a\u0068\u0075\u0020", // 0x5b4f: 孏 => Lan "\u004c\u0061\u006e\u0020", // 0x5b50: 子 => Zi "\u005a\u0069\u0020", // 0x5b51: 孑 => Jie "\u004a\u0069\u0065\u0020", // 0x5b52: 孒 => Jue "\u004a\u0075\u0065\u0020", // 0x5b53: 孓 => Jue "\u004a\u0075\u0065\u0020", // 0x5b54: 孔 => Kong "\u004b\u006f\u006e\u0067\u0020", // 0x5b55: 孕 => Yun "\u0059\u0075\u006e\u0020", // 0x5b56: 孖 => Zi "\u005a\u0069\u0020", // 0x5b57: 字 => Zi "\u005a\u0069\u0020", // 0x5b58: 存 => Cun "\u0043\u0075\u006e\u0020", // 0x5b59: 孙 => Sun "\u0053\u0075\u006e\u0020", // 0x5b5a: 孚 => Fu "\u0046\u0075\u0020", // 0x5b5b: 孛 => Bei "\u0042\u0065\u0069\u0020", // 0x5b5c: 孜 => Zi "\u005a\u0069\u0020", // 0x5b5d: 孝 => Xiao "\u0058\u0069\u0061\u006f\u0020", // 0x5b5e: 孞 => Xin "\u0058\u0069\u006e\u0020", // 0x5b5f: 孟 => Meng "\u004d\u0065\u006e\u0067\u0020", // 0x5b60: 孠 => Si "\u0053\u0069\u0020", // 0x5b61: 孡 => Tai "\u0054\u0061\u0069\u0020", // 0x5b62: 孢 => Bao "\u0042\u0061\u006f\u0020", // 0x5b63: 季 => Ji "\u004a\u0069\u0020", // 0x5b64: 孤 => Gu "\u0047\u0075\u0020", // 0x5b65: 孥 => Nu "\u004e\u0075\u0020", // 0x5b66: 学 => Xue "\u0058\u0075\u0065\u0020", // 0x5b67: 孧 => [?] "\u005b\u003f\u005d\u0020", // 0x5b68: 孨 => Zhuan "\u005a\u0068\u0075\u0061\u006e\u0020", // 0x5b69: 孩 => Hai "\u0048\u0061\u0069\u0020", // 0x5b6a: 孪 => Luan "\u004c\u0075\u0061\u006e\u0020", // 0x5b6b: 孫 => Sun "\u0053\u0075\u006e\u0020", // 0x5b6c: 孬 => Huai "\u0048\u0075\u0061\u0069\u0020", // 0x5b6d: 孭 => Mie "\u004d\u0069\u0065\u0020", // 0x5b6e: 孮 => Cong "\u0043\u006f\u006e\u0067\u0020", // 0x5b6f: 孯 => Qian "\u0051\u0069\u0061\u006e\u0020", // 0x5b70: 孰 => Shu "\u0053\u0068\u0075\u0020", // 0x5b71: 孱 => Chan "\u0043\u0068\u0061\u006e\u0020", // 0x5b72: 孲 => Ya "\u0059\u0061\u0020", // 0x5b73: 孳 => Zi "\u005a\u0069\u0020", // 0x5b74: 孴 => Ni "\u004e\u0069\u0020", // 0x5b75: 孵 => Fu "\u0046\u0075\u0020", // 0x5b76: 孶 => Zi "\u005a\u0069\u0020", // 0x5b77: 孷 => Li "\u004c\u0069\u0020", // 0x5b78: 學 => Xue "\u0058\u0075\u0065\u0020", // 0x5b79: 孹 => Bo "\u0042\u006f\u0020", // 0x5b7a: 孺 => Ru "\u0052\u0075\u0020", // 0x5b7b: 孻 => Lai "\u004c\u0061\u0069\u0020", // 0x5b7c: 孼 => Nie "\u004e\u0069\u0065\u0020", // 0x5b7d: 孽 => Nie "\u004e\u0069\u0065\u0020", // 0x5b7e: 孾 => Ying "\u0059\u0069\u006e\u0067\u0020", // 0x5b7f: 孿 => Luan "\u004c\u0075\u0061\u006e\u0020", // 0x5b80: 宀 => Mian "\u004d\u0069\u0061\u006e\u0020", // 0x5b81: 宁 => Zhu "\u005a\u0068\u0075\u0020", // 0x5b82: 宂 => Rong "\u0052\u006f\u006e\u0067\u0020", // 0x5b83: 它 => Ta "\u0054\u0061\u0020", // 0x5b84: 宄 => Gui "\u0047\u0075\u0069\u0020", // 0x5b85: 宅 => Zhai "\u005a\u0068\u0061\u0069\u0020", // 0x5b86: 宆 => Qiong "\u0051\u0069\u006f\u006e\u0067\u0020", // 0x5b87: 宇 => Yu "\u0059\u0075\u0020", // 0x5b88: 守 => Shou "\u0053\u0068\u006f\u0075\u0020", // 0x5b89: 安 => An "\u0041\u006e\u0020", // 0x5b8a: 宊 => Tu "\u0054\u0075\u0020", // 0x5b8b: 宋 => Song "\u0053\u006f\u006e\u0067\u0020", // 0x5b8c: 完 => Wan "\u0057\u0061\u006e\u0020", // 0x5b8d: 宍 => Rou "\u0052\u006f\u0075\u0020", // 0x5b8e: 宎 => Yao "\u0059\u0061\u006f\u0020", // 0x5b8f: 宏 => Hong "\u0048\u006f\u006e\u0067\u0020", // 0x5b90: 宐 => Yi "\u0059\u0069\u0020", // 0x5b91: 宑 => Jing "\u004a\u0069\u006e\u0067\u0020", // 0x5b92: 宒 => Zhun "\u005a\u0068\u0075\u006e\u0020", // 0x5b93: 宓 => Mi "\u004d\u0069\u0020", // 0x5b94: 宔 => Zhu "\u005a\u0068\u0075\u0020", // 0x5b95: 宕 => Dang "\u0044\u0061\u006e\u0067\u0020", // 0x5b96: 宖 => Hong "\u0048\u006f\u006e\u0067\u0020", // 0x5b97: 宗 => Zong "\u005a\u006f\u006e\u0067\u0020", // 0x5b98: 官 => Guan "\u0047\u0075\u0061\u006e\u0020", // 0x5b99: 宙 => Zhou "\u005a\u0068\u006f\u0075\u0020", // 0x5b9a: 定 => Ding "\u0044\u0069\u006e\u0067\u0020", // 0x5b9b: 宛 => Wan "\u0057\u0061\u006e\u0020", // 0x5b9c: 宜 => Yi "\u0059\u0069\u0020", // 0x5b9d: 宝 => Bao "\u0042\u0061\u006f\u0020", // 0x5b9e: 实 => Shi "\u0053\u0068\u0069\u0020", // 0x5b9f: 実 => Shi "\u0053\u0068\u0069\u0020", // 0x5ba0: 宠 => Chong "\u0043\u0068\u006f\u006e\u0067\u0020", // 0x5ba1: 审 => Shen "\u0053\u0068\u0065\u006e\u0020", // 0x5ba2: 客 => Ke "\u004b\u0065\u0020", // 0x5ba3: 宣 => Xuan "\u0058\u0075\u0061\u006e\u0020", // 0x5ba4: 室 => Shi "\u0053\u0068\u0069\u0020", // 0x5ba5: 宥 => You "\u0059\u006f\u0075\u0020", // 0x5ba6: 宦 => Huan "\u0048\u0075\u0061\u006e\u0020", // 0x5ba7: 宧 => Yi "\u0059\u0069\u0020", // 0x5ba8: 宨 => Tiao "\u0054\u0069\u0061\u006f\u0020", // 0x5ba9: 宩 => Shi "\u0053\u0068\u0069\u0020", // 0x5baa: 宪 => Xian "\u0058\u0069\u0061\u006e\u0020", // 0x5bab: 宫 => Gong "\u0047\u006f\u006e\u0067\u0020", // 0x5bac: 宬 => Cheng "\u0043\u0068\u0065\u006e\u0067\u0020", // 0x5bad: 宭 => Qun "\u0051\u0075\u006e\u0020", // 0x5bae: 宮 => Gong "\u0047\u006f\u006e\u0067\u0020", // 0x5baf: 宯 => Xiao "\u0058\u0069\u0061\u006f\u0020", // 0x5bb0: 宰 => Zai "\u005a\u0061\u0069\u0020", // 0x5bb1: 宱 => Zha "\u005a\u0068\u0061\u0020", // 0x5bb2: 宲 => Bao "\u0042\u0061\u006f\u0020", // 0x5bb3: 害 => Hai "\u0048\u0061\u0069\u0020", // 0x5bb4: 宴 => Yan "\u0059\u0061\u006e\u0020", // 0x5bb5: 宵 => Xiao "\u0058\u0069\u0061\u006f\u0020", // 0x5bb6: 家 => Jia "\u004a\u0069\u0061\u0020", // 0x5bb7: 宷 => Shen "\u0053\u0068\u0065\u006e\u0020", // 0x5bb8: 宸 => Chen "\u0043\u0068\u0065\u006e\u0020", // 0x5bb9: 容 => Rong "\u0052\u006f\u006e\u0067\u0020", // 0x5bba: 宺 => Huang "\u0048\u0075\u0061\u006e\u0067\u0020", // 0x5bbb: 宻 => Mi "\u004d\u0069\u0020", // 0x5bbc: 宼 => Kou "\u004b\u006f\u0075\u0020", // 0x5bbd: 宽 => Kuan "\u004b\u0075\u0061\u006e\u0020", // 0x5bbe: 宾 => Bin "\u0042\u0069\u006e\u0020", // 0x5bbf: 宿 => Su "\u0053\u0075\u0020", // 0x5bc0: 寀 => Cai "\u0043\u0061\u0069\u0020", // 0x5bc1: 寁 => Zan "\u005a\u0061\u006e\u0020", // 0x5bc2: 寂 => Ji "\u004a\u0069\u0020", // 0x5bc3: 寃 => Yuan "\u0059\u0075\u0061\u006e\u0020", // 0x5bc4: 寄 => Ji "\u004a\u0069\u0020", // 0x5bc5: 寅 => Yin "\u0059\u0069\u006e\u0020", // 0x5bc6: 密 => Mi "\u004d\u0069\u0020", // 0x5bc7: 寇 => Kou "\u004b\u006f\u0075\u0020", // 0x5bc8: 寈 => Qing "\u0051\u0069\u006e\u0067\u0020", // 0x5bc9: 寉 => Que "\u0051\u0075\u0065\u0020", // 0x5bca: 寊 => Zhen "\u005a\u0068\u0065\u006e\u0020", // 0x5bcb: 寋 => Jian "\u004a\u0069\u0061\u006e\u0020", // 0x5bcc: 富 => Fu "\u0046\u0075\u0020", // 0x5bcd: 寍 => Ning "\u004e\u0069\u006e\u0067\u0020", // 0x5bce: 寎 => Bing "\u0042\u0069\u006e\u0067\u0020", // 0x5bcf: 寏 => Huan "\u0048\u0075\u0061\u006e\u0020", // 0x5bd0: 寐 => Mei "\u004d\u0065\u0069\u0020", // 0x5bd1: 寑 => Qin "\u0051\u0069\u006e\u0020", // 0x5bd2: 寒 => Han "\u0048\u0061\u006e\u0020", // 0x5bd3: 寓 => Yu "\u0059\u0075\u0020", // 0x5bd4: 寔 => Shi "\u0053\u0068\u0069\u0020", // 0x5bd5: 寕 => Ning "\u004e\u0069\u006e\u0067\u0020", // 0x5bd6: 寖 => Qin "\u0051\u0069\u006e\u0020", // 0x5bd7: 寗 => Ning "\u004e\u0069\u006e\u0067\u0020", // 0x5bd8: 寘 => Zhi "\u005a\u0068\u0069\u0020", // 0x5bd9: 寙 => Yu "\u0059\u0075\u0020", // 0x5bda: 寚 => Bao "\u0042\u0061\u006f\u0020", // 0x5bdb: 寛 => Kuan "\u004b\u0075\u0061\u006e\u0020", // 0x5bdc: 寜 => Ning "\u004e\u0069\u006e\u0067\u0020", // 0x5bdd: 寝 => Qin "\u0051\u0069\u006e\u0020", // 0x5bde: 寞 => Mo "\u004d\u006f\u0020", // 0x5bdf: 察 => Cha "\u0043\u0068\u0061\u0020", // 0x5be0: 寠 => Ju "\u004a\u0075\u0020", // 0x5be1: 寡 => Gua "\u0047\u0075\u0061\u0020", // 0x5be2: 寢 => Qin "\u0051\u0069\u006e\u0020", // 0x5be3: 寣 => Hu "\u0048\u0075\u0020", // 0x5be4: 寤 => Wu "\u0057\u0075\u0020", // 0x5be5: 寥 => Liao "\u004c\u0069\u0061\u006f\u0020", // 0x5be6: 實 => Shi "\u0053\u0068\u0069\u0020", // 0x5be7: 寧 => Zhu "\u005a\u0068\u0075\u0020", // 0x5be8: 寨 => Zhai "\u005a\u0068\u0061\u0069\u0020", // 0x5be9: 審 => Shen "\u0053\u0068\u0065\u006e\u0020", // 0x5bea: 寪 => Wei "\u0057\u0065\u0069\u0020", // 0x5beb: 寫 => Xie "\u0058\u0069\u0065\u0020", // 0x5bec: 寬 => Kuan "\u004b\u0075\u0061\u006e\u0020", // 0x5bed: 寭 => Hui "\u0048\u0075\u0069\u0020", // 0x5bee: 寮 => Liao "\u004c\u0069\u0061\u006f\u0020", // 0x5bef: 寯 => Jun "\u004a\u0075\u006e\u0020", // 0x5bf0: 寰 => Huan "\u0048\u0075\u0061\u006e\u0020", // 0x5bf1: 寱 => Yi "\u0059\u0069\u0020", // 0x5bf2: 寲 => Yi "\u0059\u0069\u0020", // 0x5bf3: 寳 => Bao "\u0042\u0061\u006f\u0020", // 0x5bf4: 寴 => Qin "\u0051\u0069\u006e\u0020", // 0x5bf5: 寵 => Chong "\u0043\u0068\u006f\u006e\u0067\u0020", // 0x5bf6: 寶 => Bao "\u0042\u0061\u006f\u0020", // 0x5bf7: 寷 => Feng "\u0046\u0065\u006e\u0067\u0020", // 0x5bf8: 寸 => Cun "\u0043\u0075\u006e\u0020", // 0x5bf9: 对 => Dui "\u0044\u0075\u0069\u0020", // 0x5bfa: 寺 => Si "\u0053\u0069\u0020", // 0x5bfb: 寻 => Xun "\u0058\u0075\u006e\u0020", // 0x5bfc: 导 => Dao "\u0044\u0061\u006f\u0020", // 0x5bfd: 寽 => Lu "\u004c\u0075\u0020", // 0x5bfe: 対 => Dui "\u0044\u0075\u0069\u0020", // 0x5bff: 寿 => Shou "\u0053\u0068\u006f\u0075\u0020", )
8
Kotlin
6
25
e18e9cf0bad7497da15b40f6c81ba4234ec83917
15,019
kotwords
Apache License 2.0
common/sdk/recipe/crud/impl/src/commonMain/kotlin/io/chefbook/sdk/recipe/crud/impl/data/sources/remote/services/dto/crud/RecipeBody.kt
mephistolie
379,951,682
false
{"Kotlin": 1334117, "Ruby": 16819, "Swift": 352}
package io.chefbook.sdk.recipe.crud.impl.data.sources.remote.services.dto.crud import io.chefbook.libs.models.language.LanguageMapper import io.chefbook.libs.models.profile.ProfileInfo import io.chefbook.sdk.category.api.external.domain.entities.Category import io.chefbook.sdk.recipe.core.api.external.domain.entities.DecryptedRecipe import io.chefbook.sdk.recipe.core.api.external.domain.entities.DecryptedRecipeInfo import io.chefbook.sdk.recipe.core.api.external.domain.entities.EncryptedRecipe import io.chefbook.sdk.recipe.core.api.external.domain.entities.EncryptedRecipeInfo import io.chefbook.sdk.recipe.core.api.external.domain.entities.Recipe import io.chefbook.sdk.recipe.core.api.external.domain.entities.RecipeMeta import io.chefbook.sdk.recipe.core.api.internal.data.sources.common.dto.CookingItemSerializable import io.chefbook.sdk.recipe.core.api.internal.data.sources.common.dto.IngredientItemSerializable import io.chefbook.sdk.recipe.core.api.internal.data.sources.remote.services.dto.ProfileBody import io.chefbook.sdk.recipe.core.api.internal.data.sources.remote.services.dto.RatingBody import io.chefbook.sdk.recipe.core.api.internal.data.sources.remote.services.dto.RecipeTagBody import io.chefbook.sdk.recipe.core.api.internal.data.sources.remote.services.dto.VisibilitySerializable import io.chefbook.sdk.recipe.crud.impl.data.sources.remote.services.dto.pictures.PicturesBody import io.chefbook.sdk.tag.api.external.domain.entities.Tag import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable internal class RecipeBody( @SerialName("id") val id: String, @SerialName("name") val name: String, @SerialName("owner") val owner: ProfileBody, @SerialName("owned") val isOwned: Boolean = false, @SerialName("saved") val isSaved: Boolean = false, @SerialName("visibility") val visibility: VisibilitySerializable, @SerialName("encrypted") val isEncrypted: Boolean, @SerialName("language") val language: String, @SerialName("description") val description: String? = null, @SerialName("creationTimestamp") val creationTimestamp: String, @SerialName("updateTimestamp") val updateTimestamp: String, @SerialName("version") val version: Int, @SerialName("rating") val rating: RatingBody? = null, @SerialName("tags") val tags: List<String>? = null, @SerialName("categories") val categories: List<String>? = null, @SerialName("favourite") val isFavourite: Boolean = false, @SerialName("servings") val servings: Int? = null, @SerialName("time") val time: Int? = null, @SerialName("calories") val calories: Int? = null, @SerialName("macronutrients") val macronutrients: MacronutrientsBody? = null, @SerialName("ingredients") val ingredients: List<IngredientItemSerializable>, @SerialName("cooking") val cooking: List<CookingItemSerializable>, @SerialName("pictures") val pictures: PicturesBody? = null, ) internal fun RecipeBody.toEntity( categoriesMap: Map<String, Category>, tagsMap: Map<String, Tag>, ): Recipe { val meta = RecipeMeta( id = id, owner = ProfileInfo( id = owner.id, name = owner.name, avatar = owner.avatar, ), tags = tags?.mapNotNull(tagsMap::get).orEmpty(), visibility = when (visibility) { VisibilitySerializable.PUBLIC -> RecipeMeta.Visibility.PUBLIC VisibilitySerializable.LINK -> RecipeMeta.Visibility.LINK else -> RecipeMeta.Visibility.PRIVATE }, isEncryptionEnabled = isEncrypted, language = LanguageMapper.map(language), version = version, creationTimestamp = creationTimestamp, updateTimestamp = updateTimestamp, rating = RecipeMeta.Rating( index = rating?.index ?: 0F, score = rating?.score, votes = rating?.votes ?: 0, ) ) return if (ingredients.getOrNull(0)?.type == IngredientItemSerializable.TYPE_ENCRYPTED_DATA) { EncryptedRecipe( info = EncryptedRecipeInfo( meta = meta, name = name, isOwned = isOwned, isSaved = isSaved, preview = pictures?.preview, categories = categories?.mapNotNull(categoriesMap::get).orEmpty(), isFavourite = isFavourite, servings = servings, time = time, calories = calories, ), macronutrients = macronutrients?.toEntity(), description = description, ingredients = ingredients.getOrNull(0)?.text.orEmpty(), cooking = cooking.getOrNull(0)?.text.orEmpty(), cookingPictures = pictures?.cooking.orEmpty(), ) } else { DecryptedRecipe( info = DecryptedRecipeInfo( meta = meta, name = name, isOwned = isOwned, isSaved = isSaved, preview = pictures?.preview, categories = categories?.mapNotNull(categoriesMap::get).orEmpty(), isFavourite = isFavourite, servings = servings, time = time, calories = calories, ), macronutrients = macronutrients?.toEntity(), description = description, ingredients = ingredients.map(IngredientItemSerializable::toEntity), cooking = cooking.map { step -> step.toEntity(pictures?.cooking?.get(step.id)) } ) } }
0
Kotlin
0
12
ddaf82ee3142f30aee8920d226a8f07873cdcffe
5,215
chefbook-mobile
Apache License 2.0
ast-model/src/org/jetbrains/dukat/astModel/SourceSetModel.kt
Kotlin
159,510,660
false
{"Kotlin": 2656818, "WebIDL": 323681, "TypeScript": 135641, "JavaScript": 19475, "ANTLR": 11333}
package org.jetbrains.dukat.astModel data class SourceSetModel(val sourceName: List<String>, val sources: List<SourceFileModel>)
244
Kotlin
42
535
d50b9be913ce8a2332b8e97fd518f1ec1ad7f69e
129
dukat
Apache License 2.0
app/src/main/java/com/victor/newton/domain/ForecastWeather.kt
victorpm5
254,929,260
false
null
package com.victor.newton.domain class ForecastWeather() { var localitzacio: String ="" var data1: String = "" var data2: String = "" var data3: String = "" var temperatura1: String = "" var temperatur2: String = "" var temperatura3: String = "" var weatherImage1: Int = 0 var weatherImage2: Int = 0 var weatherImage3: Int = 0 var descripcio1: String = "" var descripcio2: String = "" var descripcio3: String = "" }
0
Kotlin
0
0
efaba6bd35a85256c398a72f0823a0784a7b0a3e
470
PTDMA-Newton
MIT License
app/src/main/java/com/gostsoft/giftivus/views/GiftListView.kt
GostGaming
467,555,833
false
{"Kotlin": 20474}
package com.gostsoft.giftivus.views import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import android.view.MenuItem import android.widget.LinearLayout import android.widget.TextView import androidx.activity.viewModels import androidx.constraintlayout.widget.ConstraintLayout import androidx.recyclerview.widget.LinearLayoutManager import com.gostsoft.giftivus.models.Gift import com.gostsoft.giftivus.R import com.gostsoft.giftivus.databinding.ActivityGiftListBinding import com.gostsoft.giftivus.models.db.GiftDbTable import com.gostsoft.giftivus.viewmodels.GiftListViewModel import com.gostsoft.giftivus.viewmodels.MainViewModel const val EXTRA_ID = "com.gostsoft.giftivus.USERID" class GiftListView : AppCompatActivity() { private lateinit var binding: ActivityGiftListBinding private val TAG = GiftListView::class.simpleName private val viewModel: GiftListViewModel by viewModels() val giftList = mutableListOf<Gift>() private var userId: Int? = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityGiftListBinding.inflate(layoutInflater) setContentView(binding.root) userId = intent.extras?.getInt(EXTRA_ID) ?: 0 val giftRv = binding.giftRv giftRv.setHasFixedSize(true) giftRv.layoutManager = LinearLayoutManager(this) giftRv.adapter = GiftAdapter(GiftDbTable(this).getAllGifts(), this) // updateGifts () // TODO: need to add FAB and hook it up } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_settings -> true else -> super.onOptionsItemSelected(item) // TODO: hook up to addNewGift } } fun updateGifts () { for (gift in giftList) { val giftLayout: ConstraintLayout = layoutInflater.inflate(R.layout.single_gift,null) as ConstraintLayout val giftBar = giftLayout.findViewById<LinearLayout>(R.id.gift_bar) val qty = giftBar.findViewById<TextView>(R.id.gift_qty) val name = giftBar.findViewById<TextView>(R.id.gift_name) val link = giftBar.findViewById<TextView>(R.id.gift_link) qty.text = gift.quantity.toString() name.text = gift.name link.text = gift.link } } }
0
Kotlin
0
0
19221ce5ddc3f77c1f3ea3f4b3d150f7584e943e
2,391
Giftivus
Apache License 2.0
codegen/smithy-kotlin-codegen/src/main/kotlin/software/amazon/smithy/kotlin/codegen/rendering/auth/AuthSchemeProviderGenerator.kt
awslabs
294,823,838
false
null
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package software.amazon.smithy.kotlin.codegen.rendering.auth import software.amazon.smithy.codegen.core.Symbol import software.amazon.smithy.kotlin.codegen.KotlinSettings import software.amazon.smithy.kotlin.codegen.core.* import software.amazon.smithy.kotlin.codegen.integration.AuthSchemeHandler import software.amazon.smithy.kotlin.codegen.lang.KotlinTypes import software.amazon.smithy.kotlin.codegen.model.buildSymbol import software.amazon.smithy.kotlin.codegen.model.knowledge.AuthIndex import software.amazon.smithy.kotlin.codegen.rendering.protocol.ProtocolGenerator import software.amazon.smithy.model.shapes.OperationShape /** * Generates the auth scheme resolver to use for a service (type + implementation) */ open class AuthSchemeProviderGenerator { companion object { fun getSymbol(settings: KotlinSettings): Symbol = buildSymbol { val prefix = clientName(settings.sdkId) name = "${prefix}AuthSchemeProvider" namespace = "${settings.pkg.name}.auth" definitionFile = "$name.kt" } fun getDefaultSymbol(settings: KotlinSettings): Symbol = buildSymbol { val prefix = clientName(settings.sdkId) name = "Default${prefix}AuthSchemeProvider" namespace = "${settings.pkg.name}.auth" definitionFile = "$name.kt" } } fun render(ctx: ProtocolGenerator.GenerationContext) { ctx.delegator.useSymbolWriter(getSymbol(ctx.settings)) { writer -> renderInterface(ctx, writer) } ctx.delegator.useSymbolWriter(getDefaultSymbol(ctx.settings)) { writer -> renderDefaultImpl(ctx, writer) writer.write("") } } private fun renderInterface(ctx: ProtocolGenerator.GenerationContext, writer: KotlinWriter) { val paramsSymbol = AuthSchemeParametersGenerator.getSymbol(ctx.settings) val symbol = getSymbol(ctx.settings) writer.dokka { write("${symbol.name} is responsible for resolving the authentication scheme to use for a particular operation.") write("See [#T] for the default SDK behavior of this interface.", getDefaultSymbol(ctx.settings)) } writer.write( "#L interface #T : #T<#T>", ctx.settings.api.visibility, symbol, RuntimeTypes.Auth.Identity.AuthSchemeProvider, paramsSymbol, ) } private fun renderDefaultImpl(ctx: ProtocolGenerator.GenerationContext, writer: KotlinWriter) { // FIXME - probably can't remain an object writer.withBlock( "#L object #T : #T {", "}", ctx.settings.api.visibility, getDefaultSymbol(ctx.settings), getSymbol(ctx.settings), ) { val paramsSymbol = AuthSchemeParametersGenerator.getSymbol(ctx.settings) val authIndex = AuthIndex() val operationsWithOverrides = authIndex.operationsWithOverrides(ctx) withBlock( "private val operationOverrides = mapOf<#T, List<#T>>(", ")", KotlinTypes.String, RuntimeTypes.Auth.Identity.AuthOption, ) { operationsWithOverrides.forEach { op -> val authHandlersForOperation = authIndex.effectiveAuthHandlersForOperation(ctx, op) renderAuthOptionsListOverrideForOperation(ctx, "\"${op.id.name}\"", authHandlersForOperation, writer, op) } } withBlock( "private val serviceDefaults = listOf<#T>(", ")", RuntimeTypes.Auth.Identity.AuthOption, ) { val defaultHandlers = authIndex.effectiveAuthHandlersForService(ctx) defaultHandlers.forEach { val inlineWriter: InlineKotlinWriter = { it.authSchemeProviderInstantiateAuthOptionExpr(ctx, null, this) } write("#W,", inlineWriter) } } withBlock( "override suspend fun resolveAuthScheme(params: #T): List<#T> {", "}", paramsSymbol, RuntimeTypes.Auth.Identity.AuthOption, ) { withBlock("return operationOverrides.getOrElse(params.operationName) {", "}") { write("serviceDefaults") } } // render any helper methods val allAuthSchemeHandlers = authIndex.authHandlersForService(ctx) allAuthSchemeHandlers.forEach { it.authSchemeProviderRenderAdditionalMethods(ctx, writer) } } } private fun renderAuthOptionsListOverrideForOperation( ctx: ProtocolGenerator.GenerationContext, case: String, handlers: List<AuthSchemeHandler>, writer: KotlinWriter, op: OperationShape, ) { writer.withBlock("#L to listOf(", "),", case) { handlers.forEach { val inlineWriter: InlineKotlinWriter = { it.authSchemeProviderInstantiateAuthOptionExpr(ctx, op, this) } write("#W,", inlineWriter) } } } }
33
null
18
33
ad34f2ae3a9c9619317f6df9569d649bdb8c09a8
5,423
smithy-kotlin
Apache License 2.0
voodoo/main/src/main/kotlin/voodoo/VoodooMain.kt
elytra
119,208,408
false
{"Markdown": 7, "Git Config": 1, "Gradle Kotlin DSL": 8, "INI": 4, "Shell": 15, "Text": 2, "Ignore List": 2, "Batchfile": 2, "Groovy": 1, "Java": 2, "Kotlin": 262, "Java Properties": 45, "YAML": 1, "JSON": 378, "XML": 3}
package voodoo /** * Created by nikky on 30/12/17. * @author Nikky */ import ch.qos.logback.classic.Level import ch.qos.logback.classic.Logger import com.eyeem.watchadoin.Stopwatch import com.eyeem.watchadoin.TraceEventsReport import com.eyeem.watchadoin.saveAsSvg import com.eyeem.watchadoin.asTraceEventsReport import com.eyeem.watchadoin.saveAsHtml import com.xenomachina.argparser.ArgParser import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.DEBUG_PROPERTY_NAME import kotlinx.coroutines.DEBUG_PROPERTY_VALUE_ON import kotlinx.coroutines.runBlocking import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonConfiguration import kotlinx.serialization.modules.SerializersModule import mu.KLogging import org.slf4j.LoggerFactory import voodoo.builder.Builder import voodoo.changelog.ChangelogBuilder import voodoo.data.ModloaderPattern import voodoo.data.nested.NestedPack import voodoo.script.ChangeScript import voodoo.script.MainScriptEnv import voodoo.script.TomeScript import voodoo.tome.TomeEnv import voodoo.util.Directories import voodoo.util.SharedFolders import voodoo.util.json import voodoo.util.jsonConfiguration import voodoo.voodoo.main.GeneratedConstants import java.io.File import kotlin.script.experimental.jvmhost.BasicJvmScriptingHost import kotlin.system.exitProcess object VoodooMain : KLogging() { @JvmStatic fun main(vararg fullArgs: String) { val rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME) as Logger rootLogger.level = Level.DEBUG // TODO: pass as -Dvoodoo.debug=true ? System.setProperty(DEBUG_PROPERTY_NAME, DEBUG_PROPERTY_VALUE_ON) Thread.sleep(1000) // wait for logger to catch up logger.debug("using Voodoo: ${GeneratedConstants.FULL_VERSION}") logger.debug("full arguments: ${fullArgs.joinToString(", ", "[", "]") { it }}") // logger.debug("system.properties:") // System.getProperties().forEach { k, v -> // logger.debug { " $k = $v" } // } if (fullArgs.isEmpty()) { GradleSetup.main() exitProcess(0) } val directories = Directories.get(moduleName = "script") val cacheDir = directories.cacheHome val arguments = fullArgs.drop(1) logger.info { "arguments: ${arguments}"} val script = fullArgs.getOrNull(0)?.apply { require(isNotBlank()) { "'$this' configuration script name cannot be blank" } require(endsWith(".voodoo.kts")) { "'$this' configuration script filename must end with .voodoo.kts" } } ?: run { logger.error("configuration script must be the first parameter") exitProcess(1) } val scriptFile = File(script) require(scriptFile.exists()) { "script file does not exists" } val id = scriptFile.name.substringBeforeLast(".voodoo.kts").apply { require(isNotBlank()) { "the script file must contain a id in the filename" } }.toLowerCase() logger.debug("id: $id") if(!SharedFolders.RootDir.defaultInitialized) { SharedFolders.RootDir.value = File(System.getProperty("user.dir")).absoluteFile } val rootDir = SharedFolders.RootDir.get().absoluteFile val uploadDir = SharedFolders.UploadDir.get(id) val stopwatch = Stopwatch("main") val reportName = stopwatch { val host = "createJvmScriptingHost".watch { createJvmScriptingHost(cacheDir) } val libs = rootDir.resolve("libs") // TODO: set from system property val tomeDir = SharedFolders.TomeDir.get() val docDir = SharedFolders.DocDir.get(id) val lockFileName = "$id.lock.pack.json" val lockFile = rootDir.resolve(id).resolve(lockFileName) logger.info { "fullArgs: ${fullArgs.joinToString()}"} logger.info { "arguments: ${arguments}"} val funcs = mapOf<String, suspend Stopwatch.(Array<String>) -> Unit>( VoodooTask.Build.key to { args -> // TODO: only compile in this step val scriptEnv = host.evalScript<MainScriptEnv>( stopwatch = "evalScript".watch, libs = libs, scriptFile = scriptFile, args = *arrayOf(rootDir, id) ) val tomeEnv = initTome( stopwatch = "initTome".watch, libs = libs, host = host, tomeDir = tomeDir, docDir = docDir ) logger.debug("tomeEnv: $tomeEnv") val nestedPack = scriptEnv.pack // debug // rootDir.resolve(id).resolve("$id.nested.pack.json").writeText( // json.stringify(NestedPack.serializer(), nestedPack) // ) // TODO: pass extra args object VoodooTask.Build.execute( this, id, nestedPack, tomeEnv ) logger.info("finished") }, // TODO: git tag task // TODO: make changelog tasks VoodooTask.Changelog.key to { _ -> val changelogBuilder = initChangelogBuilder( stopwatch = "initChangelogBuilder".watch, libs = libs, id = id, tomeDir = tomeDir, host = host ) val tomeEnv = initTome( stopwatch = "initTome".watch, libs = libs, host = host, tomeDir = tomeDir, docDir = docDir ) VoodooTask.Changelog.execute(this, id, changelogBuilder, tomeEnv) }, VoodooTask.Pack.key to { args -> // TODO: pass pack method val arguments = voodoo.pack.PackArguments(ArgParser(args)) val packer = Pack.packMap[arguments.method.toLowerCase()] ?: run { Pack.logger.error("no such packing method: ${arguments.method}") exitProcess(-1) } VoodooTask.Pack.execute(this, id, packer) }, VoodooTask.Test.key to { args -> // TODO: pass test method val arguments = voodoo.test.TestArguments(ArgParser(args)) val testMethod = when (arguments.method) { "mmc" -> TestMethod.MultiMC(clean = arguments.clean) else -> error("no such method found for ${arguments.method}") } VoodooTask.Test.execute(this, id, testMethod) }, VoodooTask.Version.key to { _ -> logger.info("voodoo-main: " + GeneratedConstants.FULL_VERSION) logger.info("voodoo: " + VoodooTask.Version.version) val dependencies = VoodooTask.Version.dependencies() val width = dependencies.keys.map{it.length}.max() ?: 0 dependencies.forEach { (project, version) -> logger.info(" ${project}: ${version.padStart(width)}") } } ) fun printCommands(cmd: String?) { if (cmd == null) { logger.error("no command specified") } else { logger.error("unknown command '$cmd'") } logger.warn("voodoo ${GeneratedConstants.FULL_VERSION}") logger.warn("commands: ") funcs.keys.forEach { key -> logger.warn("> $key") } } val invocations = arguments.chunkBy(separator = "-") invocations.forEach { argChunk -> val command = argChunk.getOrNull(0) ?: run { printCommands(null) return } val remainingArgs = argChunk.drop(1).toTypedArray() logger.info("executing command '$command' with args [${remainingArgs.joinToString()}]") val function = funcs[command.toLowerCase()] if (function == null) { printCommands(command) return } runBlocking(CoroutineName("main")) { "${command}Watch".watch { function(remainingArgs) } } } invocations.joinToString("_") { it.joinToString("-") } } println(stopwatch.toStringPretty()) val reportDir= rootDir.resolve("reports").apply { mkdirs() } stopwatch.saveAsSvg(reportDir.resolve("${id}_$reportName.report.svg")) stopwatch.saveAsHtml(reportDir.resolve("${id}_$reportName.report.html")) val traceEventsReport = stopwatch.asTraceEventsReport() val jsonString = Json(JsonConfiguration(prettyPrint = true, encodeDefaults = true)) .stringify(TraceEventsReport.serializer(), traceEventsReport) reportDir.resolve("${id}_$reportName.report.json").writeText(jsonString) } private fun initChangelogBuilder( stopwatch: Stopwatch, libs: File, id: String, tomeDir: File, host: BasicJvmScriptingHost ): ChangelogBuilder = stopwatch { tomeDir.resolve("$id.changelog.kts") .also { file -> logger.debug { "trying to load: $file" } } .takeIf { it.exists() }?.let { idScript -> return@stopwatch host.evalScript<ChangeScript>( "evalScript_file".watch, libs = libs, scriptFile = idScript ).let { script -> script.getBuilderOrNull() ?: throw NotImplementedError("builder was not assigned in $idScript") } } tomeDir.resolve("default.changelog.kts") .also { file -> logger.debug { "trying to load: $file" } } .takeIf { it.exists() }?.let { defaultScript -> return@stopwatch host.evalScript<ChangeScript>( "evalScript_default".watch, libs = libs, scriptFile = defaultScript ).let { script -> script.getBuilderOrNull() ?: throw NotImplementedError("builder was not assigned in $defaultScript") } } logger.debug { "falling back to default changelog builder implementation" } return@stopwatch ChangelogBuilder() } private fun initTome( stopwatch: Stopwatch, libs: File, tomeDir: File, docDir: File, host: BasicJvmScriptingHost ): TomeEnv = stopwatch { val tomeEnv = TomeEnv(docDir) val tomeScripts = tomeDir.listFiles { file -> logger.debug("tome testing: $file") file.isFile && file.name.endsWith(".tome.kts") }!! tomeScripts.forEach { scriptFile -> require(scriptFile.exists()) { "script file does not exists" } val scriptFileName = scriptFile.name val id = scriptFileName.substringBeforeLast(".tome.kts").apply { require(isNotBlank()) { "the script file must contain a id in the filename" } } val tomeScriptEnv = host.evalScript<TomeScript>( "evalScript_tome".watch, libs = libs, scriptFile = scriptFile, args = *arrayOf(id) ) val generator = tomeScriptEnv.getGeneratorOrNull() ?: throw NotImplementedError("generator was not assigned in $scriptFile") tomeEnv.add(tomeScriptEnv.filename, generator) } return@stopwatch tomeEnv } private fun Iterable<String>.chunkBy(separator: String = "-"): List<Array<String>> { val result: MutableList<MutableList<String>> = mutableListOf(mutableListOf()) this.forEach { if (it == separator) result += mutableListOf<String>() else result.last() += it } return result.map { it.toTypedArray() } } }
1
null
1
1
5a4e0217b1f8d2af193e8c04d1bee0258fd1cc5a
12,488
Voodoo
MIT License
paymentsheet/src/test/java/com/stripe/android/customersheet/utils/CustomerSheetTestHelper.kt
stripe
6,926,049
false
{"Kotlin": 9818601, "Java": 71963, "Ruby": 21633, "Shell": 18965, "Python": 13941}
package com.stripe.android.customersheet.utils import android.app.Application import androidx.activity.result.ActivityResultLauncher import androidx.lifecycle.testing.TestLifecycleOwner import androidx.test.core.app.ApplicationProvider import com.stripe.android.PaymentConfiguration import com.stripe.android.core.Logger import com.stripe.android.customersheet.CustomerAdapter import com.stripe.android.customersheet.CustomerSheet import com.stripe.android.customersheet.CustomerSheetLoader import com.stripe.android.customersheet.CustomerSheetViewModel import com.stripe.android.customersheet.CustomerSheetViewState import com.stripe.android.customersheet.ExperimentalCustomerSheetApi import com.stripe.android.customersheet.FakeCustomerAdapter import com.stripe.android.customersheet.FakeStripeRepository import com.stripe.android.customersheet.analytics.CustomerSheetEventReporter import com.stripe.android.model.PaymentMethod import com.stripe.android.model.PaymentMethodFixtures.CARD_PAYMENT_METHOD import com.stripe.android.networking.StripeRepository import com.stripe.android.payments.paymentlauncher.PaymentLauncherContract import com.stripe.android.payments.paymentlauncher.StripePaymentLauncher import com.stripe.android.payments.paymentlauncher.StripePaymentLauncherAssistedFactory import com.stripe.android.paymentsheet.IntentConfirmationInterceptor import com.stripe.android.paymentsheet.forms.FormViewModel import com.stripe.android.paymentsheet.injection.FormViewModelSubcomponent import com.stripe.android.paymentsheet.model.PaymentSelection import com.stripe.android.paymentsheet.paymentdatacollection.FormArguments import com.stripe.android.testing.PaymentIntentFactory import com.stripe.android.ui.core.cbc.CardBrandChoiceEligibility import com.stripe.android.ui.core.forms.resources.LpmRepository import com.stripe.android.uicore.address.AddressRepository import com.stripe.android.utils.DummyActivityResultCaller import com.stripe.android.utils.FakeIntentConfirmationInterceptor import kotlinx.coroutines.Dispatchers import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import javax.inject.Provider import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext @OptIn(ExperimentalCustomerSheetApi::class) object CustomerSheetTestHelper { internal val application = ApplicationProvider.getApplicationContext<Application>() internal val lpmRepository = LpmRepository( LpmRepository.LpmRepositoryArguments( resources = application.resources, isFinancialConnectionsAvailable = { true }, ) ).apply { update( PaymentIntentFactory.create( paymentMethodTypes = PaymentMethod.Type.values().map { it.code }, ), null ) } private fun mockedFormViewModel( configuration: CustomerSheet.Configuration, ): Provider<FormViewModelSubcomponent.Builder> { val formViewModel = FormViewModel( context = application, formArguments = FormArguments( PaymentMethod.Type.Card.code, showCheckbox = false, showCheckboxControlledFields = false, initialPaymentMethodCreateParams = null, merchantName = configuration.merchantDisplayName ?: application.applicationInfo.loadLabel(application.packageManager).toString(), billingDetails = configuration.defaultBillingDetails, billingDetailsCollectionConfiguration = configuration.billingDetailsCollectionConfiguration, cbcEligibility = CardBrandChoiceEligibility.Ineligible ), lpmRepository = lpmRepository, addressRepository = AddressRepository( resources = ApplicationProvider.getApplicationContext<Application>().resources, workContext = Dispatchers.Unconfined, ), showCheckboxFlow = mock() ) val mockFormBuilder = mock<FormViewModelSubcomponent.Builder>() val mockFormSubcomponent = mock<FormViewModelSubcomponent>() val mockFormSubComponentBuilderProvider = mock<Provider<FormViewModelSubcomponent.Builder>>() whenever(mockFormBuilder.build()).thenReturn(mockFormSubcomponent) whenever(mockFormBuilder.formArguments(any())).thenReturn(mockFormBuilder) whenever(mockFormBuilder.showCheckboxFlow(any())).thenReturn(mockFormBuilder) whenever(mockFormSubcomponent.viewModel).thenReturn(formViewModel) whenever(mockFormSubComponentBuilderProvider.get()).thenReturn(mockFormBuilder) return mockFormSubComponentBuilderProvider } internal fun createViewModel( lpmRepository: LpmRepository = CustomerSheetTestHelper.lpmRepository, isLiveMode: Boolean = false, workContext: CoroutineContext = EmptyCoroutineContext, initialBackStack: List<CustomerSheetViewState> = listOf( CustomerSheetViewState.Loading( isLiveMode ) ), isGooglePayAvailable: Boolean = true, customerPaymentMethods: List<PaymentMethod> = listOf(CARD_PAYMENT_METHOD), savedPaymentSelection: PaymentSelection? = null, stripeRepository: StripeRepository = FakeStripeRepository(), paymentConfiguration: PaymentConfiguration = PaymentConfiguration( publishableKey = "pk_test_123", stripeAccountId = null, ), configuration: CustomerSheet.Configuration = CustomerSheet.Configuration( googlePayEnabled = isGooglePayAvailable ), formViewModelSubcomponentBuilderProvider: Provider<FormViewModelSubcomponent.Builder> = mockedFormViewModel(configuration), eventReporter: CustomerSheetEventReporter = mock(), intentConfirmationInterceptor: IntentConfirmationInterceptor = FakeIntentConfirmationInterceptor().apply { enqueueCompleteStep(true) }, customerAdapter: CustomerAdapter = FakeCustomerAdapter( paymentMethods = CustomerAdapter.Result.success(customerPaymentMethods) ), customerSheetLoader: CustomerSheetLoader = FakeCustomerSheetLoader( customerPaymentMethods = customerPaymentMethods, paymentSelection = savedPaymentSelection, isGooglePayAvailable = isGooglePayAvailable, ), ): CustomerSheetViewModel { return CustomerSheetViewModel( application = application, initialBackStack = initialBackStack, workContext = workContext, savedPaymentSelection = savedPaymentSelection, paymentConfigurationProvider = { paymentConfiguration }, formViewModelSubcomponentBuilderProvider = formViewModelSubcomponentBuilderProvider, resources = application.resources, stripeRepository = stripeRepository, customerAdapter = customerAdapter, lpmRepository = lpmRepository, configuration = configuration, isLiveModeProvider = { isLiveMode }, logger = Logger.noop(), intentConfirmationInterceptor = intentConfirmationInterceptor, paymentLauncherFactory = object : StripePaymentLauncherAssistedFactory { override fun create( publishableKey: () -> String, stripeAccountId: () -> String?, statusBarColor: Int?, hostActivityLauncher: ActivityResultLauncher<PaymentLauncherContract.Args> ): StripePaymentLauncher { return mock() } }, statusBarColor = { null }, eventReporter = eventReporter, customerSheetLoader = customerSheetLoader, ).apply { registerFromActivity(DummyActivityResultCaller(), TestLifecycleOwner()) } } }
113
Kotlin
616
1,151
3d649d0e864826e5ca932becc1438baf981e0336
8,011
stripe-android
MIT License
skiko/src/commonMain/kotlin/org/jetbrains/skija/svg/SVGTag.kt
pa-dieter
403,520,837
true
{"Kotlin": 949848, "C++": 483039, "Objective-C++": 20299, "Dockerfile": 2368, "JavaScript": 1202, "Shell": 555}
package org.jetbrains.skija.svg enum class SVGTag { CIRCLE, CLIP_PATH, DEFS, ELLIPSE, FE_BLEND, FE_COLOR_MATRIX, FE_COMPOSITE, FE_DIFFUSE_LIGHTING, FE_DISPLACEMENT_MAP, FE_DISTANT_LIGHT, FE_FLOOD, FE_GAUSSIAN_BLUR, FE_IMAGE, FE_MORPHOLOGY, FE_OFFSET, FE_POINT_LIGHT, FE_SPECULAR_LIGHTING, FE_SPOT_LIGHT, FE_TURBULENCE, FILTER, G, IMAGE, LINE, LINEAR_GRADIENT, MASK, PATH, PATTERN, POLYGON, POLYLINE, RADIAL_GRADIENT, RECT, STOP, SVG, TEXT, TEXT_LITERAL, TEXTPATH, TSPAN, USE; }
0
null
0
0
c9dda21dea90abfa68db1fdf8932d8f12141c1f8
482
skiko
Apache License 2.0
app/src/main/java/com/grupo14/gym_androidapp/api/models/Difficulty.kt
ThomasMiz
553,204,342
false
null
package com.grupo14.gym_androidapp.api.models import com.fasterxml.jackson.annotation.JsonProperty import com.grupo14.gym_androidapp.R enum class Difficulty(val apiEnumString: String, val stringResourceId: Int) { @JsonProperty("rookie") ROOKIE("rookie", R.string.rookie), @JsonProperty("beginner") BEGINNER("beginner", R.string.beginner), @JsonProperty("intermediate") INTERMEDIATE("intermediate", R.string.intermediate), @JsonProperty("advanced") ADVANCED("advanced", R.string.advanced), @JsonProperty("expert") EXPERT("expert", R.string.expert); }
12
Kotlin
0
0
4a138ba6b0b5fd29f42e2de9901281a047cde3ce
595
GYM-AndroidApp
MIT License
app/src/main/java/com/tigerspike/flickrfeed/domain/model/ImageMedia.kt
knighthedspi
216,192,104
false
null
package com.tigerspike.flickrfeed.domain.model data class ImageMedia( val m: String )
0
Kotlin
0
2
6d4e9e856adca7da912d01f6c24dc703c7fdc7a1
90
FlickrFeed
Apache License 2.0
platform/backend/api/src/main/kotlin/io/hamal/api/http/controller/endpoint/EndpointGetController.kt
hamal-io
622,870,037
false
{"Kotlin": 2439820, "C": 1398561, "TypeScript": 321391, "Lua": 156281, "C++": 40661, "Makefile": 11728, "Java": 7564, "CMake": 2810, "JavaScript": 2640, "CSS": 1567, "Shell": 977, "HTML": 903}
package io.hamal.api.http.controller.endpoint import io.hamal.core.adapter.endpoint.EndpointGetPort import io.hamal.core.adapter.func.FuncGetPort import io.hamal.core.component.Retry import io.hamal.lib.domain.vo.EndpointId import io.hamal.lib.sdk.api.ApiEndpoint import io.hamal.lib.sdk.api.ApiEndpoint.* import io.hamal.repository.api.Endpoint import io.hamal.repository.api.Func import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RestController @RestController internal class EndpointGetController( private val retry: Retry, private val endpointGet: EndpointGetPort, private val funcGet: FuncGetPort ) { @GetMapping("/v1/endpoints/{endpointId}") fun get(@PathVariable("endpointId") endpointId: EndpointId): ResponseEntity<ApiEndpoint> = retry { endpointGet(endpointId).let { endpoint -> assemble(endpoint, funcGet(endpoint.funcId)) } } private fun assemble(endpoint: Endpoint, func: Func) = ResponseEntity.ok( ApiEndpoint( id = endpoint.id, func = Func( id = func.id, name = func.name ), name = endpoint.name ) ) }
37
Kotlin
0
0
dc4c112f018e267ff3247c70104f6c33ce5aa235
1,382
hamal
Creative Commons Zero v1.0 Universal
src/jvmTest/java/com/codeborne/selenide/commands/ShouldCommandTest.kt
TarCV
358,762,107
true
{"Kotlin": 998044, "Java": 322706, "HTML": 46587, "XSLT": 7418}
package com.codeborne.selenide.commands import com.codeborne.selenide.Condition import com.codeborne.selenide.SelenideElement import com.codeborne.selenide.impl.WebElementSource import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runBlockingTest import org.assertj.core.api.WithAssertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.mockito.Mockito import org.openqa.selenium.WebElement import kotlin.time.ExperimentalTime @ExperimentalTime @ExperimentalCoroutinesApi internal class ShouldCommandTest : WithAssertions { private val proxy = Mockito.mock(SelenideElement::class.java) private val locator = Mockito.mock(WebElementSource::class.java) private val shouldCommand = Should() private val mockedFoundElement = Mockito.mock(WebElement::class.java) @BeforeEach fun setup() = runBlockingTest { Mockito.`when`<Any>(locator.getWebElement()).thenReturn(mockedFoundElement) } @Test @Throws(NoSuchFieldException::class, IllegalAccessException::class) fun testDefaultConstructor() { val should = Should() val prefixField = should.javaClass.getDeclaredField("prefix") prefixField.isAccessible = true val prefix = prefixField[should] as String assertThat(prefix.isEmpty()) .isTrue } @Test fun testExecuteMethodWithNonStringArgs() = runBlockingTest { val returnedElement = shouldCommand.execute(proxy, locator, arrayOf<Any>(Condition.disabled)) assertThat(returnedElement) .isEqualTo(proxy) } @Test fun testExecuteMethodWithStringArgs() = runBlockingTest { val returnedElement = shouldCommand.execute(proxy, locator, arrayOf<Any>("hello")) assertThat(returnedElement) .isEqualTo(proxy) } }
0
Kotlin
0
0
c86103748bdf214adb8a027492d21765059d3629
1,846
selenide.kt-js
MIT License
domain/src/main/java/io/fournkoner/netschool/domain/repositories/ReportsRepository.kt
4nk1r
593,159,855
false
null
package io.fournkoner.netschool.domain.repositories import io.fournkoner.netschool.domain.entities.reports.* interface ReportsRepository { suspend fun getShortReportRequestData(): Result<List<ReportRequestData>> suspend fun generateShortReport(params: List<ReportRequestData>): Result<ShortReport?> suspend fun getSubjectReportRequestData(): Result<SubjectReportRequestData> suspend fun generateSubjectReport(params: List<ReportRequestData>): Result<SubjectReport?> suspend fun generateFinalReport(): Result<List<FinalReportPeriod>> }
0
Kotlin
0
0
b2038eca0fe700b784dd85c60c75ad9d686a8865
561
netschool
MIT License
app/src/main/java/com/ericampire/android/androidstudycase/presentation/screen/explore/business/ExploreViewState.kt
josh-Muleshi
410,802,212
true
{"Kotlin": 203893}
package com.ericampire.android.androidstudycase.presentation.screen.explore.business import com.airbnb.mvrx.Async import com.airbnb.mvrx.MavericksState import com.airbnb.mvrx.Uninitialized import com.ericampire.android.androidstudycase.domain.entity.Lottiefile data class ExploreViewState( val files: Async<List<Lottiefile>> = Uninitialized, ) : MavericksState
0
null
0
1
8d68f00c3e1506ec50a71901f784ca4dc5d19007
365
lottiefiles-app
Apache License 2.0
lib/src/test/java/com/irurueta/android/glutils/OrientationHelperTest.kt
albertoirurueta
417,939,959
false
null
package com.irurueta.android.glutils import android.content.Context import android.hardware.camera2.CameraCharacteristics import android.hardware.camera2.CameraManager import android.os.Build import android.view.Display import android.view.Surface import android.view.WindowManager import com.irurueta.geometry.* import com.irurueta.statistics.UniformRandomizer import io.mockk.every import io.mockk.mockk import io.mockk.unmockkAll import org.junit.After import org.junit.Assert.* import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @Suppress("DEPRECATION") @RunWith(RobolectricTestRunner::class) class OrientationHelperTest { @After fun afterTest() { unmockkAll() } @Test fun checkConstants() { assertEquals(0, OrientationHelper.ORIENTATION_0_DEGREES) assertEquals(90, OrientationHelper.ORIENTATION_90_DEGREES) assertEquals(180, OrientationHelper.ORIENTATION_180_DEGREES) assertEquals(270, OrientationHelper.ORIENTATION_270_DEGREES) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraIdSensorOrientation0DisplayRotation0AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, CAMERA_ID) assertEquals(CameraToDisplayOrientation.ORIENTATION_0_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraIdSensorOrientation0DisplayRotation90AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_90) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, CAMERA_ID) assertEquals(CameraToDisplayOrientation.ORIENTATION_270_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraIdSensorOrientation0DisplayRotation180AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_180) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, CAMERA_ID) assertEquals(CameraToDisplayOrientation.ORIENTATION_180_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraIdSensorOrientation0DisplayRotation270AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_270) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, CAMERA_ID) assertEquals(CameraToDisplayOrientation.ORIENTATION_90_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraIdSensorOrientation90DisplayRotation0AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, CAMERA_ID) assertEquals(CameraToDisplayOrientation.ORIENTATION_90_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraIdSensorOrientation90DisplayRotation90AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_90) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, CAMERA_ID) assertEquals(CameraToDisplayOrientation.ORIENTATION_0_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraIdSensorOrientation90DisplayRotation180AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_180) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, CAMERA_ID) assertEquals(CameraToDisplayOrientation.ORIENTATION_270_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraIdSensorOrientation90DisplayRotation270AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_270) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, CAMERA_ID) assertEquals(CameraToDisplayOrientation.ORIENTATION_180_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraIdSensorOrientation180DisplayRotation0AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, CAMERA_ID) assertEquals(CameraToDisplayOrientation.ORIENTATION_180_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraIdSensorOrientation180DisplayRotation90AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_90) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, CAMERA_ID) assertEquals(CameraToDisplayOrientation.ORIENTATION_90_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraIdSensorOrientation180DisplayRotation180AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_180) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, CAMERA_ID) assertEquals(CameraToDisplayOrientation.ORIENTATION_0_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraIdSensorOrientation180DisplayRotation270AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_270) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, CAMERA_ID) assertEquals(CameraToDisplayOrientation.ORIENTATION_270_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraIdSensorOrientation270DisplayRotation0AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, CAMERA_ID) assertEquals(CameraToDisplayOrientation.ORIENTATION_270_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraIdSensorOrientation270DisplayRotation90AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_90) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, CAMERA_ID) assertEquals(CameraToDisplayOrientation.ORIENTATION_180_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraIdSensorOrientation270DisplayRotation180AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_180) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, CAMERA_ID) assertEquals(CameraToDisplayOrientation.ORIENTATION_90_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraIdSensorOrientation270DisplayRotation270AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_270) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, CAMERA_ID) assertEquals(CameraToDisplayOrientation.ORIENTATION_0_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraCharacteristicsSensorOrientation0DisplayRotation0AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, cameraCharacteristics) assertEquals(CameraToDisplayOrientation.ORIENTATION_0_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraCharacteristicsSensorOrientation0DisplayRotation90AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_90) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, cameraCharacteristics) assertEquals(CameraToDisplayOrientation.ORIENTATION_270_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraCharacteristicsSensorOrientation0DisplayRotation180AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_180) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, cameraCharacteristics) assertEquals(CameraToDisplayOrientation.ORIENTATION_180_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraCharacteristicsSensorOrientation0DisplayRotation270AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_270) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, cameraCharacteristics) assertEquals(CameraToDisplayOrientation.ORIENTATION_90_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraCharacteristicsSensorOrientation90DisplayRotation0AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, cameraCharacteristics) assertEquals(CameraToDisplayOrientation.ORIENTATION_90_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraCharacteristicsSensorOrientation90DisplayRotation90AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_90) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, cameraCharacteristics) assertEquals(CameraToDisplayOrientation.ORIENTATION_0_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraCharacteristicsSensorOrientation90DisplayRotation180AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_180) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, cameraCharacteristics) assertEquals(CameraToDisplayOrientation.ORIENTATION_270_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraCharacteristicsSensorOrientation90DisplayRotation270AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_270) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, cameraCharacteristics) assertEquals(CameraToDisplayOrientation.ORIENTATION_180_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraCharacteristicsSensorOrientation180DisplayRotation0AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, cameraCharacteristics) assertEquals(CameraToDisplayOrientation.ORIENTATION_180_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraCharacteristicsSensorOrientation180DisplayRotation90AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_90) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, cameraCharacteristics) assertEquals(CameraToDisplayOrientation.ORIENTATION_90_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraCharacteristicsSensorOrientation180DisplayRotation180AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_180) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, cameraCharacteristics) assertEquals(CameraToDisplayOrientation.ORIENTATION_0_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraCharacteristicsSensorOrientation180DisplayRotation270AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_270) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, cameraCharacteristics) assertEquals(CameraToDisplayOrientation.ORIENTATION_270_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraCharacteristicsSensorOrientation270DisplayRotation0AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, cameraCharacteristics) assertEquals(CameraToDisplayOrientation.ORIENTATION_270_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraCharacteristicsSensorOrientation270DisplayRotation90AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_90) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, cameraCharacteristics) assertEquals(CameraToDisplayOrientation.ORIENTATION_180_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraCharacteristicsSensorOrientation270DisplayRotation180AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_180) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, cameraCharacteristics) assertEquals(CameraToDisplayOrientation.ORIENTATION_90_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientation_whenCameraCharacteristicsSensorOrientation270DisplayRotation270AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_270) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientation(context, cameraCharacteristics) assertEquals(CameraToDisplayOrientation.ORIENTATION_0_DEGREES, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraIdSensorOrientation0DisplayRotation0AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, CAMERA_ID) assertEquals(0, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraIdSensorOrientation0DisplayRotation90AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_90) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, CAMERA_ID) assertEquals(270, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraIdSensorOrientation0DisplayRotation180AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_180) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, CAMERA_ID) assertEquals(180, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraIdSensorOrientation0DisplayRotation270AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_270) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, CAMERA_ID) assertEquals(90, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraIdSensorOrientation90DisplayRotation0AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, CAMERA_ID) assertEquals(90, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraIdSensorOrientation90DisplayRotation90AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_90) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, CAMERA_ID) assertEquals(0, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraIdSensorOrientation90DisplayRotation180AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_180) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, CAMERA_ID) assertEquals(270, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraIdSensorOrientation90DisplayRotation270AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_270) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, CAMERA_ID) assertEquals(180, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraIdSensorOrientation180DisplayRotation0AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, CAMERA_ID) assertEquals(180, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraIdSensorOrientation180DisplayRotation90AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_90) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, CAMERA_ID) assertEquals(90, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraIdSensorOrientation180DisplayRotation180AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_180) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, CAMERA_ID) assertEquals(0, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraIdSensorOrientation180DisplayRotation270AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_270) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, CAMERA_ID) assertEquals(270, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraIdSensorOrientation270DisplayRotation0AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, CAMERA_ID) assertEquals(270, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraIdSensorOrientation270DisplayRotation90AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_90) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, CAMERA_ID) assertEquals(180, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraIdSensorOrientation270DisplayRotation180AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_180) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, CAMERA_ID) assertEquals(90, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraIdSensorOrientation270DisplayRotation270AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_270) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, CAMERA_ID) assertEquals(0, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraCharacteristicsSensorOrientation0DisplayRotation0AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, cameraCharacteristics) assertEquals(0, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraCharacteristicsSensorOrientation0DisplayRotation90AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_90) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, cameraCharacteristics) assertEquals(270, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraCharacteristicsSensorOrientation0DisplayRotation180AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_180) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, cameraCharacteristics) assertEquals(180, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraCharacteristicsSensorOrientation0DisplayRotation270AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_270) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, cameraCharacteristics) assertEquals(90, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraCharacteristicsSensorOrientation90DisplayRotation0AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, cameraCharacteristics) assertEquals(90, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraCharacteristicsSensorOrientation90DisplayRotation90AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_90) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, cameraCharacteristics) assertEquals(0, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraCharacteristicsSensorOrientation90DisplayRotation180AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_180) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, cameraCharacteristics) assertEquals(270, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraCharacteristicsSensorOrientation90DisplayRotation270AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_270) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, cameraCharacteristics) assertEquals(180, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraCharacteristicsSensorOrientation180DisplayRotation0AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, cameraCharacteristics) assertEquals(180, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraCharacteristicsSensorOrientation180DisplayRotation90AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_90) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, cameraCharacteristics) assertEquals(90, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraCharacteristicsSensorOrientation180DisplayRotation180AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_180) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, cameraCharacteristics) assertEquals(0, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraCharacteristicsSensorOrientation180DisplayRotation270AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_270) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, cameraCharacteristics) assertEquals(270, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraCharacteristicsSensorOrientation270DisplayRotation0AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, cameraCharacteristics) assertEquals(270, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraCharacteristicsSensorOrientation270DisplayRotation90AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_90) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, cameraCharacteristics) assertEquals(180, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraCharacteristicsSensorOrientation270DisplayRotation180AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_180) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, cameraCharacteristics) assertEquals(90, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenCameraCharacteristicsSensorOrientation270DisplayRotation270AndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_270) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, cameraCharacteristics) assertEquals(0, result) } @Config(sdk = [Build.VERSION_CODES.R]) @Test fun getCameraDisplayOrientationDegrees_whenDisplayRotationUnknownAndSdk30_returnsExpectedValue() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(-1) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.getCameraDisplayOrientationDegrees(context, CAMERA_ID) assertEquals(0, result) } @Test fun toViewCoordinatesRotation_whenCameraIdSensorOrientation0_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = Rotation2D() OrientationHelper.toViewCoordinatesRotation(context, CAMERA_ID, result) assertEquals(0.0, Math.toDegrees(result.theta), 0.0) } @Test fun toViewCoordinatesRotation_whenCameraIdSensorOrientation90_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = Rotation2D() OrientationHelper.toViewCoordinatesRotation(context, CAMERA_ID, result) assertEquals(90.0, Math.toDegrees(result.theta), 0.0) } @Test fun toViewCoordinatesRotation_whenCameraIdSensorOrientation180_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = Rotation2D() OrientationHelper.toViewCoordinatesRotation(context, CAMERA_ID, result) assertEquals(180.0, Math.toDegrees(result.theta), 0.0) } @Test fun toViewCoordinatesRotation_whenCameraIdSensorOrientation270_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = Rotation2D() OrientationHelper.toViewCoordinatesRotation(context, CAMERA_ID, result) assertEquals(270.0, Math.toDegrees(result.theta), 0.0) } @Test fun toViewCoordinatesRotation_whenCameraCharacteristicsSensorOrientation0_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = Rotation2D() OrientationHelper.toViewCoordinatesRotation(context, cameraCharacteristics, result) assertEquals(0.0, Math.toDegrees(result.theta), 0.0) } @Test fun toViewCoordinatesRotation_whenCameraCharacteristicsSensorOrientation90_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = Rotation2D() OrientationHelper.toViewCoordinatesRotation(context, cameraCharacteristics, result) assertEquals(90.0, Math.toDegrees(result.theta), 0.0) } @Test fun toViewCoordinatesRotation_whenCameraCharacteristicsSensorOrientation180_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = Rotation2D() OrientationHelper.toViewCoordinatesRotation(context, cameraCharacteristics, result) assertEquals(180.0, Math.toDegrees(result.theta), 0.0) } @Test fun toViewCoordinatesRotation_whenCameraCharacteristicsSensorOrientation270_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = Rotation2D() OrientationHelper.toViewCoordinatesRotation(context, cameraCharacteristics, result) assertEquals(270.0, Math.toDegrees(result.theta), 0.0) } @Test fun toViewCoordinatesRotation_whenCameraIdSensorOrientation0New_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.toViewCoordinatesRotation(context, CAMERA_ID) assertEquals(0.0, Math.toDegrees(result.theta), 0.0) } @Test fun toViewCoordinatesRotation_whenCameraIdSensorOrientation90New_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.toViewCoordinatesRotation(context, CAMERA_ID) assertEquals(90.0, Math.toDegrees(result.theta), 0.0) } @Test fun toViewCoordinatesRotation_whenCameraIdSensorOrientation180New_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.toViewCoordinatesRotation(context, CAMERA_ID) assertEquals(180.0, Math.toDegrees(result.theta), 0.0) } @Test fun toViewCoordinatesRotation_whenCameraIdSensorOrientation270New_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.toViewCoordinatesRotation(context, CAMERA_ID) assertEquals(270.0, Math.toDegrees(result.theta), 0.0) } @Test fun toViewCoordinatesRotation_whenCameraCharacteristicsSensorOrientation0New_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.toViewCoordinatesRotation(context, cameraCharacteristics) assertEquals(0.0, Math.toDegrees(result.theta), 0.0) } @Test fun toViewCoordinatesRotation_whenCameraCharacteristicsSensorOrientation90New_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.toViewCoordinatesRotation(context, cameraCharacteristics) assertEquals(90.0, Math.toDegrees(result.theta), 0.0) } @Test fun toViewCoordinatesRotation_whenCameraCharacteristicsSensorOrientation180New_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.toViewCoordinatesRotation(context, cameraCharacteristics) assertEquals(180.0, Math.toDegrees(result.theta), 0.0) } @Test fun toViewCoordinatesRotation_whenCameraCharacteristicsSensorOrientation270New_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.toViewCoordinatesRotation(context, cameraCharacteristics) assertEquals(270.0, Math.toDegrees(result.theta), 0.0) } @Test fun fromViewCoordinatesRotation_whenCameraIdSensorOrientation0_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = Rotation2D() OrientationHelper.fromViewCoordinatesRotation(context, CAMERA_ID, result) assertEquals(0.0, Math.toDegrees(result.theta), 0.0) } @Test fun fromViewCoordinatesRotation_whenCameraIdSensorOrientation90_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = Rotation2D() OrientationHelper.fromViewCoordinatesRotation(context, CAMERA_ID, result) assertEquals(-90.0, Math.toDegrees(result.theta), 0.0) } @Test fun fromViewCoordinatesRotation_whenCameraIdSensorOrientation180_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = Rotation2D() OrientationHelper.fromViewCoordinatesRotation(context, CAMERA_ID, result) assertEquals(-180.0, Math.toDegrees(result.theta), 0.0) } @Test fun fromViewCoordinatesRotation_whenCameraIdSensorOrientation270_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = Rotation2D() OrientationHelper.fromViewCoordinatesRotation(context, CAMERA_ID, result) assertEquals(-270.0, Math.toDegrees(result.theta), 0.0) } @Test fun fromViewCoordinatesRotation_whenCameraCharacteristicsSensorOrientation0_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = Rotation2D() OrientationHelper.fromViewCoordinatesRotation(context, cameraCharacteristics, result) assertEquals(0.0, Math.toDegrees(result.theta), 0.0) } @Test fun fromViewCoordinatesRotation_whenCameraCharacteristicsSensorOrientation90_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = Rotation2D() OrientationHelper.fromViewCoordinatesRotation(context, cameraCharacteristics, result) assertEquals(-90.0, Math.toDegrees(result.theta), 0.0) } @Test fun fromViewCoordinatesRotation_whenCameraCharacteristicsSensorOrientation180_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = Rotation2D() OrientationHelper.fromViewCoordinatesRotation(context, cameraCharacteristics, result) assertEquals(-180.0, Math.toDegrees(result.theta), 0.0) } @Test fun fromViewCoordinatesRotation_whenCameraCharacteristicsSensorOrientation270_returnsExpectedRotation() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = Rotation2D() OrientationHelper.fromViewCoordinatesRotation(context, cameraCharacteristics, result) assertEquals(-270.0, Math.toDegrees(result.theta), 0.0) } @Test fun fromViewCoordinatesRotation_whenCameraIdSensorOrientation0New_returnExpectedResult() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.fromViewCoordinatesRotation(context, CAMERA_ID) assertEquals(0.0, Math.toDegrees(result.theta), 0.0) } @Test fun fromViewCoordinatesRotation_whenCameraIdSensorOrientation90New_returnsExpectedResult() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.fromViewCoordinatesRotation(context, CAMERA_ID) assertEquals(-90.0, Math.toDegrees(result.theta), 0.0) } @Test fun fromViewCoordinatesRotation_whenCameraIdSensorOrientation180New_returnsExpectedResult() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.fromViewCoordinatesRotation(context, CAMERA_ID) assertEquals(-180.0, Math.toDegrees(result.theta), 0.0) } @Test fun fromViewCoordinatesRotation_whenCameraIdSensorOrientation270New_returnsExpectedResult() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val result = OrientationHelper.fromViewCoordinatesRotation(context, CAMERA_ID) assertEquals(-270.0, Math.toDegrees(result.theta), 0.0) } @Test fun fromViewCoordinatesRotation_whenCameraCharacteristicsSensorOrientation0New_returnsExpectedResult() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.fromViewCoordinatesRotation(context, cameraCharacteristics) assertEquals(0.0, Math.toDegrees(result.theta), 0.0) } @Test fun fromViewCoordinatesRotation_whenCameracharacteristicsSensorOrientation90New_returnsExpectedResult() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.fromViewCoordinatesRotation(context, cameraCharacteristics) assertEquals(-90.0, Math.toDegrees(result.theta), 0.0) } @Test fun fromViewCoordinatesRotation_whenCameraCharacteristicsSensorOrientation180New_returnsExpectedResult() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.fromViewCoordinatesRotation(context, cameraCharacteristics) assertEquals(-180.0, Math.toDegrees(result.theta), 0.0) } @Test fun fromViewCoordinatesRotation_whenCameraCharacteristicsSensorOrientation270New_returnsExpectedResult() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val result = OrientationHelper.fromViewCoordinatesRotation(context, cameraCharacteristics) assertEquals(-270.0, Math.toDegrees(result.theta), 0.0) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraIdSensorOrientation0AndIntrinsics_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( context, CAMERA_ID, intrinsics, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( context, CAMERA_ID, intrinsics, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraIdSensorOrientation90AndIntrinsics_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( context, CAMERA_ID, intrinsics, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( context, CAMERA_ID, intrinsics, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraIdSensorOrientation180AndIntrinsics_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( context, CAMERA_ID, intrinsics, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( context, CAMERA_ID, intrinsics, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraIdSensorOrientation270AndIntrinsics_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( context, CAMERA_ID, intrinsics, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( context, CAMERA_ID, intrinsics, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraCharacteristicsSensorOrientation0AndIntrinsics_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( context, cameraCharacteristics, intrinsics, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( context, cameraCharacteristics, intrinsics, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraCharacteristicsSensorOrientation90AndIntrinsics_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( context, cameraCharacteristics, intrinsics, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( context, cameraCharacteristics, intrinsics, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraCharacteristicsSensorOrientation180AndIntrinsics_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( context, cameraCharacteristics, intrinsics, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( context, cameraCharacteristics, intrinsics, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraCharacteristicsSensorOrientation270AndIntrinsics_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( context, cameraCharacteristics, intrinsics, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( context, cameraCharacteristics, intrinsics, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenOrientation0AndIntrinsics_areInverseTransformations() { val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_0_DEGREES, intrinsics, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_0_DEGREES, intrinsics, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenOrientation90AndIntrinsics_areInverseTransformations() { val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_90_DEGREES, intrinsics, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_90_DEGREES, intrinsics, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenOrientation180AndIntrinsics_areInverseTransformations() { val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_180_DEGREES, intrinsics, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_180_DEGREES, intrinsics, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenOrientation270AndIntrinsics_areInverseTransformations() { val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_270_DEGREES, intrinsics, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_270_DEGREES, intrinsics, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenOrientationUnknownAndIntrinsics_areInverseTransformations() { val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_UNKNOWN, intrinsics, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_UNKNOWN, intrinsics, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenRotationAndIntrinsics_areInverseTransformations() { val randomizer = UniformRandomizer() val angle = Math.toRadians( randomizer.nextDouble( MIN_ROTATION_ANGLE_DEGREES, MAX_ROTATION_ANGLE_DEGREES ) ) val rotation = Rotation2D(angle) val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( rotation, intrinsics, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( rotation, intrinsics, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraIdSensorOrientation0AndPivot_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation(context, CAMERA_ID, pivot, toViewResult) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( context, CAMERA_ID, pivot, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraIdSensorOrientation90AndPivot_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation(context, CAMERA_ID, pivot, toViewResult) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( context, CAMERA_ID, pivot, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraIdSensorOrientation180AndPivot_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation(context, CAMERA_ID, pivot, toViewResult) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( context, CAMERA_ID, pivot, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraIdSensorOrientation270AndPivot_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation(context, CAMERA_ID, pivot, toViewResult) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( context, CAMERA_ID, pivot, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraCharacteristicsSensorOrientation0AndPivot_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( context, cameraCharacteristics, pivot, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( context, cameraCharacteristics, pivot, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraCharacteristicsSensorOrientation90AndPivot_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( context, cameraCharacteristics, pivot, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( context, cameraCharacteristics, pivot, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraCharacteristicsSensorOrientation180AndPivot_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( context, cameraCharacteristics, pivot, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( context, cameraCharacteristics, pivot, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraCharacteristicsSensorOrientation270AndPivot_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( context, cameraCharacteristics, pivot, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( context, cameraCharacteristics, pivot, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenOrientation0AndPivot_areInverseTransformations() { val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_0_DEGREES, pivot, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_0_DEGREES, pivot, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenOrientation90AndPivot_areInverseTransformations() { val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_90_DEGREES, pivot, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_90_DEGREES, pivot, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenOrientation180AndPivot_areInverseTransformations() { val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_180_DEGREES, pivot, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_180_DEGREES, pivot, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenOrientation270AndPivot_areInverseTransformations() { val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_270_DEGREES, pivot, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_270_DEGREES, pivot, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenOrientationUnknownAndPivot_areInverseTransformations() { val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_UNKNOWN, pivot, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_UNKNOWN, pivot, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenRotationAndPivot_areInverseTransformations() { val randomizer = UniformRandomizer() val angle = Math.toRadians( randomizer.nextDouble( MIN_ROTATION_ANGLE_DEGREES, MAX_ROTATION_ANGLE_DEGREES ) ) val rotation = Rotation2D(angle) val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = ProjectiveTransformation2D() OrientationHelper.toViewCoordinatesTransformation( rotation, pivot, toViewResult ) val fromViewResult = ProjectiveTransformation2D() OrientationHelper.fromViewCoordinatesTransformation( rotation, pivot, fromViewResult ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraIdSensorOrientation0AndIntrinsicsNew_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( context, CAMERA_ID, intrinsics ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( context, CAMERA_ID, intrinsics ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraIdSensorOrientation90AndIntrinsicsNew_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( context, CAMERA_ID, intrinsics ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( context, CAMERA_ID, intrinsics ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraIdSensorOrientation180AndIntrinsicsNew_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( context, CAMERA_ID, intrinsics ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( context, CAMERA_ID, intrinsics ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraIdSensorOrientation270AndIntrinsicsNew_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( context, CAMERA_ID, intrinsics ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( context, CAMERA_ID, intrinsics ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraCharacteristicsSensorOrientation0AndIntrinsicsNew_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( context, cameraCharacteristics, intrinsics ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( context, cameraCharacteristics, intrinsics ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraCharacteristicsSensorOrientation90AndIntrinsicsNew_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( context, cameraCharacteristics, intrinsics ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( context, cameraCharacteristics, intrinsics ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraCharacteristicsSensorOrientation180AndIntrinsicsNew_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( context, cameraCharacteristics, intrinsics ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( context, cameraCharacteristics, intrinsics ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraCharacteristicsSensorOrientation270AndIntrinsicsNew_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( context, cameraCharacteristics, intrinsics ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( context, cameraCharacteristics, intrinsics ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenOrientation0AndIntrinsicsNew_areInverseTransformations() { val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_0_DEGREES, intrinsics ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_0_DEGREES, intrinsics ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenOrientation90AndIntrinsicsNew_areInverseTransformations() { val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_90_DEGREES, intrinsics ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_90_DEGREES, intrinsics ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenOrientation180AndIntrinsicsNew_areInverseTransformations() { val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_180_DEGREES, intrinsics ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_180_DEGREES, intrinsics ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenOrientation270AndIntrinsicsNew_areInverseTransformations() { val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_270_DEGREES, intrinsics ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_270_DEGREES, intrinsics ) // check toViewResult.t = toViewResult.t fromViewResult.t = fromViewResult.t toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenOrientationUnknownAndIntrinsicsNew_areInverseTransformations() { val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_UNKNOWN, intrinsics ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_UNKNOWN, intrinsics ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenRotationAndIntrinsicsNew_areInverseTransformations() { val randomizer = UniformRandomizer() val angle = Math.toRadians( randomizer.nextDouble( MIN_ROTATION_ANGLE_DEGREES, MAX_ROTATION_ANGLE_DEGREES ) ) val rotation = Rotation2D(angle) val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( rotation, intrinsics ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( rotation, intrinsics ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraIdSensorOrientation0AndPivotNew_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation(context, CAMERA_ID, pivot) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( context, CAMERA_ID, pivot ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraIdSensorOrientation90AndPivotNew_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation(context, CAMERA_ID, pivot) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( context, CAMERA_ID, pivot ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraIdSensorOrientation180AndPivotNew_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation(context, CAMERA_ID, pivot) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( context, CAMERA_ID, pivot ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraIdSensorOrientation270AndPivotNew_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation(context, CAMERA_ID, pivot) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( context, CAMERA_ID, pivot ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraCharacteristicsSensorOrientation0AndPivotNew_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( context, cameraCharacteristics, pivot ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( context, cameraCharacteristics, pivot ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraCharacteristicsSensorOrientation90AndPivotNew_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( context, cameraCharacteristics, pivot ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( context, cameraCharacteristics, pivot ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraCharacteristicsSensorOrientation180AndPivotNew_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( context, cameraCharacteristics, pivot ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( context, cameraCharacteristics, pivot ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenCameraCharacteristicsSensorOrientation270AndPivotNew_areInverseTransformations() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( context, cameraCharacteristics, pivot ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( context, cameraCharacteristics, pivot ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenOrientation0AndPivotNew_areInverseTransformations() { val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_0_DEGREES, pivot ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_0_DEGREES, pivot ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenOrientation90AndPivotNew_areInverseTransformations() { val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_90_DEGREES, pivot ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_90_DEGREES, pivot ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenOrientation180AndPivotNew_areInverseTransformations() { val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_180_DEGREES, pivot ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_180_DEGREES, pivot ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenOrientation270AndPivotNew_areInverseTransformations() { val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_270_DEGREES, pivot ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_270_DEGREES, pivot ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenOrientationUnknownAndPivotNew_areInverseTransformations() { val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_UNKNOWN, pivot ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( CameraToDisplayOrientation.ORIENTATION_UNKNOWN, pivot ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesTransformation_whenRotationAndPivotNew_areInverseTransformations() { val randomizer = UniformRandomizer() val angle = Math.toRadians( randomizer.nextDouble( MIN_ROTATION_ANGLE_DEGREES, MAX_ROTATION_ANGLE_DEGREES ) ) val rotation = Rotation2D(angle) val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val toViewResult = OrientationHelper.toViewCoordinatesTransformation( rotation, pivot ) val fromViewResult = OrientationHelper.fromViewCoordinatesTransformation( rotation, pivot ) // check toViewResult.normalize() fromViewResult.normalize() val invToViewResult = toViewResult.inverseAndReturnNew() as ProjectiveTransformation2D val invFromViewResult = fromViewResult.inverseAndReturnNew() as ProjectiveTransformation2D invToViewResult.normalize() invFromViewResult.normalize() assertTrue(toViewResult.t.equals(invFromViewResult.t, SMALL_ABSOLUTE_ERROR)) assertTrue(fromViewResult.t.equals(invToViewResult.t, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraIdSensorOrientation0_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera(context, CAMERA_ID, camera, viewCamera) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera(context, CAMERA_ID, viewCamera, openGlCamera) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraIdSensorOrientation90_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera(context, CAMERA_ID, camera, viewCamera) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera(context, CAMERA_ID, viewCamera, openGlCamera) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraIdSensorOrientation180_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera(context, CAMERA_ID, camera, viewCamera) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera(context, CAMERA_ID, viewCamera, openGlCamera) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraIdSensorOrientation270_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera(context, CAMERA_ID, camera, viewCamera) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera(context, CAMERA_ID, viewCamera, openGlCamera) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraCharacteristicsOrientation0_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera( context, cameraCharacteristics, camera, viewCamera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( context, cameraCharacteristics, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraCharacteristicsOrientation90_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera( context, cameraCharacteristics, camera, viewCamera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( context, cameraCharacteristics, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraCharacteristicsOrientation180_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera( context, cameraCharacteristics, camera, viewCamera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( context, cameraCharacteristics, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraCharacteristicsOrientation270_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera( context, cameraCharacteristics, camera, viewCamera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( context, cameraCharacteristics, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenOrientation0_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_0_DEGREES, camera, viewCamera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_0_DEGREES, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenOrientation90_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_90_DEGREES, camera, viewCamera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_90_DEGREES, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenOrientation180_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_180_DEGREES, camera, viewCamera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_180_DEGREES, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenOrientation270_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_270_DEGREES, camera, viewCamera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_270_DEGREES, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenOrientationUnknown_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_UNKNOWN, camera, viewCamera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_UNKNOWN, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenRotation_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val randomizer = UniformRandomizer() val angle = Math.toRadians( randomizer.nextDouble( MIN_ROTATION_ANGLE_DEGREES, MAX_ROTATION_ANGLE_DEGREES ) ) val viewRotation = Rotation2D(angle) val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera( viewRotation, camera, viewCamera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( viewRotation, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraIdSensorOrientation0AndPivot_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera(context, CAMERA_ID, pivot, camera, viewCamera) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( context, CAMERA_ID, pivot, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraIdSensorOrientation90AndPivot_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera(context, CAMERA_ID, pivot, camera, viewCamera) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( context, CAMERA_ID, pivot, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraIdSensorOrientation180AndPivot_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera(context, CAMERA_ID, pivot, camera, viewCamera) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( context, CAMERA_ID, pivot, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraIdSensorOrientation270AndPivot_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera(context, CAMERA_ID, pivot, camera, viewCamera) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( context, CAMERA_ID, pivot, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraCharacteristicsOrientation0AndPivot_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera( context, cameraCharacteristics, pivot, camera, viewCamera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( context, cameraCharacteristics, pivot, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraCharacteristicsOrientation90AndPivot_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera( context, cameraCharacteristics, pivot, camera, viewCamera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( context, cameraCharacteristics, pivot, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraCharacteristicsOrientation180AndPivot_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera( context, cameraCharacteristics, pivot, camera, viewCamera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( context, cameraCharacteristics, pivot, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraCharacteristicsOrientation270AndPivot_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera( context, cameraCharacteristics, pivot, camera, viewCamera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( context, cameraCharacteristics, pivot, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenOrientation0AndPivot_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_0_DEGREES, pivot, camera, viewCamera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_0_DEGREES, pivot, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenOrientation90AndPivot_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_90_DEGREES, pivot, camera, viewCamera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_90_DEGREES, pivot, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenOrientation180AndPivot_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_180_DEGREES, pivot, camera, viewCamera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_180_DEGREES, pivot, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenOrientation270AndPivot_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_270_DEGREES, pivot, camera, viewCamera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_270_DEGREES, pivot, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenOrientationUnknownAndPivot_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_UNKNOWN, pivot, camera, viewCamera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_UNKNOWN, pivot, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenRotationAndPivot_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val angle = Math.toRadians( randomizer.nextDouble( MIN_ROTATION_ANGLE_DEGREES, MAX_ROTATION_ANGLE_DEGREES ) ) val viewRotation = Rotation2D(angle) val viewCamera = PinholeCamera() OrientationHelper.toViewCoordinatesCamera( viewRotation, pivot, camera, viewCamera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = PinholeCamera() OrientationHelper.fromViewCoordinatesCamera( viewRotation, pivot, viewCamera, openGlCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraIdSensorOrientation0New_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera(context, CAMERA_ID, camera) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera(context, CAMERA_ID, viewCamera) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraIdSensorOrientation90New_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera(context, CAMERA_ID, camera) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera(context, CAMERA_ID, viewCamera) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraIdSensorOrientation180New_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera(context, CAMERA_ID, camera) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera(context, CAMERA_ID, viewCamera) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraIdSensorOrientation270New_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera(context, CAMERA_ID, camera) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera(context, CAMERA_ID, viewCamera) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraCharacteristicsOrientation0New_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera( context, cameraCharacteristics, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( context, cameraCharacteristics, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraCharacteristicsOrientation90New_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera( context, cameraCharacteristics, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( context, cameraCharacteristics, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraCharacteristicsOrientation180New_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera( context, cameraCharacteristics, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( context, cameraCharacteristics, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraCharacteristicsOrientation270New_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera( context, cameraCharacteristics, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( context, cameraCharacteristics, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenOrientation0New_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_0_DEGREES, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_0_DEGREES, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenOrientation90New_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_90_DEGREES, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_90_DEGREES, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenOrientation180New_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_180_DEGREES, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_180_DEGREES, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenOrientation270New_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_270_DEGREES, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_270_DEGREES, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenOrientationUnknownNew_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_UNKNOWN, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_UNKNOWN, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenRotationNew_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val randomizer = UniformRandomizer() val angle = Math.toRadians( randomizer.nextDouble( MIN_ROTATION_ANGLE_DEGREES, MAX_ROTATION_ANGLE_DEGREES ) ) val viewRotation = Rotation2D(angle) val viewCamera = OrientationHelper.toViewCoordinatesCamera( viewRotation, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( viewRotation, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraIdSensorOrientation0PivotNew_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera(context, CAMERA_ID, pivot, camera) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( context, CAMERA_ID, pivot, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraIdSensorOrientation90PivotNew_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera(context, CAMERA_ID, pivot, camera) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( context, CAMERA_ID, pivot, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraIdSensorOrientation180PivotNew_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera(context, CAMERA_ID, pivot, camera) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( context, CAMERA_ID, pivot, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraIdSensorOrientation270PivotNew_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val cameraManager = mockk<CameraManager>() every { cameraManager.getCameraCharacteristics(any()) }.returns(cameraCharacteristics) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.getSystemService(Context.CAMERA_SERVICE) }.returns(cameraManager) every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera(context, CAMERA_ID, pivot, camera) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( context, CAMERA_ID, pivot, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraCharacteristicsOrientation0PivotNew_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(0) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera( context, cameraCharacteristics, pivot, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( context, cameraCharacteristics, pivot, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraCharacteristicsOrientation90PivotNew_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(90) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera( context, cameraCharacteristics, pivot, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( context, cameraCharacteristics, pivot, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraCharacteristicsOrientation180PivotNew_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(180) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera( context, cameraCharacteristics, pivot, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( context, cameraCharacteristics, pivot, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenCameraCharacteristicsOrientation270PivotNew_areInverseCameras() { val cameraCharacteristics = mockk<CameraCharacteristics>() every { cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) }.returns(270) val display = mockk<Display>() every { display.rotation }.returns(Surface.ROTATION_0) val context = mockk<Context>() every { context.display }.returns(display) // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera( context, cameraCharacteristics, pivot, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( context, cameraCharacteristics, pivot, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenOrientation0PivotNew_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_0_DEGREES, pivot, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_0_DEGREES, pivot, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenOrientation90PivotNew_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_90_DEGREES, pivot, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_90_DEGREES, pivot, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenOrientation180PivotNew_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_180_DEGREES, pivot, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_180_DEGREES, pivot, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenOrientation270PivotNew_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_270_DEGREES, pivot, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_270_DEGREES, pivot, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenOrientationUnknownPivotNew_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) // convert val viewCamera = OrientationHelper.toViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_UNKNOWN, pivot, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( CameraToDisplayOrientation.ORIENTATION_UNKNOWN, pivot, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun toAndFromViewCoordinatesCamera_whenRotationPivotNew_areInverseCameras() { // camera with no orientation val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // convert val randomizer = UniformRandomizer() val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val angle = Math.toRadians( randomizer.nextDouble( MIN_ROTATION_ANGLE_DEGREES, MAX_ROTATION_ANGLE_DEGREES ) ) val viewRotation = Rotation2D(angle) val viewCamera = OrientationHelper.toViewCoordinatesCamera( viewRotation, pivot, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() val openGlCamera = OrientationHelper.fromViewCoordinatesCamera( viewRotation, pivot, viewCamera ) openGlCamera.normalize() openGlCamera.fixCameraSign() openGlCamera.decompose() assertTrue(openGlCamera.internalMatrix.equals(camera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun transformCamera_returnsExpectedCamera() { val randomizer = UniformRandomizer() val angle = Math.toRadians( randomizer.nextDouble( MIN_ROTATION_ANGLE_DEGREES, MAX_ROTATION_ANGLE_DEGREES ) ) val viewRotation = Rotation2D(angle) val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val transformation = OrientationHelper.toViewCoordinatesTransformation( viewRotation, pivot ) val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // transform camera val result = PinholeCamera() OrientationHelper.transformCamera(transformation, camera, result) val viewCamera = OrientationHelper.toViewCoordinatesCamera( viewRotation, pivot, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() result.normalize() result.fixCameraSign() result.decompose() assertTrue(result.internalMatrix.equals(viewCamera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun transformCamera_whenNewInstance_returnsExpectedCamera() { val randomizer = UniformRandomizer() val angle = Math.toRadians( randomizer.nextDouble( MIN_ROTATION_ANGLE_DEGREES, MAX_ROTATION_ANGLE_DEGREES ) ) val viewRotation = Rotation2D(angle) val pivot = InhomogeneousPoint2D( randomizer.nextDouble(MIN_POS, MAX_POS), randomizer.nextDouble(MIN_POS, MAX_POS) ) val transformation = OrientationHelper.toViewCoordinatesTransformation( viewRotation, pivot ) val projectionMatrix = createProjectionMatrix() val intrinsics = OpenGlToCameraHelper.computePinholeCameraIntrinsicsAndReturnNew( projectionMatrix, WIDTH, HEIGHT ) val rotation = createRotation() val center = createCenter() val camera = PinholeCamera(intrinsics, rotation, center) camera.normalize() camera.fixCameraSign() camera.decompose() // transform camera val result = OrientationHelper.transformCamera(transformation, camera) val viewCamera = OrientationHelper.toViewCoordinatesCamera( viewRotation, pivot, camera ) viewCamera.normalize() viewCamera.fixCameraSign() viewCamera.decompose() result.normalize() result.fixCameraSign() result.decompose() assertTrue(result.internalMatrix.equals(viewCamera.internalMatrix, SMALL_ABSOLUTE_ERROR)) } @Test fun convertOrientationDegreesToEnum() { val name = "convertOrientationDegreesToEnum" assertEquals( CameraToDisplayOrientation.ORIENTATION_0_DEGREES, OrientationHelper.callPrivateStaticFunc(name, 0) ) assertEquals( CameraToDisplayOrientation.ORIENTATION_90_DEGREES, OrientationHelper.callPrivateStaticFunc(name, 90) ) assertEquals( CameraToDisplayOrientation.ORIENTATION_180_DEGREES, OrientationHelper.callPrivateStaticFunc(name, 180) ) assertEquals( CameraToDisplayOrientation.ORIENTATION_270_DEGREES, OrientationHelper.callPrivateStaticFunc(name, 270) ) assertEquals( CameraToDisplayOrientation.ORIENTATION_UNKNOWN, OrientationHelper.callPrivateStaticFunc(name, 45) ) } @Test fun convertOrientationEnumToRadians() { val name = "convertOrientationEnumToRadians" assertEquals( 0.0, OrientationHelper.callPrivateStaticFunc( name, CameraToDisplayOrientation.ORIENTATION_0_DEGREES ) as Double, 0.0 ) assertEquals( Math.PI / 2.0, OrientationHelper.callPrivateStaticFunc( name, CameraToDisplayOrientation.ORIENTATION_90_DEGREES ) as Double, 0.0 ) assertEquals( Math.PI, OrientationHelper.callPrivateStaticFunc( name, CameraToDisplayOrientation.ORIENTATION_180_DEGREES ) as Double, 0.0 ) assertEquals( 3.0 * Math.PI / 2.0, OrientationHelper.callPrivateStaticFunc( name, CameraToDisplayOrientation.ORIENTATION_270_DEGREES ) as Double, 0.0 ) assertNull( OrientationHelper.callPrivateStaticFunc( name, CameraToDisplayOrientation.ORIENTATION_UNKNOWN ) ) } @Test fun convertOrientationEnumToRotation() { val name = "convertOrientationEnumToRotation" var rotation: Rotation2D? = OrientationHelper.callPrivateStaticFunc( name, CameraToDisplayOrientation.ORIENTATION_0_DEGREES ) as Rotation2D? requireNotNull(rotation) assertEquals(0.0, rotation.theta, 0.0) rotation = OrientationHelper.callPrivateStaticFunc( name, CameraToDisplayOrientation.ORIENTATION_90_DEGREES ) as Rotation2D? requireNotNull(rotation) assertEquals(Math.PI / 2.0, rotation.theta, 0.0) rotation = OrientationHelper.callPrivateStaticFunc( name, CameraToDisplayOrientation.ORIENTATION_180_DEGREES ) as Rotation2D? requireNotNull(rotation) assertEquals(Math.PI, rotation.theta, 0.0) rotation = OrientationHelper.callPrivateStaticFunc( name, CameraToDisplayOrientation.ORIENTATION_270_DEGREES ) as Rotation2D? requireNotNull(rotation) assertEquals(3.0 * Math.PI / 2.0, rotation.theta, 0.0) rotation = OrientationHelper.callPrivateStaticFunc( name, CameraToDisplayOrientation.ORIENTATION_UNKNOWN ) as Rotation2D? assertNull(rotation) } private companion object { const val CAMERA_ID = "1" const val WIDTH = 480 const val HEIGHT = 640 const val MIN_ROTATION_ANGLE_DEGREES = -45.0 const val MAX_ROTATION_ANGLE_DEGREES = 45.0 const val MIN_POS = -50.0 const val MAX_POS = 50.0 const val SMALL_ABSOLUTE_ERROR = 1e-6 private fun createProjectionMatrix(): FloatArray { // Pixel 2 device has the following projection matrix // [2.8693345 0.0 -0.004545755 0.0 ] // [0.0 1.5806589 0.009158132 0.0 ] // [0.0 0.0 -1.002002 -0.2002002 ] // [0.0 0.0 -1.0 0.0 ] // android.opengl.Matrix defines values column-wise return floatArrayOf( 2.8693345f, 0.0f, 0.0f, 0.0f, 0.0f, 1.5806589f, 0.0f, 0.0f, -0.004545755f, 0.009158132f, -1.002002f, -1.0f, 0.0f, 0.0f, -0.2002002f, 0.0f ) } private fun createRotation(): Rotation3D { val randomizer = UniformRandomizer() val roll = Math.toRadians( randomizer.nextDouble( MIN_ROTATION_ANGLE_DEGREES, MAX_ROTATION_ANGLE_DEGREES ) ) val pitch = Math.toRadians( randomizer.nextDouble( MIN_ROTATION_ANGLE_DEGREES, MAX_ROTATION_ANGLE_DEGREES ) ) val yaw = Math.toRadians( randomizer.nextDouble( MIN_ROTATION_ANGLE_DEGREES, MAX_ROTATION_ANGLE_DEGREES ) ) return Quaternion(roll, pitch, yaw) } private fun createCenter(): Point3D { val randomizer = UniformRandomizer() val x = randomizer.nextDouble( MIN_POS, MAX_POS ) val y = randomizer.nextDouble( MIN_POS, MAX_POS ) val z = randomizer.nextDouble( MIN_POS, MAX_POS ) return InhomogeneousPoint3D(x, y, z) } } }
0
Kotlin
0
0
c79b243df5bc6a69c70f2baace69663427843007
269,095
irurueta-android-glutils
Apache License 2.0
content-types/content-types-core-services/src/test/kotlin/org/orkg/contenttypes/domain/actions/templates/TemplateTargetClassValidatorUnitTest.kt
TIBHannover
197,416,205
false
{"Kotlin": 4974568, "Cypher": 219418, "Python": 4881, "Shell": 2767, "Groovy": 1936, "HTML": 240}
package org.orkg.contenttypes.domain.actions.templates import io.kotest.matchers.shouldBe import io.mockk.clearAllMocks import io.mockk.confirmVerified import io.mockk.every import io.mockk.mockk import io.mockk.verify import java.util.* import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertDoesNotThrow import org.junit.jupiter.api.assertThrows import org.orkg.common.PageRequests import org.orkg.common.ThingId import org.orkg.contenttypes.domain.TemplateAlreadyExistsForClass import org.orkg.graph.domain.ClassNotFound import org.orkg.graph.domain.Classes import org.orkg.graph.domain.Predicates import org.orkg.graph.output.ClassRepository import org.orkg.graph.output.StatementRepository import org.orkg.graph.testing.fixtures.createClass import org.orkg.graph.testing.fixtures.createPredicate import org.orkg.graph.testing.fixtures.createResource import org.orkg.graph.testing.fixtures.createStatement import org.orkg.testing.pageOf class TemplateTargetClassValidatorUnitTest { private val classRepository: ClassRepository = mockk() private val statementRepository: StatementRepository = mockk() private val templateTargetClassValidator = TemplateTargetClassValidator<ThingId?, ThingId?>(classRepository, statementRepository, { it }, { it }) @BeforeEach fun resetState() { clearAllMocks() } @AfterEach fun verifyMocks() { confirmVerified(classRepository, statementRepository) } @Test fun `Given a target class id, when validating, it returns success`() { val targetClass = ThingId("targetClass") every { classRepository.findById(targetClass) } returns Optional.of(createClass()) every { statementRepository.findAll( subjectClasses = setOf(Classes.nodeShape), predicateId = Predicates.shTargetClass, objectId = targetClass, pageable = PageRequests.SINGLE ) } returns pageOf() assertDoesNotThrow { templateTargetClassValidator(targetClass, null) } verify(exactly = 1) { classRepository.findById(targetClass) } verify(exactly = 1) { statementRepository.findAll( subjectClasses = setOf(Classes.nodeShape), predicateId = Predicates.shTargetClass, objectId = targetClass, pageable = PageRequests.SINGLE ) } } @Test fun `Given a target class id, when null, it returns success`() { assertDoesNotThrow { templateTargetClassValidator(null, null) } } @Test fun `Given a target class id, when target class does not exist, it throws an exception`() { val targetClass = ThingId("targetClass") every { classRepository.findById(targetClass) } returns Optional.empty() assertThrows<ClassNotFound> { templateTargetClassValidator(targetClass, null) } verify(exactly = 1) { classRepository.findById(targetClass) } } @Test fun `Given a target class id, when target class already has a template, it throws an exception`() { val targetClassId = ThingId("targetClass") val otherTemplate = createResource() val targetClass = createClass(targetClassId) val exception = TemplateAlreadyExistsForClass(targetClassId, otherTemplate.id) every { classRepository.findById(targetClassId) } returns Optional.of(targetClass) every { statementRepository.findAll( subjectClasses = setOf(Classes.nodeShape), predicateId = Predicates.shTargetClass, objectId = targetClassId, pageable = PageRequests.SINGLE ) } returns pageOf( createStatement( subject = otherTemplate, predicate = createPredicate(Predicates.shTargetClass), `object` = targetClass ) ) assertThrows<TemplateAlreadyExistsForClass> { templateTargetClassValidator(targetClassId, null) } shouldBe exception verify(exactly = 1) { classRepository.findById(targetClassId) } verify(exactly = 1) { statementRepository.findAll( subjectClasses = setOf(Classes.nodeShape), predicateId = Predicates.shTargetClass, objectId = targetClassId, pageable = PageRequests.SINGLE ) } } @Test fun `Given a target class id, when it is identical to old target class, it returns success`() { val targetClass = ThingId("targetClass") assertDoesNotThrow { templateTargetClassValidator(targetClass, targetClass) } } }
0
Kotlin
0
4
80f66b3b43fa199dedeffc4732c2d82720699ee7
4,793
orkg-backend
MIT License
app/src/main/java/com/lambdaschool/hackathon_portal/ui/fragments/detail/ProjectFragment.kt
BloomTech-Labs
227,462,757
false
{"Kotlin": 158652}
package com.lambdaschool.hackathon_portal.ui.fragments.detail import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import androidx.cardview.widget.CardView import androidx.core.view.isVisible import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.lambdaschool.hackathon_portal.R import com.lambdaschool.hackathon_portal.model.ProjectHackathon import com.lambdaschool.hackathon_portal.model.Participant import com.lambdaschool.hackathon_portal.ui.fragments.BaseFragment import com.lambdaschool.hackathon_portal.util.visGone import com.lambdaschool.hackathon_portal.util.visVisible import kotlinx.android.synthetic.main.fragment_project.* import kotlinx.android.synthetic.main.project_list_item_view.view.* class ProjectFragment : BaseFragment() { private lateinit var detailViewModel: DetailViewModel private var organizerId: Int? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) detailViewModel = ViewModelProvider(this, viewModelProviderFactory) .get(DetailViewModel::class.java) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_project, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) fragment_project_recycler_view.apply { setHasFixedSize(false) layoutManager = LinearLayoutManager(context) adapter = ProjectListAdapter(mutableListOf<ProjectHackathon>()) } var projectId: Int? = null detailViewModel.currentHackathon.observe(this, Observer { it?.let { hackathon -> organizerId = hackathon.organizer_id initApproveButton() hackathon.projects?.let { projectList -> fragment_project_recycler_view.adapter = ProjectListAdapter(projectList .filter { project -> project.is_approved!! }.toMutableList()) } hackathon.id?.let { hackathonId -> projectId = hackathonId } } }) button_fragment_project_create_project.setOnClickListener { if (projectId != null) { val bundle = Bundle() projectId?.let { bundle.putInt("hackathon_id", it) } navController.navigate(R.id.nav_create_project, bundle) } } } inner class ProjectListAdapter(private val teams: MutableList<ProjectHackathon>): RecyclerView.Adapter<ProjectListAdapter.ViewHolder>() { lateinit var context: Context inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val nameView: TextView = view.text_view_team_name val participantsView: TextView = view.text_view_team_participants val parentView: CardView = view.parent_card_view val detailView: TextView = view.text_view_project_details val linearLayout: LinearLayout = view.linear_layout_list_members } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { context = parent.context val view = LayoutInflater.from(parent.context) .inflate(R.layout.project_list_item_view, parent, false) return ViewHolder(view) } override fun getItemCount(): Int = teams.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { val data = teams[position] var hasBeenExpanded = false holder.nameView.text = data.project_title holder.participantsView.text = " ${data.participants?.size.toString()}" holder.linearLayout.visGone() holder.parentView.setOnClickListener { when { !holder.linearLayout.isVisible && !hasBeenExpanded -> { data.participants?.forEach { holder.linearLayout.addView(createTeamMemberViews(it)) } holder.linearLayout.visVisible() hasBeenExpanded = true } !holder.linearLayout.isVisible && hasBeenExpanded -> { holder.linearLayout.visVisible() } holder.linearLayout.isVisible -> { holder.linearLayout.visGone() } } } holder.detailView.setOnClickListener { val bundle = Bundle() bundle.putInt("project_id", data.project_id) navController.navigate(R.id.nav_project_details, bundle) } } } @Suppress("DEPRECATION") private fun createTeamMemberViews(participant: Participant): LinearLayout { val linearLayout = LinearLayout(this.context) val usernameTextView = TextView(this.context) val roleTextView = TextView(this.context) val paddingAll = 8 usernameTextView.text = participant.username usernameTextView.setTextColor(resources.getColor(R.color.colorAccentLight)) roleTextView.text = participant.developer_role roleTextView.setTextColor(resources.getColor(R.color.colorAccentLight)) linearLayout.orientation = LinearLayout.VERTICAL linearLayout.addView(usernameTextView) linearLayout.addView(roleTextView) linearLayout.setPadding(paddingAll, paddingAll, paddingAll, paddingAll) return linearLayout } private fun initApproveButton() { if (organizerId == detailViewModel.getCurrentUserId()) { button_fragment_project_all_projects.visibility = View.VISIBLE button_fragment_project_all_projects.setOnClickListener { navController.navigate(R.id.approveProjectFragment) } } } }
4
Kotlin
0
0
d8bca01bfd6453f623b807c58f57b89c8bc9ca86
6,411
hackathon-portal-android
MIT License
app/src/main/java/com/otsembo/farmersfirst/ui/components/AppTexts.kt
otsembo
763,582,014
false
{"Kotlin": 251482}
package com.otsembo.farmersfirst.ui.components import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.withStyle @Composable fun AppHeading( modifier: Modifier = Modifier, text: String = "Popular", ) { Text( modifier = modifier, text = buildAnnotatedString { withStyle( SpanStyle( brush = Brush.linearGradient( colors = listOf( MaterialTheme.colorScheme.primary, MaterialTheme.colorScheme.secondary, MaterialTheme.colorScheme.tertiary, ), ), ), ) { append(text) } }, style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold, ) }
0
Kotlin
0
0
5c74fa9163d77354dc5373dd31bcd4889bf9fc5e
1,359
FarmersFirst
MIT License
generators/app/templates/ErrorCode.kt
apachesep
130,507,965
true
{"JavaScript": 94734, "Kotlin": 74607, "Vue": 34859, "CSS": 9765, "HTML": 5735}
package <%= package %> /** * Contains all error codes * @author martinlabs CRUD generator */ object ErrorCode { val INVALID_LOGIN = 33 }
0
JavaScript
0
0
f808d0c8582acec10d5e8a44e6f1fad630388593
151
generator-martinlabs
Apache License 2.0
src/testData/jvm/expression/operatorOverload/operatorOverload0/target/Target.kt
XYZboom
767,934,164
false
{"Kotlin": 1314423, "Java": 30284}
package target class Target { /*<target>*/operator fun plus(target: Target) { }/*<target/>*/ }
0
Kotlin
1
0
4dffca923b558f54c246c451ffcf43cb366fd754
104
psi-reference-extractor
Apache License 2.0
src/testData/jvm/expression/operatorOverload/operatorOverload0/target/Target.kt
XYZboom
767,934,164
false
{"Kotlin": 1314423, "Java": 30284}
package target class Target { /*<target>*/operator fun plus(target: Target) { }/*<target/>*/ }
0
Kotlin
1
0
4dffca923b558f54c246c451ffcf43cb366fd754
104
psi-reference-extractor
Apache License 2.0
ProfileService/src/test/kotlin/com/github/saboteur/beeline/profileservice/service/ProfileServiceDataProvider.kt
insotriplesix
256,169,374
false
null
package com.github.saboteur.beeline.profileservice.service import com.github.saboteur.beeline.profileservice.config.properties.RestProperties import com.github.saboteur.beeline.profileservice.dto.ProfileDto import com.github.saboteur.beeline.profileservice.dto.external.randomuser.RandomUserNameDto import com.github.saboteur.beeline.profileservice.dto.external.randomuser.RandomUserProfileDto import com.github.saboteur.beeline.profileservice.dto.external.randomuser.RandomUserResultDto import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.ArgumentsProvider import java.util.stream.Stream class ProfileServiceDataProvider { class GetProfileWithoutCallerId : ArgumentsProvider { override fun provideArguments(extensionContext: ExtensionContext?): Stream<out Arguments> { val providedProfile = ProfileDto( ctn = "TEST", callerId = "", name = "Durov Super", email = "[email protected]" ) val providedRandomUserProfileDto = RandomUserProfileDto( results = listOf( RandomUserResultDto( gender = null, name = RandomUserNameDto( title = "Mr.", first = "Super", last = "Durov" ), email = "[email protected]" ) ), info = null, error = null ) val providedRestProperties = RestProperties( externalServiceUrl = "externalServiceUrl", externalServiceName = "randomuser", fields = fields ) val providedReqUrl = StringBuilder() .append(providedRestProperties.externalServiceUrl) .append(apiSuffix) .append("TEST") .append(incSuffix) .append(providedRestProperties.fields) .toString() val arguments = Arguments.of( providedProfile, providedRandomUserProfileDto, providedRestProperties, providedReqUrl ) return Stream.of(arguments) } } class GetProfileWithCallerId : ArgumentsProvider { override fun provideArguments(extensionContext: ExtensionContext?): Stream<out Arguments> { val providedProfile = ProfileDto( ctn = "1234567890", callerId = exampleId, name = "Durov Pavel", email = "[email protected]" ) val providedRandomUserProfileDto = RandomUserProfileDto( results = listOf( RandomUserResultDto( gender = "M", name = RandomUserNameDto( title = "Mr.", first = "Pavel", last = "Durov" ), email = "[email protected]" ) ), info = null, error = null ) val providedCallerId = exampleId val providedRestProperties = RestProperties( externalServiceUrl = "externalServiceUrl", externalServiceName = "randomuser", fields = fields ) val providedReqUrl = StringBuilder() .append(providedRestProperties.externalServiceUrl) .append(apiSuffix) .append("1234567890") .append(incSuffix) .append(providedRestProperties.fields) .toString() val arguments = Arguments.of( providedProfile, providedRandomUserProfileDto, providedCallerId, providedRestProperties, providedReqUrl ) return Stream.of(arguments) } } class GetProfileWithError : ArgumentsProvider { override fun provideArguments(extensionContext: ExtensionContext?): Stream<out Arguments> { val providedProfile = ProfileDto( ctn = "1234567890", callerId = exampleId, name = "", email = "" ) val providedRandomUserProfileDto = RandomUserProfileDto( results = null, info = null, error = "This is error! Error?! THIS IS TEST CASE!!!!111" ) val providedCallerId = exampleId val providedRestProperties = RestProperties( externalServiceUrl = "externalServiceUrl", externalServiceName = "randomuser", fields = fields ) val providedReqUrl = StringBuilder() .append(providedRestProperties.externalServiceUrl) .append(apiSuffix) .append("1234567890") .append(incSuffix) .append(providedRestProperties.fields) .toString() val arguments = Arguments.of( providedProfile, providedRandomUserProfileDto, providedCallerId, providedRestProperties, providedReqUrl ) return Stream.of(arguments) } } class GetProfileWithUnknownType : ArgumentsProvider { override fun provideArguments(extensionContext: ExtensionContext?): Stream<out Arguments> { val providedProfile = ProfileDto( ctn = "TEST", callerId = "", name = "", email = "" ) return Stream.of(Arguments.of(providedProfile)) } } class GetProfileWhenExceptionThrown : ArgumentsProvider { override fun provideArguments(extensionContext: ExtensionContext?): Stream<out Arguments> { val providedProfile = ProfileDto( ctn = "TEST", callerId = "", name = "", email = "" ) val providedRestProperties = RestProperties( externalServiceUrl = "invalidUrl", externalServiceName = "randomuser", fields = "gender" ) val providedReqUrl = StringBuilder() .append(providedRestProperties.externalServiceUrl) .append(apiSuffix) .append("TEST") .append(incSuffix) .append(providedRestProperties.fields) .toString() return Stream.of(Arguments.of(providedProfile, providedRestProperties, providedReqUrl)) } } companion object { const val exampleId = "03e17537-30de-4598-a816-108945fa68b4" const val apiSuffix = "/api/?phone=" const val incSuffix = "&inc=" const val fields = "name,email" } }
0
Kotlin
0
1
1266d45fe626d43daa302c69380ced87fcd8fcef
7,409
beeline-task
MIT License
core/src/main/kotlin/com/tea505/teaplanner/core/geometry/Angle.kt
Tea505
802,756,909
false
{"Kotlin": 39864}
package com.tea505.teaplanner.core.geometry import kotlin.math.PI object Angle { private const val TAU = PI * 2 /** * Returns [angle] clamped to `[0, 2pi]`. * * @param angle angle measure in radians */ @JvmStatic fun norm(angle: Double): Double { var modifiedAngle = angle % TAU modifiedAngle = (modifiedAngle + TAU) % TAU return modifiedAngle } /** * Returns [angleDelta] clamped to `[-pi, pi]`. * * @param angleDelta angle delta in radians */ @JvmStatic fun normDelta(angleDelta: Double): Double { var modifiedAngleDelta = norm(angleDelta) if (modifiedAngleDelta > PI) { modifiedAngleDelta -= TAU } return modifiedAngleDelta } // REMEMBER IF USING A REGULAR SERVO UR RANGE IS 0 TO 180 DEGREES. // HOWEVER, A SMART REV SERVO'S RANGE IS 0 to 270 DEGREES. // Despite the servo configured the positional range will always be 0 to 1. /** * Convert degrees to servo position (0 to 1 range) */ fun degreesToServoPosition(degrees: Double): Double { return degrees / 180.0 } /** * Convert radians to servo position (0 to 1 range) */ fun radiansToServoPosition(radians: Double): Double { return radians / PI } }
0
Kotlin
0
0
59b79a9536ac18783d99e4876f33ab4786014e10
1,330
TeaLeafPlanner
MIT License
features/charts/src/main/java/com/igorvd/bitcoincharts/features/charts/domain/repository/BitcoinChartRepository.kt
igorvilela28
368,578,315
false
null
package com.igorvd.bitcoincharts.features.charts.domain.repository import com.igorvd.bitcoincharts.features.charts.domain.model.BitcoinMetricScreen import com.igorvd.bitcoincharts.features.charts.domain.model.BitcoinStatsHomeScreen import com.igorvd.bitcoincharts.features.charts.domain.model.ChartType interface BitcoinChartRepository { suspend fun getBitcoinStatsHomeScreen(): BitcoinStatsHomeScreen suspend fun getBitcoinMetricScreen(chartType: ChartType): BitcoinMetricScreen }
0
Kotlin
1
2
87282e175c612e2c0af7f21c102a1b8d407ea6b3
492
bitcoin-charts
The Unlicense
multik-core/src/nativeMain/kotlin/org/jetbrains/kotlinx/multik/ndarray/complex/ComplexDouble.native.kt
Kotlin
265,785,552
false
{"Kotlin": 1233813, "C++": 95317, "C": 8142, "CMake": 6406}
@file:OptIn(ExperimentalForeignApi::class) package org.jetbrains.kotlinx.multik.ndarray.complex import kotlinx.cinterop.ExperimentalForeignApi import kotlinx.cinterop.Vector128 import kotlinx.cinterop.vectorOf /** * Creates a [ComplexDouble] with the given real and imaginary values in floating-point format. * * @param re the real value of the complex number in double format. * @param im the imaginary value of the complex number in double format. */ public actual fun ComplexDouble(re: Double, im: Double): ComplexDouble { val reBits = re.toBits() val reHigherBits = (reBits shr 32).toInt() val reLowerBits = (reBits and 0xFFFFFFFFL).toInt() val imBits = im.toBits() val imHigherBits = (imBits shr 32).toInt() val imLowerBits = (imBits and 0xFFFFFFFFL).toInt() return NativeComplexDouble(vectorOf(reLowerBits, reHigherBits, imLowerBits, imHigherBits)) } /** * Creates a [ComplexDouble] with the given real and imaginary values in number format. * * @param re the real value of the complex number in number format. * @param im the imaginary value of the complex number in number format. */ public actual fun ComplexDouble(re: Number, im: Number): ComplexDouble = ComplexDouble(re.toDouble(), im.toDouble()) /** * Represents a complex number with double precision. * * @property re The real part of the complex number. * @property im The imaginary part of the complex number. */ public value class NativeComplexDouble internal constructor(private val vector: Vector128) : ComplexDouble { public override val re: Double get() = vector.getDoubleAt(0) public override val im: Double get() = vector.getDoubleAt(1) override fun eq(other: Any): Boolean = when { other is NativeComplexDouble && vector == other.vector -> true other is NativeComplexDouble -> re == other.re && im == other.im else -> false } override fun hash(): Int = 31 * vector.hashCode() override fun toString(): String = "$re+($im)i" }
59
Kotlin
39
636
b121652b8d151782d5770c5e1505864ac0307a5b
2,042
multik
Apache License 2.0
QRCodeStore/app/src/main/java/com/example/qrcodestore/UserHomeActivity.kt
dpb3k
856,705,776
false
{"Kotlin": 52125, "Python": 1268}
package com.example.qrcodestore import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.Toast import androidx.annotation.OptIn import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.camera.core.ExperimentalGetImage import com.google.firebase.auth.FirebaseAuth import com.google.mlkit.vision.barcode.BarcodeScanning import com.google.mlkit.vision.barcode.common.Barcode import com.google.mlkit.vision.common.InputImage import com.google.mlkit.vision.barcode.BarcodeScannerOptions import androidx.appcompat.app.ActionBar class UserHomeActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_user_home) supportActionBar?.title = "QR-Code Store - Home" } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.user_home, menu) return true } fun scanQr(view: View) { // Start the scanning activity try { val intent = Intent(this, ScanBarcodeActivity::class.java) startActivity(intent) } catch (e: Exception) { Toast.makeText(this, "Failed to open scanner: ${e.message}", Toast.LENGTH_LONG).show() } } fun viewCartDetails(view: View) { try { val intent = Intent(this, ProductCartListActivity::class.java) startActivity(intent) } catch (e : Exception) { Toast.makeText(this, "Failed to open cart details: ${e.message}", Toast.LENGTH_LONG).show() } } fun logout(view: View) { // Sign out from Firebase FirebaseAuth.getInstance().signOut() // Optionally clear any other stored data // Redirect back to MainActivity val intent = Intent(this, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK startActivity(intent) finish() } }
0
Kotlin
0
0
68d9547e4b9a30f2aaa36d5d6aa3d95b0c65ea6d
2,131
qrcodestore
MIT License
oofqrreader/src/main/java/com/github/soranakk/oofqrreader/detector/QRCodeDetector.kt
shinmiy
344,734,034
true
{"Kotlin": 10539}
package com.github.soranakk.oofqrreader.detector import com.github.soranakk.oofqrreader.extension.erode import com.github.soranakk.oofqrreader.extension.findContours import com.github.soranakk.oofqrreader.extension.thresholdOTSU import com.github.soranakk.oofqrreader.model.ImageData import com.github.soranakk.oofqrreader.util.MatUtil import org.opencv.core.MatOfPoint import org.opencv.core.Rect import org.opencv.core.Size import org.opencv.imgproc.Imgproc class QRCodeDetector(private val settings: DetectionSettings = DetectionSettings()) { companion object { private const val erodeSizeWidth = 5.0 private const val erodeSizeHeight = 5.0 } data class DetectionSettings( val includeFullScreen: Boolean = false, val minSizeRate: Double = 0.01, val maxSizeRate: Double = 1.0 ) fun detectRectWhereQRExists(image: ImageData): List<Rect> { val imageSize = Size(image.width.toDouble(), image.height.toDouble()) return MatUtil.convertYuvToGray(image) .thresholdOTSU() .erode(Size(erodeSizeWidth, erodeSizeHeight)) .findContours() .boundingRect() .filterNot { it.isInvalid(imageSize, settings.minSizeRate, settings.maxSizeRate) } .let { if (settings.includeFullScreen) { it.toMutableList().apply { add(Rect(0, 0, image.width, image.height)) } } else it } .sortedBy { it.width * it.height } } private fun List<MatOfPoint>.boundingRect(): Iterable<Rect> { return this.map { point -> Imgproc.boundingRect(point).also { point.release() } } } private fun Rect.isInvalid(imageSize: Size, minSizeRate: Double, maxSizeRate: Double) = this.width < imageSize.minWidth(minSizeRate) || this.height < imageSize.minHeight(minSizeRate) || this.width > imageSize.maxWidth(maxSizeRate) || this.height > imageSize.maxHeight(maxSizeRate) private fun Size.minWidth(minSizeRate: Double) = (this.width * minSizeRate).toInt() private fun Size.minHeight(minSizeRate: Double) = (this.height * minSizeRate).toInt() private fun Size.maxWidth(maxSizeRate: Double) = (this.width * maxSizeRate).toInt() private fun Size.maxHeight(maxSizeRate: Double) = (this.height * maxSizeRate).toInt() }
0
null
0
0
c765f04cff85caac5ea91dffd135b3beb4bd8771
2,458
OutOfFocusQRReader
Apache License 2.0
examples/with-thirdparty/android/app/src/main/kotlin/com/supertokens/with_thirdparty/MainActivity.kt
supertokens
348,763,735
false
{"Dart": 205484, "JavaScript": 27248, "Shell": 16720, "HTML": 1549, "Dockerfile": 284}
package com.supertokens.with_thirdparty import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
5
Dart
10
14
4f63e3d9085b3cfc90e07ad1506ea5d8bd60a5aa
136
supertokens-flutter
Apache License 2.0
src/day08/Day08.kt
idle-code
572,642,410
false
{"Kotlin": 79612}
package day08 import readInput fun main() { fun visibilityHorizontally(input: List<List<Int>>, xRange: IntProgression, startVisibility: Int = -1): Array<BooleanArray> { val mask = Array(input.size) { BooleanArray(input[0].size) { false } } for (y in 0..input.lastIndex) { var previousTreeHeight = startVisibility for (x in xRange) { val currentHeight = input[y][x] if (currentHeight > previousTreeHeight) { mask[y][x] = true previousTreeHeight = currentHeight } } } return mask } fun visibilityVertically(input: List<List<Int>>, yRange: IntProgression, startVisibility: Int = -1): Array<BooleanArray> { val mask = Array(input.size) { BooleanArray(input[0].size) { false } } for (x in 0..input[0].lastIndex) { var previousTreeHeight = startVisibility for (y in yRange) { val currentHeight = input[y][x] if (currentHeight > previousTreeHeight) { mask[y][x] = true previousTreeHeight = currentHeight } } } return mask } fun mergeVisibilityMasks(vararg masks: Array<BooleanArray>): Array<BooleanArray> { val height = masks[0].lastIndex val width = masks[0][0].lastIndex val mergedMask = Array(height + 1) { BooleanArray(width + 1) { false } } for (m in masks) { for (y in 0..height) { for (x in 0..width) { mergedMask[y][x] = mergedMask[y][x] || m[y][x] } } } return mergedMask } fun countAllVisible(mask: Array<BooleanArray>): Int { val height = mask.lastIndex var visibleCount = 0 for (y in 0..height) { visibleCount += mask[y].count { it } } return visibleCount } fun calculateLineOfSightVertically( input: List<List<Int>>, x: Int, yRange: IntProgression, currentTreeHeight: Int ): Int { var visibleTreeCount = 0 for (yy in yRange) { if (input[yy][x] >= currentTreeHeight) { ++visibleTreeCount break } ++visibleTreeCount } return visibleTreeCount } fun calculateLineOfSightHorizontally( input: List<List<Int>>, xRange: IntProgression, y: Int, currentTreeHeight: Int ): Int { var visibleTreeCount = 0 for (xx in xRange) { if (input[y][xx] >= currentTreeHeight) { ++visibleTreeCount break } ++visibleTreeCount } return visibleTreeCount } fun calculateScenicScore(input: List<List<Int>>, x: Int, y: Int): Int { val currentTreeHeight = input[y][x] val visibleToLeft = calculateLineOfSightHorizontally(input, x-1 downTo 0, y, currentTreeHeight) val visibleToRight = calculateLineOfSightHorizontally(input, x+1..input[y].lastIndex, y, currentTreeHeight) val visibleToTop = calculateLineOfSightVertically(input, x, y - 1 downTo 0, currentTreeHeight) val visibleToBottom = calculateLineOfSightVertically(input, x, y+1 ..input.lastIndex, currentTreeHeight) return visibleToRight * visibleToLeft * visibleToBottom * visibleToTop } fun maxScenicScore(input: List<List<Int>>): Int { var maxScore = 0 for (y in 0..input.lastIndex) { for (x in 0..input[y].lastIndex) { val scenicScore = calculateScenicScore(input, y, x) if (scenicScore > maxScore) maxScore = scenicScore } } return maxScore } fun part1(rawInput: List<String>): Int { val input = rawInput.map { it.map { char -> char.digitToInt() } } val maskFromLeft = visibilityHorizontally(input, 0..input[0].lastIndex) val maskFromRight = visibilityHorizontally(input, input[0].lastIndex downTo 0) val maskFromTop = visibilityVertically(input, 0..input.lastIndex) val maskFromBottom = visibilityVertically(input, input.lastIndex downTo 0) val mergedMask = mergeVisibilityMasks(maskFromLeft, maskFromRight, maskFromTop, maskFromBottom) return countAllVisible(mergedMask) } fun part2(rawInput: List<String>): Int { val input = rawInput.map { it.map { char -> char.digitToInt() } } return maxScenicScore(input) } val testInput = readInput("sample_data", 8) println(part1(testInput)) check(part1(testInput) == 21) val mainInput = readInput("main_data", 8) println(part1(mainInput)) check(part1(mainInput) == 1798) println(part2(testInput)) check(part2(testInput) == 8) println(part2(mainInput)) check(part2(mainInput) == 259308) }
0
Kotlin
0
0
1b261c399a0a84c333cf16f1031b4b1f18b651c7
4,996
advent-of-code-2022
Apache License 2.0
data/src/main/java/dev/kibet/data/di/DataModule.kt
kibettheophilus
426,187,174
false
null
package dev.kibet.data import androidx.room.Room import dev.kibet.data.local.db.CharactersDatabase import dev.kibet.data.remote.api.CharactersApi import dev.kibet.data.repository.CharacterRepositoryImpl import dev.kibet.domain.repository.CharactersRepository import dev.kibet.domain.utils.Constants.BASE_URL import org.koin.android.ext.koin.androidApplication import org.koin.dsl.module import org.koin.dsl.single import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory val dataModule = module { single<CharactersRepository> { CharacterRepositoryImpl(get(), get()) } single { Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() .create(CharactersApi::class.java) } single { Room.databaseBuilder(androidApplication(), CharactersDatabase::class.java, "charaters.db") .fallbackToDestructiveMigration().build() } single { get<CharactersDatabase>().charactersDao() } }
0
Kotlin
0
11
0b1add4f489420668515faeaa7303ad079ec8aad
1,036
RickyandMorty
MIT License
app/src/main/java/give/away/good/deeds/ui/screens/main/messages/detail/ChatScreen.kt
hitesh-dhamshaniya
803,497,316
false
{"Kotlin": 273575}
package give.away.good.deeds.ui.screens.main.messages.detail import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Send import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.navigation.NavController import give.away.good.deeds.network.model.ChatGroupMessage import give.away.good.deeds.network.model.ChatMessage import give.away.good.deeds.network.model.User import give.away.good.deeds.ui.screens.app_common.ErrorStateView import give.away.good.deeds.ui.screens.app_common.NoInternetStateView import give.away.good.deeds.ui.screens.app_common.ProfileAvatar import give.away.good.deeds.ui.screens.main.setting.location.LoadingView import give.away.good.deeds.ui.screens.state.AppState import give.away.good.deeds.ui.screens.state.ErrorCause import org.koin.androidx.compose.koinViewModel @Composable fun MessageDetailScreen( groupId: String = "", navController: NavController?, viewModel: ChatViewModel = koinViewModel() ) { LaunchedEffect(Unit, block = { viewModel.fetchChatMessages(groupId) }) val uiState = viewModel.uiState.collectAsState() when (val state = uiState.value) { is AppState.Result<ChatGroupMessage> -> { val chatGroupMessage = state.data if (chatGroupMessage != null) { LaunchedEffect(Unit, block = { viewModel.setSnapshotListener(chatGroupMessage) }) } MessageDetailContainer( navController = navController, chatGroupMessage = chatGroupMessage, ) } is AppState.Loading -> { LoadingView() } is AppState.Error -> { when (state.cause) { ErrorCause.NO_INTERNET -> { NoInternetStateView { viewModel.fetchChatMessages(groupId) } } ErrorCause.NO_RESULT -> { ChatView( chatGroupMessage = null ) } ErrorCause.UNKNOWN -> { ErrorStateView( title = "Couldn't Load Messages!", message = state.message, ) { viewModel.fetchChatMessages(groupId) } } else -> { } } } is AppState.Ideal -> { // do nothing } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun MessageDetailContainer( chatGroupMessage: ChatGroupMessage?, navController: NavController?, ) { Scaffold(topBar = { TopAppBar( title = { Text( text = chatGroupMessage?.user?.getName() ?: "", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold ) }, navigationIcon = { IconButton(onClick = { navController?.popBackStack() }) { Icon( imageVector = Icons.Filled.ArrowBack, contentDescription = "Back Arrow" ) } }, ) }) { contentPadding -> Box( modifier = Modifier .padding(contentPadding) .padding(horizontal = 16.dp) .fillMaxSize() ) { ChatView( chatGroupMessage = chatGroupMessage, ) } } } @Composable fun ChatView( chatGroupMessage: ChatGroupMessage?, viewModel: ChatViewModel = koinViewModel() ) { Column( verticalArrangement = Arrangement.spacedBy(16.dp) ) { LazyColumn( modifier = Modifier .fillMaxWidth() .weight(1f), verticalArrangement = Arrangement.spacedBy(16.dp), reverseLayout = true ) { val chatMessages = chatGroupMessage?.messageList ?: emptyList() items(chatMessages.reversed()) { chatMessage -> ChatCard( chatMessage = chatMessage, userId = chatGroupMessage?.me?.id ?: "", senderProfilePic = chatGroupMessage?.user?.profilePic ) } } val message = remember { mutableStateOf("") } TextField( value = message.value, onValueChange = { message.value = it }, modifier = Modifier.fillMaxWidth(), maxLines = 3, shape = RoundedCornerShape(8.dp, 8.dp), placeholder = { Text("Message") }, trailingIcon = { IconButton(onClick = { if (chatGroupMessage != null && message.value.isNotBlank()) { viewModel.sendMessage(chatGroupMessage, message.value.trim()) message.value = "" } }) { Icon( imageVector = Icons.Filled.Send, contentDescription = "Send" ) } }) Spacer(modifier = Modifier.height(8.dp)) } }
0
Kotlin
0
0
5da593d493a04319b3d53a537d3893ccde9ab47d
6,887
GiveAwayThings_GoodDeed
MIT License
app/src/main/java/com/lemu/pay/checkout/home/HomeScreen.kt
Visels
853,435,251
false
{"Kotlin": 125294}
package com.lemu.pay.checkout.home import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import com.lemu.pay.checkout.ui.SNumberPad import com.lemu.pay.checkout.ui.theme.bluePrimary import com.lemu.pay.checkout.ui.theme.blueSecondary import com.lemu.pay.checkout.ui.theme.poppins_medium @Composable fun HomeScreen( navigateToPayment:(String) -> Unit ) { val viewModel: CalculatorViewModel = viewModel() Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Column( verticalArrangement = Arrangement.Bottom, horizontalAlignment = Alignment.End, modifier = Modifier .fillMaxWidth() .padding(16.dp, 12.dp) .weight(0.1f), ) { BasicTextField( value = viewModel.input.ifBlank { "0" }, onValueChange = {}, textStyle = MaterialTheme.typography.headlineLarge.copy( textAlign = TextAlign.End, color = Color.Black, ), modifier = Modifier .fillMaxSize() .background(color = Color.White), readOnly = true, maxLines = 1, ) } Row ( modifier = Modifier.weight(0.7f) ){ SNumberPad(viewModel::updateInput) } Row( modifier = Modifier .fillMaxWidth() .weight(0.1f) ) { Button( colors = ButtonDefaults.buttonColors( containerColor = bluePrimary, contentColor = Color.White ), shape = RoundedCornerShape(5.dp), onClick = { navigateToPayment.invoke(viewModel.result) }, modifier = Modifier .fillMaxWidth() .fillMaxHeight(0.8f) .padding(horizontal = 8.dp) ) { Text( text = "CHARGE", style = MaterialTheme.typography.titleLarge, fontFamily = poppins_medium ) } } } }
2
Kotlin
0
0
4136bed5ef49764eed96371396fcbc48d2b6f5ca
2,998
Payment-Checkout
MIT License
src/main/kotlin/io/github/magonxesp/fancapsextract/Context.kt
magonxesp
758,567,542
false
{"Kotlin": 48781, "Makefile": 1179}
package io.github.magonxesp.fancapsextract abstract class Context { val baseUrl = "https://fancaps.net" val cdnBaseUrl = "https://cdni.fancaps.net" open val userAgent = "FanCapExtractLib/0.0.0" /** * Get the full url including the protocol and domain. */ fun getFullUrl(url: String): String { if (url.startsWith("$baseUrl/")) { return url } return "$baseUrl/${url.removePrefix("/")}" } /** * Get the full url including the protocol and domain. */ fun getCdnFullUrl(url: String): String { if (url.startsWith("$cdnBaseUrl/")) { return url } return "$cdnBaseUrl/${url.removePrefix("/")}" } } object DefaultContext : Context()
0
Kotlin
0
1
83c70768fd979a2e6e7ca0acc38868f59bcf3419
664
fancaps-extract
MIT License
vk-api-generated/src/main/kotlin/name/anton3/vkapi/generated/ads/methods/AdsGetAccounts.kt
Anton3
159,801,334
true
{"Kotlin": 1382186}
@file:Suppress("unused", "MemberVisibilityCanBePrivate", "SpellCheckingInspection") package name.anton3.vkapi.generated.ads.methods import com.fasterxml.jackson.module.kotlin.jacksonTypeRef import name.anton3.vkapi.generated.ads.objects.Account import name.anton3.vkapi.method.UserMethod import name.anton3.vkapi.method.VkMethod /** * [https://vk.com/dev/ads.getAccounts] * * Returns a list of advertising accounts. * */ class AdsGetAccounts : VkMethod<List<Account>, UserMethod>("ads.getAccounts", jacksonTypeRef())
2
Kotlin
0
8
773c89751c4382a42f556b6d3c247f83aabec625
526
kotlin-vk-api
MIT License
src/test/kotlin/be/seppevolkaerts/day3/Part1Test.kt
Cybermaxke
727,453,020
false
{"Kotlin": 35118}
package be.seppevolkaerts.day3 import be.seppevolkaerts.lines import kotlin.test.Test import kotlin.test.assertEquals class Part1Test { @Test fun example() { assertEquals(4361, sumOfPartNumbers(lines("day3/example.txt"))) } @Test fun main() { val sumOfPartNumbers = sumOfPartNumbers(lines("day3/input.txt")) println("Sum of part numbers: $sumOfPartNumbers") } }
0
Kotlin
0
1
56ed086f8493b9f5ff1b688e2f128c69e3e1962c
385
advent-2023
MIT License
plugins/modules-catalog/src/main/kotlin/shuttle.plugins.modulescatalog/ModulesCatalogExtension.kt
4face-studi0
462,194,990
false
null
package shuttle.plugins.modulescatalog import org.gradle.api.Project import shuttle.plugins.util.create import javax.inject.Inject open class ModulesCatalogExtension @Inject constructor(private val project: Project) { fun add(module: String) { project.dependencies.add("implementation", project.project(":shuttle:$module")) } companion object { fun setup(project: Project): ModulesCatalogExtension = project.extensions.create("moduleDependencies") } }
11
Kotlin
0
14
55ab90f13bb96e10add14d45cd3117ada38262ed
489
Shuttle
Apache License 2.0
src/main/java/com/cocktailsguru/app/staticfiles/CocktailsWebMvcConfiguration.kt
CocktailsGuru
103,529,993
false
null
package com.cocktailsguru.app.staticfiles import org.springframework.beans.factory.annotation.Value import org.springframework.context.annotation.Configuration import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry import org.springframework.web.servlet.config.annotation.WebMvcConfigurer @Configuration class CocktailsWebMvcConfiguration : WebMvcConfigurer { companion object { const val ASSETS_PATH = "/assets/**" } @Value("\${cocktails.resource.assets}") private lateinit var assetsResourceLocation: String final override fun addResourceHandlers(registry: ResourceHandlerRegistry) { registry.addResourceHandler(ASSETS_PATH) .setCachePeriod(864000) .setCacheControl(null) .addResourceLocations(assetsResourceLocation) } }
0
Kotlin
0
1
f0a447975dedb7f54bd64dba1dce10fefeda64ce
843
server
MIT License
app/src/main/java/com/moviebag/unofficial/data/model/uimodel/ReviewViewItem.kt
ajayverma16305
344,219,499
false
null
package com.moviebag.unofficial.data.model.uimodel data class ReviewViewItem( val name: String, val profilePath: String, val comment: String, val createdAt: String )
0
Kotlin
0
0
801dc97a9bb310123a96e7fef0da8b53a0e8e222
182
MovieBag
MIT License
libraries/csm.cloud.common.web/src/main/kotlin/com/bosch/pt/csm/cloud/common/facade/rest/ApiVersionRequestMappingHandlerMapping.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: <NAME> Power Tools GmbH, 2018 - 2021 * * ************************************************************************ */ package com.bosch.pt.csm.cloud.common.facade.rest import java.lang.reflect.Method import org.springframework.core.annotation.AnnotationUtils.findAnnotation import org.springframework.web.servlet.mvc.condition.RequestCondition import org.springframework.web.servlet.mvc.method.RequestMappingInfo import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping import org.springframework.web.util.pattern.PathPatternParser class ApiVersionRequestMappingHandlerMapping(private val properties: ApiVersionProperties) : RequestMappingHandlerMapping() { override fun getMappingForMethod(method: Method, handlerType: Class<*>): RequestMappingInfo? { val info = super.getMappingForMethod(method, handlerType) ?: return null // Create mapping if ApiVersion annotation is defined on the specified method findAnnotation(method, ApiVersion::class.java)?.apply { // Concatenate our ApiVersion with the usual request mapping return createApiVersionInfo(method, this, getCustomMethodCondition(method)).combine(info) } // Create mapping if ApiVersion annotation is defined on the controller class findAnnotation(handlerType, ApiVersion::class.java)?.apply { // Concatenate our ApiVersion with the usual request mapping return createApiVersionInfo(method, this, getCustomTypeCondition(handlerType)).combine(info) } // Handle normally without API versioning, i.e. map URLs directly return super.getMappingForMethod(method, handlerType) } private fun createApiVersionInfo( method: Method, annotation: ApiVersion, customCondition: RequestCondition<*>? ): RequestMappingInfo { // Get specified API versions for the endpoint var from = annotation.from var to = annotation.to // If no min version is defined, set to min api version if (from == 0) { from = properties.version.min } // If no limit is defined, set to max api version if (to == 0) { to = properties.version.max } // Calculate URL version prefixes to map for the given endpoint val urlVersionPrefixes = createUrlPrefixArray(method, from, to, properties.version.min, properties.version.max) var index = 0 var version = from while (version <= to) { urlVersionPrefixes[index] = properties.version.prefix + version version++ index++ } // Create the url mapping return RequestMappingInfo.paths(*urlVersionPrefixes) .apply { if (customCondition != null) { this.customCondition(customCondition) } this.options( RequestMappingInfo.BuilderConfiguration().apply { patternParser = PathPatternParser() }) } .build() } private fun createUrlPrefixArray( method: Method, from: Int, to: Int, minVersion: Int, maxApiVersion: Int ): Array<String?> { require(from >= minVersion) { "From API version is older than the min version for method: $method" } require(to <= maxApiVersion) { "Invalid To API version for method: $method defined" } require(from <= to) { "From/To API versions are mixed up for method: $method defined" } return arrayOfNulls(to - from + 1) } }
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
3,516
bosch-pt-refinemysite-backend
Apache License 2.0
z2-kotlin-plugin/src/hu/simplexion/z2/kotlin/ir/rui/air/AirBuilderWhen.kt
spxbhuhb
665,463,766
false
{"Kotlin": 1355048, "CSS": 126999, "Java": 7121, "HTML": 1560, "JavaScript": 975}
package hu.simplexion.z2.kotlin.ir.rui.air import hu.simplexion.z2.kotlin.ir.rui.ClassBoundIrBuilder import hu.simplexion.z2.kotlin.ir.rui.air.visitors.AirElementVisitor import hu.simplexion.z2.kotlin.ir.rui.rum.RumWhen import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction class AirBuilderWhen( override val rumElement: RumWhen, override val irFunction: IrSimpleFunction, override val externalPatch: AirFunction, override val subBuilders: List<AirBuilder> ) : AirBuilder { override fun toIr(parent: ClassBoundIrBuilder) = TODO() override fun <R, D> accept(visitor: AirElementVisitor<R, D>, data: D): R = visitor.visitBuilderWhen(this, data) }
6
Kotlin
0
1
980100fb733a7b9346ff3482ec7bb8a3b03d0e7f
687
z2
Apache License 2.0
app/src/main/java/m1k/kotik/negocards/fragments/pages/code_create_pages/CanvasCodePreCreateFragment.kt
M1KoTiK
586,878,944
false
{"Kotlin": 264202}
package m1k.kotik.negocards.fragments.pages.code_create_pages import android.animation.ObjectAnimator import android.content.Context import android.os.Bundle import android.text.Editable import android.text.TextWatcher import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.AdapterView import android.widget.ArrayAdapter import androidx.core.animation.doOnEnd import m1k.kotik.negocards.R import m1k.kotik.negocards.databinding.FragmentCanvasCodePreCreateBinding import m1k.kotik.negocards.fragments.choiceParametersForQR.ChoiceParametersForCardFragment import m1k.kotik.negocards.fragments.choiceParametersForQR.ChoiceParametersForTextFragment import m1k.kotik.negocards.fragments.utils_fragment.PlaceholderFragment class CanvasCodePreCreateFragment : Fragment() { lateinit var binding: FragmentCanvasCodePreCreateBinding var customConfigSizePanelIsShow = false var selectedItemPosition = 1 override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentCanvasCodePreCreateBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val types = resources.getStringArray(R.array.canvas_config_size) val arrayAdapter = ArrayAdapter(requireActivity(),R.layout.dropdown_item,types) binding.autoCompleteTextView.setAdapter(arrayAdapter) binding.autoCompleteTextView.onItemClickListener = AdapterView.OnItemClickListener { parent, _, position, id -> if(selectedItemPosition != position){ selectedItemPosition = position if(customConfigSizePanelIsShow){ val container = binding.customCanvasConfigSizeContainer val widthAnimator = ObjectAnimator.ofFloat(container, "scaleX", 1f, 0f) widthAnimator.duration = 500 widthAnimator.doOnEnd { } widthAnimator.start() val heightAnimator = ObjectAnimator.ofFloat(container, "scaleY", 1f, 0f) heightAnimator.duration = 600 heightAnimator.start() customConfigSizePanelIsShow = false binding.canvasConfigHeight.clearFocus() binding.canvasConfigWidth.clearFocus() val imm = context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(binding.root.windowToken, 0) } //Toast.makeText(requireActivity(), "Selected: $position", Toast.LENGTH_SHORT).show() when(binding.autoCompleteTextView.text.toString()){ "Маленький"->{ binding.canvasConfig.canvasWidth = 600 binding.canvasConfig.canvasHeight = 350 } "Средний"->{ binding.canvasConfig.canvasWidth = 800 binding.canvasConfig.canvasHeight = 600 } "Большой"->{ binding.canvasConfig.canvasWidth = 1000 binding.canvasConfig.canvasHeight = 700 } "Кастомный"->{ val container = binding.customCanvasConfigSizeContainer val widthAnimator = ObjectAnimator.ofFloat(container, "scaleX", 0f, 1f) widthAnimator.duration = 500 widthAnimator.doOnEnd { } widthAnimator.start() val heightAnimator = ObjectAnimator.ofFloat(container, "scaleY", 0f, 1f) heightAnimator.duration = 600 heightAnimator.start() customConfigSizePanelIsShow = true } } } binding.canvasConfigHeight.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable){} override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { val height = binding.canvasConfigHeight.text.toString() if(height.toIntOrNull() != null && before < count){ binding.canvasConfig.canvasHeight = height.toInt() } } }) binding.canvasConfigWidth.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable) {} override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { val width = binding.canvasConfigWidth.text.toString() if (width.toIntOrNull() != null && before < count) { binding.canvasConfig.canvasWidth = width.toInt() } } }) //Получение текстового представления //val selectedItem = parent.getItemAtPosition(position).toString() } } }
0
Kotlin
0
2
b9e18395cebeb3686e29992b561f000232bf3ddd
5,659
Nego-Cards
Apache License 2.0
common/src/commonMain/kotlin/com/example/common/state/MoviesState.kt
reduxkotlin
202,409,249
true
null
package com.example.common.state import com.example.common.models.* import kotlinx.serialization.Serializable @Serializable data class MoviesState( var movies: MutableMap<String, Movie> = mutableMapOf(), var moviesList: MutableMap<MoviesMenu, List<String>> = mutableMapOf(), var recommended: MutableMap<String, List<String>> = mutableMapOf(), var similar: MutableMap<String, List<String>> = mutableMapOf(), var search: MutableMap<String, MutableList<String>> = mutableMapOf(), var searchKeywords: MutableMap<String, List<Keyword>> = mutableMapOf(), var recentSearches: Set<String> = setOf(), var moviesUserMeta: MutableMap<String, MovieUserMeta> = mutableMapOf(), var discover: MutableList<String> = mutableListOf(), var discoverFilter: DiscoverFilter? = null, var savedDiscoverFilters: MutableList<DiscoverFilter> = mutableListOf(), var wishlist: Set<String> = setOf(), var seenlist: Set<String> = setOf(), var withGenre: MutableMap<String, MutableList<String>> = mutableMapOf(), var withKeywords: MutableMap<String, MutableList<String>> = mutableMapOf(), var withCrew: MutableMap<String, List<String>> = mutableMapOf(), var reviews: MutableMap<String, List<Review>> = mutableMapOf(), var customLists: MutableMap<String, CustomList> = mutableMapOf(), var genres: MutableList<Genre> = mutableListOf() ) { enum class CodingKeys(val rawValue: String) { movies("movies"), wishlist("wishlist"), seenlist("seenlist"), customLists("customLists"), moviesUserMeta( "moviesUserMeta" ), savedDiscoverFilters("savedDiscoverFilters"); companion object { operator fun invoke(rawValue: String) = CodingKeys.values().firstOrNull { it.rawValue == rawValue } } } fun withMovieId(movieId: String): Movie = movies[movieId]!! fun withCrewId(crewId: String) = withCrew[crewId] ?: listOf() fun withListId(listId: String) = customLists[listId] fun withKeywordId(keywordId: String) = withKeywords[keywordId]!!.toList() fun withGenreId(genreId: String): List<String> = withGenre[genreId] ?: listOf() fun getGenreById(genreId: String) = genres.find { it.id == genreId } fun search(searchText: String) = search[searchText]?.toList() val customListsList: List<CustomList> get() = customLists.values.toList() fun reviewByMovieId(movieId: String): List<Review>? = reviews[movieId] fun recommendedMovies(movieId: String): List<Movie>? = recommended[movieId]?.filter { movies.containsKey(it) }?.mapNotNull { movies[it] } fun similarMovies(movieId: String): List<Movie>? = similar[movieId]?.filter { movies.containsKey(it) }?.mapNotNull { movies[it] } fun getMoviesToSave() = movies.filter { shouldSaveMovie(it.value.id) }.toMutableMap() fun getSaveState() = MoviesState(movies = getMoviesToSave(), seenlist = seenlist, wishlist = wishlist, customLists = customLists) private fun shouldSaveMovie(movieId: String): Boolean = seenlist.contains(movieId) || wishlist.contains(movieId) || customLists.any { it.value.movies.contains(movieId) || it.value.cover == movieId } }
1
Objective-C
2
32
42a2429cd78f2222564278e8fb20dd9f05ac08f2
3,237
MovieSwiftUI-Kotlin
Apache License 2.0
kandy-api/src/main/kotlin/org/jetbrains/kotlinx/kandy/ir/aes/AesName.kt
Kotlin
502,039,936
false
null
/* * Copyright 2020-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package org.jetbrains.kotlinx.kandy.ir.aes /** * Wrapper for an aesthetic attribute name. * * @property name attribute name. */ public data class AesName(val name: String)
79
Kotlin
0
98
fd613edc4dd37aac0d0ecdb4245a770e09617fc7
286
kandy
Apache License 2.0
app/src/main/java/com/example/animeapp/ui/home/HomeViewModel.kt
emrekizil
578,072,214
false
{"Kotlin": 66198}
package com.example.animeapp.ui.home import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.example.animeapp.R import com.example.animeapp.data.NetworkResponseState import com.example.animeapp.domain.module.AnimeEntity import com.example.animeapp.data.mappers.AnimeListMapper import com.example.animeapp.domain.GetAnimeWithCategoriesUseCase import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class HomeViewModel @Inject constructor( private val getAnimeWithCategoriesUseCase: GetAnimeWithCategoriesUseCase, private val animeListMapper: AnimeListMapper<AnimeEntity, HomeUiData> ) : ViewModel() { private val _animeHomeUiState=MutableLiveData<HomeUiState>() val animeHomeUiState:LiveData<HomeUiState> get() = _animeHomeUiState fun getAnimeWithCategories(categoryQuery:String){ viewModelScope.launch { //We should get latest response state because it reflects ui.It explains why we use collect latest getAnimeWithCategoriesUseCase(categoryQuery).collectLatest{ when(it){ is NetworkResponseState.Success->{ _animeHomeUiState.postValue(HomeUiState.Success(animeListMapper.map(it.result))) } is NetworkResponseState.Error->{ _animeHomeUiState.postValue(HomeUiState.Error(R.string.error)) } is NetworkResponseState.Loading->{ _animeHomeUiState.postValue(HomeUiState.Loading) } } } } } }
0
Kotlin
0
4
8f15b49b95a598d8c9aadfaf08870cd5a4c3f77e
1,814
AnimeApp
Apache License 2.0
src/integrationTest/kotlin/uk/gov/justice/digital/hmpps/jobsboard/api/jobs/domain/JobRepositoryTestCase.kt
ministryofjustice
775,484,528
false
{"Kotlin": 265607, "Dockerfile": 1362}
package uk.gov.justice.digital.hmpps.jobsboard.api.jobs.domain import org.junit.jupiter.api.BeforeEach import org.mockito.kotlin.whenever import org.springframework.beans.factory.annotation.Autowired import uk.gov.justice.digital.hmpps.jobsboard.api.commons.domain.RepositoryTestCase import uk.gov.justice.digital.hmpps.jobsboard.api.employers.domain.EmployerRepository import java.time.Instant import java.util.* abstract class JobRepositoryTestCase : RepositoryTestCase() { @Autowired protected lateinit var employerRepository: EmployerRepository @Autowired protected lateinit var jobRepository: JobRepository protected final val jobCreationTime: Instant = TestPrototypes.jobCreationTime protected final val jobModificationTime: Instant = TestPrototypes.jobModificationTime protected final val expectedPrisonNumber = TestPrototypes.expectedPrisonNumber protected final val amazonEmployer = TestPrototypes.amazonEmployer protected final val amazonForkliftOperatorJob = TestPrototypes.amazonForkliftOperatorJob protected final val nonExistentJob = TestPrototypes.nonExistentJob @BeforeEach override fun setUp() { jobRepository.deleteAll() employerRepository.deleteAll() whenever(dateTimeProvider.now).thenReturn(Optional.of(jobCreationTime)) } protected fun obtainTheJobJustCreated(): Job { employerRepository.save(amazonEmployer) return jobRepository.save(amazonForkliftOperatorJob).also { entityManager.flush() } } }
2
Kotlin
0
1
f821551ec9a18686b0dafe343377857b683e47b0
1,488
hmpps-jobs-board-api
MIT License
app/src/main/java/com/workfort/pstuian/app/ui/forgotpassword/ForgotPasswordScreenStateReducer.kt
arhanashik
411,942,559
false
{"Kotlin": 1131964}
package com.workfort.pstuian.app.ui.forgotpassword import com.workfort.pstuian.view.service.StateReducer class ForgotPasswordScreenStateReducer : StateReducer<ForgotPasswordScreenState, ForgotPasswordScreenStateUpdate> { override val initial: ForgotPasswordScreenState get() = ForgotPasswordScreenState() }
0
Kotlin
0
2
a5efa08fc1483df3c76067063d085c3a8ae24579
312
PSTUian-android
Apache License 2.0
mastodonk-core/src/commonMain/kotlin/fr/outadoc/mastodonk/api/endpoint/accounts/ReportsApi.kt
outadoc
361,237,514
false
null
package fr.outadoc.mastodonk.api.endpoint.accounts import fr.outadoc.mastodonk.api.entity.Report import fr.outadoc.mastodonk.api.entity.request.ReportCreate /** * Create user reports. * * @see [Official Docs](https://docs.joinmastodon.org/methods/accounts/reports/) */ public interface ReportsApi { /** * File a [Report]. */ public suspend fun fileReport(report: ReportCreate): Report }
1
Kotlin
0
3
0dff922e6077184f4d9fcefb9f5204fac6b3bdfd
412
mastodonk
Apache License 2.0
app/src/main/java/com/supplier/sl_delivery/modals/MainCategory.kt
aMujeeb
255,690,445
false
null
package com.supplier.sl_delivery.modals import com.supplier.sl_delivery.rest.APIClient import com.supplier.sl_delivery.rest.responses.CategoriesResponse import com.supplier.sl_delivery.rest.responses.ItemsByCategoryResponse import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers /** * Created by Aurora on 2020-04-13. */ data class MainCategory(var id : String, var lable : String, var active : Boolean) { companion object { fun getAllCategories() : Observable<CategoriesResponse?>? { return APIClient.getAllCategoriesList()!!.subscribeOn(Schedulers.io()).observeOn( AndroidSchedulers.mainThread()) } } fun getAllItems() : Observable<ItemsByCategoryResponse?>? { return APIClient.getAllItemsUnderCategory(this.id)!!.subscribeOn(Schedulers.io()).observeOn( AndroidSchedulers.mainThread()) } }
0
Kotlin
0
1
061f2065589c385b18c3a8df9e27efa9a5eec265
953
SL_Delivery
Apache License 2.0
src/test/kotlin/io/andrewohara/tabbychat/DevRunner.kt
oharaandrew314
391,217,773
false
null
package io.andrewohara.tabbychat import dev.forkhandles.result4k.valueOrNull import org.http4k.server.SunHttp import org.http4k.server.asServer fun main() { val port = System.getenv("PORT")?.toIntOrNull() ?: 8000 val provider = TabbyChatProvider.fromEnv(System.getenv()) val server = provider.http .asServer(SunHttp(port)) .start() println("Running ${provider.realm} provider on port $port") val user = provider.createUser("Test User") val token = provider.service.createAccessToken(user.id).valueOrNull()!! println("Access Token: $token") server.block() }
0
Kotlin
0
0
a48f7604dd30180c9c88e40530480707e9cbcf43
612
tabby-chat-server
The Unlicense
apps/hops-api/test/api/MockServers.kt
navikt
291,966,099
false
null
package api import io.ktor.http.HttpHeaders import io.ktor.http.withCharset import no.nav.helse.hops.convert.ContentTypes import no.nav.helse.hops.test.HopsOAuthMock import no.nav.helse.hops.test.MockServer import okhttp3.mockwebserver.MockResponse import org.junit.jupiter.api.extension.BeforeAllCallback import org.junit.jupiter.api.extension.ExtensionContext import java.util.concurrent.atomic.AtomicBoolean object MockServers { val oAuth = HopsOAuthMock() val eventStore = MockServer().apply { matchRequest( { request -> request.method == "GET" && request.path == "/fhir/4.0/Bundle" }, { MockResponse() .setHeader(HttpHeaders.ContentType, ContentTypes.fhirJsonR4.withCharset(Charsets.UTF_8).toString()) .setBody("""{"resourceType": "Bundle"}""") } ) matchRequest( { request -> request.method == "POST" && request.path == "/fhir/4.0/\$process-message" }, { MockResponse() .setHeader(HttpHeaders.ContentType, ContentTypes.fhirJsonR4.withCharset(Charsets.UTF_8).toString()) .setBody("""""") } ) } object Setup : BeforeAllCallback { private val started = AtomicBoolean(false) override fun beforeAll(context: ExtensionContext?) { if (!started.getAndSet(true)) { oAuth.start() eventStore.start() } } } }
18
Kotlin
3
1
00e0fd26d14b4883fbbebb55546c30a9ac90a565
1,522
helseopplysninger
MIT License
services/hierarchy/src/test/kotlin/ProductServiceTest.kt
eclipse-apoapsis
760,319,414
false
{"Kotlin": 2994047, "Dockerfile": 24090, "Shell": 6277}
/* * Copyright (C) 2023 The ORT Server Authors (See <https://github.com/eclipse-apoapsis/ort-server/blob/main/NOTICE>) * * 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.eclipse.apoapsis.ortserver.services import io.kotest.core.spec.style.WordSpec import io.mockk.coEvery import io.mockk.coVerify import io.mockk.just import io.mockk.mockk import io.mockk.runs import org.eclipse.apoapsis.ortserver.dao.repositories.DaoProductRepository import org.eclipse.apoapsis.ortserver.dao.repositories.DaoRepositoryRepository import org.eclipse.apoapsis.ortserver.dao.test.DatabaseTestExtension import org.eclipse.apoapsis.ortserver.dao.test.Fixtures import org.eclipse.apoapsis.ortserver.model.RepositoryType import org.jetbrains.exposed.sql.Database class ProductServiceTest : WordSpec({ val dbExtension = extension(DatabaseTestExtension()) lateinit var db: Database lateinit var productRepository: DaoProductRepository lateinit var repositoryRepository: DaoRepositoryRepository lateinit var fixtures: Fixtures beforeEach { db = dbExtension.db productRepository = dbExtension.fixtures.productRepository repositoryRepository = dbExtension.fixtures.repositoryRepository fixtures = dbExtension.fixtures } "createRepository" should { "create Keycloak permissions" { val authorizationService = mockk<AuthorizationService> { coEvery { createRepositoryPermissions(any()) } just runs coEvery { createRepositoryRoles(any()) } just runs } val service = ProductService(db, productRepository, repositoryRepository, authorizationService) val repository = service.createRepository(RepositoryType.GIT, "https://example.com/repo.git", fixtures.product.id) coVerify(exactly = 1) { authorizationService.createRepositoryPermissions(repository.id) authorizationService.createRepositoryRoles(repository.id) } } } "deleteProduct" should { "delete Keycloak permissions" { val authorizationService = mockk<AuthorizationService> { coEvery { deleteProductPermissions(any()) } just runs coEvery { deleteProductRoles(any()) } just runs } val service = ProductService(db, productRepository, repositoryRepository, authorizationService) service.deleteProduct(fixtures.product.id) coVerify(exactly = 1) { authorizationService.deleteProductPermissions(fixtures.product.id) authorizationService.deleteProductRoles(fixtures.product.id) } } } })
18
Kotlin
2
9
0af70d6382a86f0ebc35d9b377f4229c6a71637a
3,308
ort-server
Apache License 2.0
Temas-1-2-3/Ejercicios/unidad2Relacion2Ejercicio21/src/main/kotlin/Main.kt
idanirf
508,465,509
false
{"Kotlin": 31341}
fun main(args: Array<String>) { println("Muestra los números pares que estén entre 1 y 20 :)") for (i in 1..20) if (i%2==0) println("Los números pares comprendidos ente 1 y 20 son: $i") }
1
Kotlin
0
2
74d62574c657babf0f658d3739e2646da44cfe65
215
KotlinCamp
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsactivitiesmanagementapi/job/ManageAllocationsJobTest.kt
ministryofjustice
533,838,017
false
null
package uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.job import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.service.AllocationOperation import uk.gov.justice.digital.hmpps.hmppsactivitiesmanagementapi.service.ManageAllocationsService class ManageAllocationsJobTest { private val offenderDeallocationService: ManageAllocationsService = mock() private val job = ManageAllocationsJob(offenderDeallocationService) @Test fun `attendance records creation triggered for today`() { job.execute() verify(offenderDeallocationService).allocations(AllocationOperation.DEALLOCATE_ENDING) } }
4
Kotlin
0
1
9f121ceca8be8482d39edc7cd16180ae586e5b34
726
hmpps-activities-management-api
MIT License
app/src/main/java/dev/berwyn/jellybox/data/local/JellyfinServerDao.kt
berwyn
586,199,884
false
null
package dev.berwyn.jellybox.data.local import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Update import kotlinx.coroutines.flow.Flow @Dao interface JellyfinServerDao { @Query("SELECT * FROM jellyfinserver") fun getAll(): Flow<List<JellyfinServer>> @Query("SELECT * FROM jellyfinserver WHERE is_default = 1") suspend fun getDefault(): JellyfinServer? @Query("SELECT * FROM jellyfinserver WHERE is_selected = 1") suspend fun getSelected(): JellyfinServer? @Query("SELECT * FROM jellyfinserver WHERE is_selected = 1") fun getSelectedFlow(): Flow<JellyfinServer?> @Query("SELECT * FROM jellyfinserver WHERE id = :id") suspend fun findById(id: Long): JellyfinServer @Query("SELECT * FROM jellyfinserver WHERE id = :id") suspend fun findById(id: Int): JellyfinServer @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun storeServer(server: JellyfinServer): Long @Update suspend fun updateServer(server: JellyfinServer) @Delete suspend fun deleteServer(server: JellyfinServer) }
0
Kotlin
0
0
8e484fcece73e27a0514b5ba97bedabde7685c25
1,180
jellybox
Apache License 2.0
app/src/main/java/github/sachin2dehury/nitrresources/admin/onedrive/OneDriveItemDetails.kt
sachin2dehury
296,853,144
false
null
package github.sachin2dehury.nitrresources.admin.onedrive import com.squareup.moshi.Json data class OneDriveItemDetails( @field:Json(name = "@content.downloadUrl") val url: String, @field:Json(name = "name") val name: String, @field:Json(name = "parentReference") val parent: ItemParent, @field:Json(name = "file") val type: ItemMime, @field:Json(name = "size") val size: Long )
0
Kotlin
0
1
91029b96c273c534469ce133ae2c32114cc36437
400
NITR_Resources
Apache License 2.0
memo/src/main/kotlin/com/mistar/memo/application/request/UserSignOutRequest.kt
mike-urssu
354,238,895
false
{"Kotlin": 64000}
package com.mistar.memo.application.request import com.fasterxml.jackson.annotation.JsonProperty import com.mistar.memo.domain.model.dto.UserSignOutDto class UserSignOutRequest( @JsonProperty("refreshToken") private val refreshToken: String ) { fun toUserSignOutDto() = UserSignOutDto(refreshToken) }
0
Kotlin
0
0
ef28332a40a9b8f8422456d3ffaa97f20cdfaf62
314
memo-incubating
Apache License 2.0
src/main/kotlin/io/github/ydwk/ydwk/impl/interaction/application/ApplicationCommandImpl.kt
YDWK
527,250,343
false
null
/* * Copyright 2022 YDWK 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 io.github.ydwk.ydwk.impl.interaction.application import com.fasterxml.jackson.databind.JsonNode import io.github.ydwk.ydwk.YDWK import io.github.ydwk.ydwk.entities.Channel import io.github.ydwk.ydwk.entities.Guild import io.github.ydwk.ydwk.entities.Message import io.github.ydwk.ydwk.entities.User import io.github.ydwk.ydwk.entities.guild.Member import io.github.ydwk.ydwk.interaction.Interaction import io.github.ydwk.ydwk.interaction.application.ApplicationCommand import io.github.ydwk.ydwk.interaction.sub.InteractionType import io.github.ydwk.ydwk.util.EntityToStringBuilder import io.github.ydwk.ydwk.util.GetterSnowFlake abstract class ApplicationCommandImpl( override val ydwk: YDWK, override val json: JsonNode, override val idAsLong: Long, val interaction: Interaction ) : ApplicationCommand { override val name: String get() = json["name"].asText() override val description: String get() = json["description"].asText() override val isDmPermissions: Boolean? get() = if (json.has("dm_permission")) json["dm_permission"].asBoolean() else null override val isNsfw: Boolean? get() = if (json.has("nsfw")) json["nsfw"].asBoolean() else null override val guild: Guild? = interaction.guild override val targetId: GetterSnowFlake? get() = if (json.has("target_id")) GetterSnowFlake.of(json["target_id"].asLong()) else null override val user: User? = interaction.user override val member: Member? = interaction.member override val applicationId: GetterSnowFlake = interaction.applicationId override val interactionType: InteractionType = interaction.type override val channel: Channel? = interaction.channel override val token: String = interaction.token override val version: Int = interaction.version override val message: Message? = interaction.message override val permissions: Long? = interaction.permissions override fun toString(): String { return EntityToStringBuilder(ydwk, this).name(this.name).toString() } }
3
Kotlin
1
2
7e479b29ddca2e0d9093ab8c5dae6892f5640d80
2,681
YDWK
Apache License 2.0
src/main/kotlin/ru/yoomoney/gradle/plugins/release/git/GitRepoFactory.kt
yoomoney
320,603,497
false
null
package ru.yoomoney.gradle.plugins.release.git import org.eclipse.jgit.api.Git import org.eclipse.jgit.storage.file.FileRepositoryBuilder import java.io.File /** * Класс для создания GitRepo * * @author horyukova * @since 24.06.2019 */ class GitRepoFactory(private val settings: GitSettings) { /** * Получить объект для работы с git-репозиторием из уже существующей директории * * @param directory директория с git-репозиторием * @return объект для работы с git-репозиторием */ fun createFromExistingDirectory(directory: File): GitRepo { return GitRepo(Git(FileRepositoryBuilder() .readEnvironment() .findGitDir(directory) .build()), settings) } }
2
Kotlin
0
2
581f070c324efcb2b8235e411ec0a1628ec310ce
760
artifact-release-plugin
MIT License
android/src/main/kotlin/com/uc/uclocation/provider/LocationUpdateListener.kt
Ankursohal007
429,316,533
false
null
package com.uc.uclocation.provider import java.util.HashMap interface LocationUpdateListener { fun onLocationUpdated(location: HashMap<Any, Any>?) }
1
Kotlin
0
1
8e108e116320d116ff0f059f41a29185c861ee16
154
location_track
MIT License
drm-ipfs/src/main/kotlin/moe/_47saikyo/drm/ipfs/service/impl/IpfsServiceImpl.kt
Smileslime47
738,883,139
false
{"Kotlin": 243069, "Vue": 73384, "Java": 49135, "TypeScript": 25030, "Solidity": 18621, "CSS": 1622, "Dockerfile": 774, "Shell": 511, "HTML": 390}
package moe._47saikyo.drm.ipfs.service.impl import moe._47saikyo.drm.ipfs.service.IpfsService import io.ipfs.api.NamedStreamable.ByteArrayWrapper import io.ipfs.multihash.Multihash class IpfsServiceImpl : IpfsService { override fun upload(content: ByteArray): String { val ipfs = IpfsService.getInstance() val file = ByteArrayWrapper(content) val node = ipfs.add(file)[0] return node.hash.toString() } override fun download(hash: String): ByteArray { val ipfs = IpfsService.getInstance() val content = ipfs.cat(Multihash.decode(hash)) return content } }
0
Kotlin
0
4
e0053b3b1e81e049c6869e4a0f52bfdfb2bcbacb
631
Digital-Rights-Management
MIT License
app/src/main/java/com/zhufucdev/motion_emulator/ui/component/CaptionText.kt
zhufucdev
550,925,935
false
{"Kotlin": 229760}
package com.zhufucdev.motion_emulator.ui.component import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight @Composable fun CaptionText(modifier: Modifier = Modifier, text: String) { Text( text = text, style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Bold), color = MaterialTheme.colorScheme.secondary, modifier = modifier ) }
15
Kotlin
16
231
a6307c7ae25cadc9271f867eed340b584b580397
551
MotionEmulator
Apache License 2.0
app/src/main/java/com/mattskala/trezorwallet/ui/addresses/AddressesViewModel.kt
MattSkala
119,818,836
false
null
package com.mattskala.trezorwallet.ui.addresses import android.app.Application import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.Observer import com.mattskala.trezorwallet.R import com.mattskala.trezorwallet.data.AppDatabase import com.mattskala.trezorwallet.data.entity.Address import com.mattskala.trezorwallet.data.item.AddressItem import com.mattskala.trezorwallet.data.item.ButtonItem import com.mattskala.trezorwallet.data.item.Item import com.mattskala.trezorwallet.data.item.SectionItem import com.mattskala.trezorwallet.ui.BaseViewModel import org.kodein.di.generic.instance /** * A ViewModel for AddressesFragment. */ class AddressesViewModel(app: Application) : BaseViewModel(app) { companion object { private const val FRESH_ADDRESSES_LIMIT = 20 } private val database: AppDatabase by instance() val items = MutableLiveData<List<Item>>() private var initialized = false private lateinit var accountId: String private var addresses: List<Address> = mutableListOf() private var previousAddressesExpanded = false private var freshAddressesCount = 1 private val addressesLiveData by lazy { database.addressDao().getByAccountLiveData(accountId, false) } private val addressesObserver = Observer<List<Address>> { if (it != null) { addresses = it updateItems() } } fun start(accountId: String) { if (!initialized) { this.accountId = accountId addressesLiveData.observeForever(addressesObserver) initialized = true } } fun togglePreviousAddresses() { previousAddressesExpanded = !previousAddressesExpanded updateItems() } fun addFreshAddress() { freshAddressesCount++ updateItems() } override fun onCleared() { addressesLiveData.removeObserver(addressesObserver) } private fun updateItems() { val items = mutableListOf<Item>() val firstFreshIndex = findFirstFreshIndex(addresses) items.add(SectionItem(R.string.previous_addresses, true, previousAddressesExpanded)) addresses.forEachIndexed { index, address -> if (index == firstFreshIndex) { items.add(SectionItem(R.string.fresh_address)) } if ((index < firstFreshIndex && previousAddressesExpanded) || (index >= firstFreshIndex && index < firstFreshIndex + freshAddressesCount)) { items.add(AddressItem(address)) } } if (freshAddressesCount < FRESH_ADDRESSES_LIMIT) { items.add(ButtonItem(R.string.more_addresses)) } this.items.value = items } private fun findFirstFreshIndex(addresses: List<Address>): Int { var lastUsedIndex: Int = -1 addresses.forEachIndexed { index, address -> if (address.totalReceived > 0) { lastUsedIndex = index } } return lastUsedIndex + 1 } }
4
null
4
8
f3edc15ded7d79acb2ba8d5d65cd82c407b1fe95
3,068
trezor-wallet
MIT License
boxicons/src/commonMain/kotlin/com/woowla/compose/icon/collections/boxicons/boxicons/solid/BxsHappy.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.boxicons.boxicons.solid import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.boxicons.boxicons.SolidGroup public val SolidGroup.BxsHappy: ImageVector get() { if (_bxsHappy != null) { return _bxsHappy!! } _bxsHappy = Builder(name = "BxsHappy", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 2.0f) curveTo(6.486f, 2.0f, 2.0f, 6.486f, 2.0f, 12.0f) reflectiveCurveToRelative(4.486f, 10.0f, 10.0f, 10.0f) reflectiveCurveToRelative(10.0f, -4.486f, 10.0f, -10.0f) reflectiveCurveTo(17.514f, 2.0f, 12.0f, 2.0f) close() moveTo(15.493f, 9.0f) arcToRelative(1.494f, 1.494f, 0.0f, true, true, -0.001f, 2.987f) arcTo(1.494f, 1.494f, 0.0f, false, true, 15.493f, 9.0f) close() moveTo(8.5f, 9.0f) arcToRelative(1.5f, 1.5f, 0.0f, true, true, -0.001f, 3.001f) arcTo(1.5f, 1.5f, 0.0f, false, true, 8.5f, 9.0f) close() moveTo(12.0f, 18.0f) curveToRelative(-4.0f, 0.0f, -5.0f, -4.0f, -5.0f, -4.0f) horizontalLineToRelative(10.0f) reflectiveCurveToRelative(-1.0f, 4.0f, -5.0f, 4.0f) close() } } .build() return _bxsHappy!! } private var _bxsHappy: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
2,265
compose-icon-collections
MIT License
react-table-kotlin/src/jsMain/kotlin/tanstack/table/core/GroupingColumnDef.kt
karakum-team
393,199,102
false
null
// Automatically generated - do not modify! package tanstack.table.core external interface GroupingColumnDef<TData : RowData, TValue> { var aggregationFn: AggregationFnOption<TData>? var aggregatedCell: ColumnDefTemplate<CellContext<TData, TValue>>? var enableGrouping: Boolean? var getGroupingValue: ((row: TData) -> Any)? }
0
null
6
26
9100a0654c91ca4cd0cf3b2b6657bf653d7207e2
344
types-kotlin
Apache License 2.0
feature/favourite/src/main/java/st/slex/csplashscreen/feature/favourite/di/FavouriteComponent.kt
stslex
413,161,718
false
{"Kotlin": 324470, "Ruby": 1145}
package st.slex.csplashscreen.feature.favourite.di import androidx.lifecycle.ViewModelProvider import dagger.Component import st.slex.csplashscreen.core.favourite.di.FavouriteApi import st.slex.csplashscreen.core.ui.di.NavigationApi @Component( dependencies = [FavouriteDependencies::class], modules = [FavouriteModule::class] ) @FavouriteScope interface FavouriteComponent { @Component.Factory interface Factory { fun create(dependencies: FavouriteDependencies): FavouriteComponent } @Component(dependencies = [FavouriteApi::class, NavigationApi::class]) @FavouriteScope interface FavouriteDependenciesComponent : FavouriteDependencies { @Component.Factory interface Factory { fun create( favouriteApi: FavouriteApi, navigationApi: NavigationApi ): FavouriteDependencies } } val viewModelFactory: ViewModelProvider.Factory }
3
Kotlin
0
3
3bcac8199765dcac567e39836c53be89a9765843
961
CSplashScreen
Apache License 2.0
Day_7-15_whyNotesApp/WhyNote/app/src/main/java/com/example/whynote/MyApplication.kt
SohailAhmed145
803,098,555
false
{"Kotlin": 106855}
package com.example.whynote import androidx.compose.runtime.Composable @Composable fun MyApplication(){ }
0
Kotlin
0
0
366720dd103e4922d3e52af7c1b8afe114908d4f
108
60_Day_KMP_App_development
MIT License
src/main/kotlin/net/olegg/lottie/idea/Icons.kt
0legg
81,909,274
false
null
package net.olegg.lottie.idea import com.intellij.openapi.util.IconLoader /** * Helper class to store icons. */ object Icons { fun load(path: String) = IconLoader.getIcon(path) val LOAD = load("/icons/wiggle.png") val OPEN = load("/icons/in.png") val PLAY = load("/icons/play.png") val PAUSE = load("/icons/pause.png") val LOOP = load("/icons/repeat.png") }
7
Kotlin
1
36
86ca74f91d5c5e5b7cfac2978c63ed0c99c25abd
386
lottie-idea
MIT License
kotstruct-generator/src/test/kotlin/io/github/kotstruct/happy/nested/onetoone/NestedOneToOneMapperTest.kt
vooft
739,672,405
false
{"Kotlin": 62028}
package io.github.kotstruct.happy.nested.onetoone import com.tschuchort.compiletesting.KotlinCompilation import com.tschuchort.compiletesting.kspSourcesDir import com.tschuchort.compiletesting.symbolProcessorProviders import io.github.kotstruct.GENERATED_PACKAGE import io.github.kotstruct.GENERATED_PREFIX import io.github.kotstruct.KotStructDescribedBy import io.github.kotstruct.KotStructDescriptor import io.github.kotstruct.KotStructDescriptor.Companion.kotStruct import io.github.kotstruct.KotStructMapper import io.github.kotstruct.KotStructMapperDslProcessorProvider import io.kotest.matchers.paths.shouldExist import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test import java.util.UUID import kotlin.io.path.Path import kotlin.io.path.readText class NestedOneToOneMapperTest { @Test fun `should generate class with nested classes`() { val compilation = KotlinCompilation().also { it.sources = listOf() it.symbolProcessorProviders = listOf(KotStructMapperDslProcessorProvider(this::class)) it.inheritClassPath = true it.messageOutputStream = System.out // see diagnostics in real time } val result = compilation.compile() result.exitCode shouldBe KotlinCompilation.ExitCode.OK val generatedFile = compilation.kspSourcesDir.toPath().resolve("kotlin") .resolve(Path(".", *GENERATED_PACKAGE.split(".").toTypedArray())) .resolve("$GENERATED_PREFIX${Mappers.MyMapper::class.simpleName}.kt") generatedFile.shouldExist() println(generatedFile.readText()) } @Suppress("unused") class Mappers { data class SourceDto(val id: IdWrapper) { data class IdWrapper(val id: ValueWrapper) { data class ValueWrapper(val value: String) } } data class TargetDto(val id: IdWrapper) { data class IdWrapper(val id: ValueWrapper) { data class ValueWrapper(val value: String) } } @KotStructDescribedBy(MyMapperDescriptor::class) interface MyMapper : KotStructMapper { fun map(src: SourceDto): TargetDto } object MyMapperDescriptor : KotStructDescriptor by kotStruct({ mapperFor<String, UUID> { UUID.fromString(it) } mapperFor<UUID, String> { it.toString() } }) } }
1
Kotlin
1
1
e0b759af67c4286df199b2442492d69ef2644a7d
2,409
kotstruct
Apache License 2.0
middleware/src/main/java/com/anytypeio/anytype/middleware/interactor/MiddlewareEventMapper.kt
anyproto
647,371,233
false
{"Kotlin": 11623123, "Java": 69306, "Shell": 11350, "Makefile": 1334}
package com.anytypeio.anytype.middleware.interactor import com.anytypeio.anytype.core_models.Block import com.anytypeio.anytype.core_models.Event import com.anytypeio.anytype.middleware.BuildConfig import com.anytypeio.anytype.middleware.mappers.MWidgetLayout import com.anytypeio.anytype.middleware.mappers.toCoreModel import com.anytypeio.anytype.middleware.mappers.toCoreModels import com.anytypeio.anytype.middleware.mappers.toCoreModelsAlign import com.anytypeio.anytype.middleware.mappers.toCoreModelsBookmarkState import timber.log.Timber fun anytype.Event.Message.toCoreModels( context: String ): Event.Command? = when { blockAdd != null -> { val event = blockAdd checkNotNull(event) Event.Command.AddBlock( context = context, blocks = event.blocks.toCoreModels() ) } blockSetText != null -> { val event = blockSetText checkNotNull(event) Event.Command.GranularChange( context = context, id = event.id, text = event.text?.value_, style = event.style?.value_?.toCoreModels(), color = event.color?.value_, marks = event.marks?.value_?.marks?.map { it.toCoreModels() }, checked = event.checked?.value_, emojiIcon = event.iconEmoji?.value_, imageIcon = event.iconImage?.value_, ) } blockSetBackgroundColor != null -> { val event = blockSetBackgroundColor checkNotNull(event) Event.Command.GranularChange( context = context, id = event.id, backgroundColor = event.backgroundColor ) } blockDelete != null -> { val event = blockDelete checkNotNull(event) Event.Command.DeleteBlock( context = context, targets = event.blockIds ) } blockSetChildrenIds != null -> { val event = blockSetChildrenIds checkNotNull(event) Event.Command.UpdateStructure( context = context, id = event.id, children = event.childrenIds ) } objectDetailsSet != null -> { val event = objectDetailsSet checkNotNull(event) Event.Command.Details.Set( context = context, target = event.id, details = event.details.toCoreModel() ) } objectDetailsAmend != null -> { val event = objectDetailsAmend checkNotNull(event) Event.Command.Details.Amend( context = context, target = event.id, details = event.details.associate { it.key to it.value_ } ) } objectDetailsUnset != null -> { val event = objectDetailsUnset checkNotNull(event) Event.Command.Details.Unset( context = context, target = event.id, keys = event.keys ) } blockSetLink != null -> { val event = blockSetLink checkNotNull(event) Event.Command.LinkGranularChange( context = context, id = event.id, target = event.targetBlockId?.value_.orEmpty(), iconSize = event.iconSize?.value_?.toCoreModel(), cardStyle = event.cardStyle?.value_?.toCoreModel(), description = event.description?.value_?.toCoreModel(), relations = event.relations?.value_?.toSet() ) } blockSetAlign != null -> { val event = blockSetAlign checkNotNull(event) Event.Command.GranularChange( context = context, id = event.id, alignment = event.align.toCoreModelsAlign() ) } blockSetFields != null -> { val event = blockSetFields checkNotNull(event) Event.Command.UpdateFields( context = context, target = event.id, fields = event.fields.toCoreModel() ) } blockSetFile != null -> { val event = blockSetFile checkNotNull(event) with(event) { Event.Command.UpdateFileBlock( context = context, id = id, state = state?.value_?.toCoreModels(), type = type?.value_?.toCoreModels(), name = name?.value_, hash = hash?.value_, mime = mime?.value_, size = size?.value_ ) } } blockSetBookmark != null -> { val event = blockSetBookmark checkNotNull(event) Event.Command.BookmarkGranularChange( context = context, target = event.id, url = event.url?.value_, title = event.title?.value_, description = event.description?.value_, image = event.imageHash?.value_, favicon = event.faviconHash?.value_, targetObjectId = event.targetObjectId?.value_, state = event.state?.value_?.toCoreModelsBookmarkState() ) } blockDataviewRelationSet != null -> { val event = blockDataviewRelationSet checkNotNull(event) Event.Command.DataView.SetRelation( dv = event.id, context = context, links = event.relationLinks.map { it.toCoreModels() } ) } blockSetDiv != null -> { val event = blockSetDiv checkNotNull(event) val style = event.style checkNotNull(style) Event.Command.UpdateDividerBlock( context = context, id = event.id, style = style.value_.toCoreModels() ) } blockSetWidget != null -> { val event = blockSetWidget checkNotNull(event) Event.Command.Widgets.SetWidget( context = context, widget = event.id, activeView = event.viewId?.value_, limit = event.limit?.value_, layout = when(event.layout?.value_) { MWidgetLayout.Link -> Block.Content.Widget.Layout.LINK MWidgetLayout.Tree -> Block.Content.Widget.Layout.TREE MWidgetLayout.List -> Block.Content.Widget.Layout.LIST MWidgetLayout.CompactList -> Block.Content.Widget.Layout.COMPACT_LIST else -> null } ) } blockDataviewViewSet != null -> { val event = blockDataviewViewSet checkNotNull(event) val view = event.view checkNotNull(view) Event.Command.DataView.SetView( context = context, target = event.id, viewerId = event.viewId, viewer = view.toCoreModels() ) } blockDataviewViewDelete != null -> { val event = blockDataviewViewDelete checkNotNull(event) Event.Command.DataView.DeleteView( context = context, target = event.id, viewer = event.viewId ) } blockDataviewViewOrder != null -> { val event = blockDataviewViewOrder checkNotNull(event) Event.Command.DataView.OrderViews( context = context, dv = event.id, order = event.viewIds ) } blockDataviewTargetObjectIdSet != null -> { val event = blockDataviewTargetObjectIdSet checkNotNull(event) Event.Command.DataView.SetTargetObjectId( context = context, dv = event.id, targetObjectId = event.targetObjectId ) } blockSetRelation != null -> { val event = blockSetRelation checkNotNull(event) Event.Command.BlockEvent.SetRelation( context = context, id = event.id, key = event.key?.value_ ) } objectRelationsAmend != null -> { val event = objectRelationsAmend checkNotNull(event) Event.Command.ObjectRelationLinks.Amend( context = context, id = event.id, relationLinks = event.relationLinks.map { it.toCoreModels() } ) } objectRelationsRemove != null -> { val event = objectRelationsRemove checkNotNull(event) Event.Command.ObjectRelationLinks.Remove( context = context, id = event.id, keys = event.relationKeys ) } blockDataviewViewUpdate != null -> { val event = blockDataviewViewUpdate checkNotNull(event) Event.Command.DataView.UpdateView( context = context, block = event.id, viewerId = event.viewId, filterUpdates = event.filter.mapNotNull { filter -> filter.toCoreModels() }, sortUpdates = event.sort.mapNotNull { sort -> sort.toCoreModels() }, relationUpdates = event.relation.mapNotNull { relation -> relation.toCoreModels() }, fields = event.fields?.toCoreModels() ) } blockDataviewRelationDelete != null -> { val event = blockDataviewRelationDelete checkNotNull(event) Event.Command.DataView.DeleteRelation( context = context, dv = event.id, keys = event.relationKeys ) } blockDataviewIsCollectionSet != null -> { val event = blockDataviewIsCollectionSet checkNotNull(event) Event.Command.DataView.SetIsCollection( context = context, dv = event.id, isCollection = event.value_ ) } else -> { if (BuildConfig.DEBUG) { Timber.w("Skipped event while mapping: $this") } null } }
45
Kotlin
43
528
c708958dcb96201ab7bb064c838ffa8272d5f326
9,758
anytype-kotlin
RSA Message-Digest License
app/src/main/java/com/cmf/userslist/ui/UserMapper.kt
CristianFanjul
451,215,919
false
null
package com.cmf.userslist.ui import com.cmf.userslist.model.User import com.cmf.userslist.ui.main.UserUiModel class UserMapper { fun userToUiModel(user: User): UserUiModel { return UserUiModel( id = user.id, name = "${user.name} ${user.lastName}", biography = user.biography, imageUri = user.imageUri ) } }
0
Kotlin
0
0
ab149412c16ff8467d6820cfe9cd5b4669813ac0
380
users-list
Apache License 2.0
src/main/kotlin/com/bkahlert/kustomize/patch/WifiPowerSafeModePatch.kt
bkahlert
390,165,287
false
null
package com.bkahlert.kustomize.patch import com.bkahlert.kustomize.os.LinuxRoot import com.bkahlert.kustomize.os.OperatingSystemImage /** * Applied to an [OperatingSystemImage] this [Patch] * disables the power-safe mode for the wifi adapter. */ class WifiPowerSafeModePatch : (OperatingSystemImage) -> PhasedPatch { override fun invoke(osImage: OperatingSystemImage): PhasedPatch = PhasedPatch.build( "Disable Wifi Power-Safe Mode", osImage ) { virtCustomize { firstBoot("Disable Wifi Power-Safe Mode") { file(LinuxRoot.etc.rc_local.pathString) { removeLine("exit 0") appendLine("/sbin/iw dev wlan0 set power_save off || true") appendLine("exit 0") } } } } }
10
Kotlin
0
2
0e0d325c42c5981e7eb43069e3da80c7cfc7564c
825
kustomize
MIT License
data/src/main/java/com/spiderbiggen/manhwa/data/usecase/read/SetReadImpl.kt
spiderbiggen
624,650,535
false
{"Kotlin": 118713}
package com.spiderbiggen.manhwa.data.usecase.read import com.spiderbiggen.manhwa.data.repository.ReadRepository import com.spiderbiggen.manhwa.domain.model.AppError import com.spiderbiggen.manhwa.domain.model.Either import com.spiderbiggen.manhwa.domain.usecase.read.SetRead import javax.inject.Inject class SetReadImpl @Inject constructor( private val readRepository: ReadRepository, ) : SetRead { override suspend fun invoke(chapterId: String, isRead: Boolean): Either<Unit, AppError> = Either.Left(readRepository.setRead(chapterId, isRead)) }
1
Kotlin
0
0
cbd3531735d456a0615f17f7fdf32b1364764c71
564
manhwa-reader
MIT License
imagepicker/src/main/java/dev/wendyyanto/imagepicker/di/Injector.kt
WendyYanto
184,189,739
false
null
package dev.wendyyanto.imagepicker.di object Injector { val maps: MutableMap<Class<*>, Any> = mutableMapOf() inline fun <reified T> get(): T { return maps[T::class.java] as T } fun store(clazz: Class<*>, obj: Any) { maps[clazz] = obj } fun remove(clazz: Class<*>) { maps.remove(clazz) } }
0
Kotlin
0
3
8ccf38ec2b11c87381be0f03292be9be44a0c67c
346
android-image-picker
Apache License 2.0
app/src/main/java/com/jinbo/newsdemo/logic/network/ServiceCreator.kt
AuPt666
394,197,132
false
null
package com.jinbo.newsdemo.logic.network import android.util.Log import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory /***********Retrofit构建器**************/ object ServiceCreator { private const val BASE_URL = "https://api.jisuapi.com" private val retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() fun <T> create(serviceClass: Class<T>): T { return retrofit.create(serviceClass) } inline fun <reified T> create(): T = create(T::class.java) }
0
Kotlin
0
0
896a55fffe64e7b2b7c2ddda6133c1f6ae333f44
584
NewsDemo
Apache License 2.0