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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/kotlin/cn/navigational/dbfx/navigator/folder/pg/PgSchemeFolder.kt
|
tivrfoa
| 303,001,716
| true
|
{"Kotlin": 108780, "Java": 52343, "CSS": 9400}
|
package cn.navigational.dbfx.navigator.folder.pg
import cn.navigational.dbfx.kit.SQLQuery
import cn.navigational.dbfx.kit.enums.Clients
import cn.navigational.dbfx.kit.postgres.PgQuery
import cn.navigational.dbfx.navigator.FolderItem
import cn.navigational.dbfx.navigator.scheme.ComSchemeItem
class PgSchemeFolder(private val database: String) : FolderItem() {
init {
value = "模式"
}
override suspend fun initFolder() {
if (this.children.isNotEmpty()) {
this.children.clear()
}
val query = SQLQuery.getClQuery(Clients.POSTGRESQL) as PgQuery
val list = query.queryDbScheme(database, currentClient.client)
val items = list.map {
ComSchemeItem(Clients.POSTGRESQL,"${database}.$it")
}.toList()
this.children.addAll(items)
}
}
| 0
| null |
0
| 0
|
84074162f9765f5f480f77bfd6c5b220a1f093e3
| 828
|
dbfx
|
Apache License 2.0
|
compiler/tests-spec/testData/psi/linked/constant-literals/boolean-literals/p-1/pos/2.11.kt
|
haerulmuttaqin
| 156,727,010
| true
|
{"Kotlin": 31513732, "Java": 7641810, "JavaScript": 152543, "HTML": 68411, "Lex": 18275, "IDL": 10060, "ANTLR": 9803, "Shell": 6769, "Groovy": 5466, "CSS": 4679, "Batchfile": 4437}
|
/*
KOTLIN PSI SPEC TEST (POSITIVE)
SECTIONS: constant-literals, boolean-literals
PARAGRAPH: 1
SENTENCE: [2] These are strong keywords which cannot be used as identifiers unless escaped.
NUMBER: 11
DESCRIPTION: The use of Boolean literals as the identifier (with backtick) in the function.
NOTE: this test data is generated by FeatureInteractionTestDataGenerator. DO NOT MODIFY CODE MANUALLY!
*/
fun `true`() {}
suspend fun `false`() {}
inline fun <T: Number> `true`() = `false`
| 0
|
Kotlin
|
1
| 2
|
8f2117685f9f1b76b7f61ef67c0f58431bbf2f0e
| 490
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/example/factoryfm/db/AlbumTypeConverter.kt
|
supermzn
| 160,585,725
| false
| null |
package com.example.factoryfm.db
import android.arch.persistence.room.TypeConverter
import com.example.factoryfm.model.FmImage
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
class AlbumTypeConverter {
val gson: Gson = Gson()
@TypeConverter
fun listToString(list: List<FmImage>): String? {
return gson.toJson(list)
}
@TypeConverter
fun stringToList(data: String?): List<FmImage> {
return if (data == null)
emptyList()
else {
gson.fromJson(data, object : TypeToken<List<FmImage>>() {}.type)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d8d57b413ff0879890a0cb7b4a57cb56d940a0f8
| 606
|
factoryFM
|
MIT License
|
ontrack-extension-jenkins/src/main/java/net/nemerosa/ontrack/extension/jenkins/client/DefaultJenkinsClientFactory.kt
|
nemerosa
| 19,351,480
| false
| null |
package net.nemerosa.ontrack.extension.jenkins.client
import net.nemerosa.ontrack.extension.jenkins.JenkinsConfiguration
import net.nemerosa.ontrack.extension.jenkins.JenkinsConfigurationProperties
import org.springframework.boot.web.client.RestTemplateBuilder
import org.springframework.stereotype.Component
import java.time.Duration
@Component
class DefaultJenkinsClientFactory(
private val jenkinsConfigurationProperties: JenkinsConfigurationProperties,
) : JenkinsClientFactory {
override fun getClient(configuration: JenkinsConfiguration): JenkinsClient {
return DefaultJenkinsClient(
url = configuration.url,
client = RestTemplateBuilder()
.rootUri(configuration.url)
.basicAuthentication(configuration.user, configuration.password)
.setReadTimeout(Duration.ofSeconds(jenkinsConfigurationProperties.timeout.toLong()))
.build()
)
}
}
| 57
| null |
27
| 97
|
7c71a3047401e088ba0c6d43aa3a96422024857f
| 959
|
ontrack
|
MIT License
|
domain/src/main/java/com/escodro/domain/usecase/task/UpdateTask.kt
|
igorescodro
| 116,942,964
| false
| null |
package com.escodro.domain.usecase.task
import com.escodro.domain.model.Task
/**
* Use case to update a task from the database.
*/
interface UpdateTask {
/**
* Updates a task.
*
* @param task the task to be updated
*
* @return observable to be subscribe
*/
suspend operator fun invoke(task: Task)
}
| 16
|
Kotlin
|
106
| 999
|
e64a652c6b62dd5ca80c2c128186ef4b8bf6cf63
| 342
|
alkaa
|
Apache License 2.0
|
features/films_favourite/src/main/java/com/doskoch/movies/features/films_favourite/repository/db/FavouriteFilmsDbRepository.kt
|
VitaliyDoskoch
| 263,280,184
| false
| null |
package com.doskoch.movies.features.films_favourite.repository.db
import com.doskoch.movies.core.components.database.DatabaseConnector
import com.doskoch.movies.database.BaseEntity
import com.doskoch.movies.database.modules.films.entity.DbFavouriteFilm
import com.doskoch.movies.database.modules.films.view.Film
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Single
import kotlin.reflect.KClass
class FavouriteFilmsDbRepository(private val dependencies: Dependencies) {
data class Dependencies(val dbConnector: DatabaseConnector)
fun observeChanges(): Flowable<Set<KClass<out BaseEntity>>> {
return dependencies.dbConnector.observeChanges(setOf(DbFavouriteFilm::class), true)
}
fun count(): Single<Int> {
return dependencies.dbConnector.select {
Single.fromCallable { dbFavouriteFilmDao().count() }
}
}
fun get(limit: Int, offset: Int): Single<List<Film>> {
return dependencies.dbConnector.select {
Single.fromCallable { filmDao().selectFavourite(limit, offset) }
}
}
fun delete(item: Film): Completable {
return dependencies.dbConnector.modify {
Completable.fromCallable { dbFavouriteFilmDao().delete(item.id) }
}
}
}
| 0
|
Kotlin
|
0
| 0
|
9de9670b1b24934a39122b58517d026569cea1d3
| 1,287
|
Movies
|
MIT License
|
shared/src/commonMain/kotlin/uk/co/sentinelweb/cuer/app/ui/cast/CastDialogViewModel.kt
|
sentinelweb
| 220,796,368
| false
|
{"Kotlin": 2627509, "CSS": 205156, "Java": 98919, "Swift": 85812, "HTML": 19322, "JavaScript": 12105, "Ruby": 2170}
|
package uk.co.sentinelweb.cuer.app.ui.cast
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import uk.co.sentinelweb.cuer.app.ui.remotes.selector.RemotesDialogContract
import uk.co.sentinelweb.cuer.core.providers.CoroutineContextProvider
class CastDialogViewModel(
private val castController: CastController,
private val remotesLauncher: RemotesDialogContract.Launcher,
private val coroutines: CoroutineContextProvider
) {
private val _model = MutableStateFlow(CastDialogModel.blank)
val model: Flow<CastDialogModel> = _model
init {
coroutines.mainScope.launch {
_model.value = castController.map()
}
}
fun connectCuerCast() {
if (!_model.value.cuerCastStatus.isConnected) {
remotesLauncher.launchRemotesDialog({ remoteNode, selectedScreen ->
remotesLauncher.hideRemotesDialog()
castController.connectCuerCast(remoteNode, selectedScreen)
}, null)
}
}
fun disconnectCuerCast() {
castController.connectCuerCast(null, null)
coroutines.mainScope.launch {
_model.value = castController.map()
}
}
fun stopCuerCast() {
coroutines.mainScope.launch {
castController.stopCuerCast()
_model.value = castController.map()
}
}
fun focusCuerCast() {
coroutines.mainScope.launch {
castController.focusCuerCast()
_model.value = castController.map()
}
}
fun connectChromeCast() {
if (!_model.value.chromeCastStatus.isConnected) {
castController.connectChromeCast()
coroutines.mainScope.launch {
_model.value = castController.map()
}
}
}
fun disconnectChromeCast() {
castController.disonnectChromeCast()
coroutines.mainScope.launch {
_model.value = castController.map()
}
}
}
| 95
|
Kotlin
|
0
| 2
|
1e3522bffa43f75f0e030f7ead3ce1b6873f5bd6
| 2,029
|
cuer
|
Apache License 2.0
|
app/src/main/java/ro/alexmamo/firestorecleanarchitecture/data/repository/BooksRepositoryImpl.kt
|
alexmamo
| 413,736,186
| false
| null |
package ro.alexmamo.firestorecleanarchitecture.data.repository
import com.google.firebase.firestore.CollectionReference
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.tasks.await
import ro.alexmamo.firestorecleanarchitecture.core.Constants.TITLE
import ro.alexmamo.firestorecleanarchitecture.domain.model.Book
import ro.alexmamo.firestorecleanarchitecture.domain.model.Response.Failure
import ro.alexmamo.firestorecleanarchitecture.domain.model.Response.Success
import ro.alexmamo.firestorecleanarchitecture.domain.repository.AddBookResponse
import ro.alexmamo.firestorecleanarchitecture.domain.repository.BooksRepository
import ro.alexmamo.firestorecleanarchitecture.domain.repository.DeleteBookResponse
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class BooksRepositoryImpl @Inject constructor(
private val booksRef: CollectionReference
): BooksRepository {
override fun getBooksFromFirestore() = callbackFlow {
val snapshotListener = booksRef.orderBy(TITLE).addSnapshotListener { snapshot, e ->
val booksResponse = if (snapshot != null) {
val books = snapshot.toObjects(Book::class.java)
Success(books)
} else {
Failure(e)
}
trySend(booksResponse)
}
awaitClose {
snapshotListener.remove()
}
}
override suspend fun addBookToFirestore(title: String, author: String): AddBookResponse {
return try {
val id = booksRef.document().id
val book = Book(
id = id,
title = title,
author = author
)
booksRef.document(id).set(book).await()
Success(true)
} catch (e: Exception) {
Failure(e)
}
}
override suspend fun deleteBookFromFirestore(bookId: String): DeleteBookResponse {
return try {
booksRef.document(bookId).delete().await()
Success(true)
} catch (e: Exception) {
Failure(e)
}
}
}
| 0
| null |
31
| 98
|
354d33ad5811aae9d3b791386111c47452b4207b
| 2,146
|
FirestoreCleanArchitectureApp
|
Apache License 2.0
|
realm/realm-annotations-processor/src/main/java/io/realm/processor/RealmProxyMediatorGenerator.kt
|
realm
| 4,084,908
| false
| null |
/*
* Copyright 2019 Realm 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.realm.processor
import com.squareup.javawriter.JavaWriter
import io.realm.annotations.RealmModule
import java.io.BufferedWriter
import java.io.IOException
import java.util.*
import javax.annotation.processing.ProcessingEnvironment
import javax.lang.model.element.Modifier
import javax.tools.JavaFileObject
class RealmProxyMediatorGenerator(private val processingEnvironment: ProcessingEnvironment,
private val className: SimpleClassName,
classesToValidate: Set<ClassMetaData>) {
private val qualifiedModelClasses = ArrayList<QualifiedClassName>()
private val qualifiedProxyClasses = ArrayList<QualifiedClassName>()
private val simpleModelClassNames = ArrayList<SimpleClassName>()
private val internalClassNames = ArrayList<String>()
private val embeddedClass = ArrayList<Boolean>()
private val primaryKeyClasses = mutableListOf<QualifiedClassName>()
init {
// Sort classes to ensure deterministic output. This is relevant when e.g. using Gradle
// Remote Cache since the order is not guaranteed between OS and Java versions.
for (metadata in classesToValidate.toSortedSet(compareByDescending { it.qualifiedClassName.name })) {
qualifiedModelClasses.add(metadata.qualifiedClassName)
val qualifiedProxyClassName = QualifiedClassName("${Constants.REALM_PACKAGE_NAME}.${Utils.getProxyClassName(metadata.qualifiedClassName)}")
qualifiedProxyClasses.add(qualifiedProxyClassName)
simpleModelClassNames.add(metadata.simpleJavaClassName)
internalClassNames.add(metadata.internalClassName)
embeddedClass.add(metadata.embedded)
if(metadata.primaryKey != null) {
primaryKeyClasses.add(metadata.qualifiedClassName)
}
}
}
@Throws(IOException::class)
fun generate() {
val qualifiedGeneratedClassName: String = String.format(Locale.US, "%s.%sMediator", Constants.REALM_PACKAGE_NAME, className)
val sourceFile: JavaFileObject = processingEnvironment.filer.createSourceFile(qualifiedGeneratedClassName)
val imports = ArrayList(Arrays.asList("android.util.JsonReader",
"java.io.IOException",
"java.util.Collections",
"java.util.HashSet",
"java.util.List",
"java.util.Map",
"java.util.HashMap",
"java.util.Set",
"java.util.Iterator",
"java.util.Collection",
"io.realm.ImportFlag",
"io.realm.internal.ColumnInfo",
"io.realm.internal.RealmObjectProxy",
"io.realm.internal.RealmProxyMediator",
"io.realm.internal.Row",
"io.realm.internal.OsSchemaInfo",
"io.realm.internal.OsObjectSchemaInfo",
"org.json.JSONException",
"org.json.JSONObject"))
val writer = JavaWriter(BufferedWriter(sourceFile.openWriter()))
writer.apply {
indent = " "
emitPackage(Constants.REALM_PACKAGE_NAME)
emitEmptyLine()
emitImports(imports)
emitEmptyLine()
emitAnnotation(RealmModule::class.java)
beginType(qualifiedGeneratedClassName, // full qualified name of the item to generate
"class", // the type of the item
emptySet(), // modifiers to apply
"RealmProxyMediator") // class to extend
emitEmptyLine()
emitFields(this)
emitGetExpectedObjectSchemaInfoMap(this)
emitCreateColumnInfoMethod(this)
emitGetSimpleClassNameMethod(this)
emitGetClazzClassNameMethod(this)
emitHasPrimaryKeyMethod(this)
emitNewInstanceMethod(this)
emitGetClassModelList(this)
emitCopyOrUpdateMethod(this)
emitInsertObjectToRealmMethod(this)
emitInsertListToRealmMethod(this)
emitInsertOrUpdateObjectToRealmMethod(this)
emitInsertOrUpdateListToRealmMethod(this)
emitCreteOrUpdateUsingJsonObject(this)
emitCreateUsingJsonStream(this)
emitCreateDetachedCopyMethod(this)
emitIsEmbeddedMethod(this)
emitUpdateEmbeddedObjectMethod(this)
endType()
close()
}
}
@Throws(IOException::class)
private fun emitFields(writer: JavaWriter) {
writer.apply {
emitField("Set<Class<? extends RealmModel>>", "MODEL_CLASSES", EnumSet.of(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL))
beginInitializer(true)
emitStatement("Set<Class<? extends RealmModel>> modelClasses = new HashSet<Class<? extends RealmModel>>(%s)", qualifiedModelClasses.size)
for (clazz in qualifiedModelClasses) {
emitStatement("modelClasses.add(%s.class)", clazz)
}
emitStatement("MODEL_CLASSES = Collections.unmodifiableSet(modelClasses)")
endInitializer()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitGetExpectedObjectSchemaInfoMap(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod("Map<Class<? extends RealmModel>, OsObjectSchemaInfo>","getExpectedObjectSchemaInfoMap", EnumSet.of(Modifier.PUBLIC))
emitStatement("Map<Class<? extends RealmModel>, OsObjectSchemaInfo> infoMap = new HashMap<Class<? extends RealmModel>, OsObjectSchemaInfo>(%s)", qualifiedProxyClasses.size)
for (i in qualifiedProxyClasses.indices) {
emitStatement("infoMap.put(%s.class, %s.getExpectedObjectSchemaInfo())", qualifiedModelClasses[i], qualifiedProxyClasses[i])
}
emitStatement("return infoMap")
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitCreateColumnInfoMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"ColumnInfo",
"createColumnInfo",
EnumSet.of(Modifier.PUBLIC),
"Class<? extends RealmModel>", "clazz", // Argument type & argument name
"OsSchemaInfo", "schemaInfo"
)
emitMediatorShortCircuitSwitch(writer, emitStatement = { i: Int ->
emitStatement("return %s.createColumnInfo(schemaInfo)", qualifiedProxyClasses[i])
})
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitGetSimpleClassNameMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"String",
"getSimpleClassNameImpl",
EnumSet.of(Modifier.PUBLIC),
"Class<? extends RealmModel>", "clazz"
)
emitMediatorShortCircuitSwitch(writer, emitStatement = { i: Int ->
emitStatement("return \"%s\"", internalClassNames[i])
})
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitGetClazzClassNameMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"Class<? extends RealmModel>",
"getClazzImpl",
EnumSet.of(Modifier.PUBLIC),
"String", "className"
)
emitMediatorInverseShortCircuitSwitch(writer, emitStatement = { i: Int ->
emitStatement("return %s.class", qualifiedModelClasses[i])
})
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitHasPrimaryKeyMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"boolean",
"hasPrimaryKeyImpl",
EnumSet.of(Modifier.PUBLIC),
"Class<? extends RealmModel>", "clazz"
)
if (primaryKeyClasses.size == 0) {
emitStatement("return false")
} else {
val primaryKeyCondition = primaryKeyClasses.joinToString(".class.isAssignableFrom(clazz)\n|| ", "", ".class.isAssignableFrom(clazz)")
emitStatement("return %s", primaryKeyCondition)
}
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitNewInstanceMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"<E extends RealmModel> E",
"newInstance",
EnumSet.of(Modifier.PUBLIC),
"Class<E>", "clazz",
"Object", "baseRealm",
"Row", "row",
"ColumnInfo", "columnInfo",
"boolean", "acceptDefaultValue",
"List<String>", "excludeFields"
)
emitStatement("final BaseRealm.RealmObjectContext objectContext = BaseRealm.objectContext.get()")
beginControlFlow("try")
emitStatement("objectContext.set((BaseRealm) baseRealm, row, columnInfo, acceptDefaultValue, excludeFields)")
emitMediatorShortCircuitSwitch(writer, emitStatement = { i: Int ->
emitStatement("return clazz.cast(new %s())", qualifiedProxyClasses[i])
})
nextControlFlow("finally")
emitStatement("objectContext.clear()")
endControlFlow()
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitGetClassModelList(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod("Set<Class<? extends RealmModel>>", "getModelClasses", EnumSet.of(Modifier.PUBLIC))
emitStatement("return MODEL_CLASSES")
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitCopyOrUpdateMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"<E extends RealmModel> E",
"copyOrUpdate",
EnumSet.of(Modifier.PUBLIC),
"Realm", "realm",
"E", "obj",
"boolean", "update",
"Map<RealmModel, RealmObjectProxy>", "cache",
"Set<ImportFlag>", "flags"
)
emitSingleLineComment("This cast is correct because obj is either")
emitSingleLineComment("generated by RealmProxy or the original type extending directly from RealmObject")
emitStatement("@SuppressWarnings(\"unchecked\") Class<E> clazz = (Class<E>) ((obj instanceof RealmObjectProxy) ? obj.getClass().getSuperclass() : obj.getClass())")
emitEmptyLine()
emitMediatorShortCircuitSwitch(writer, false) { i: Int ->
emitStatement("%1\$s columnInfo = (%1\$s) realm.getSchema().getColumnInfo(%2\$s.class)", Utils.getSimpleColumnInfoClassName(qualifiedModelClasses[i]), qualifiedModelClasses[i])
emitStatement("return clazz.cast(%s.copyOrUpdate(realm, columnInfo, (%s) obj, update, cache, flags))", qualifiedProxyClasses[i], qualifiedModelClasses[i])
}
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitInsertObjectToRealmMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"long",
"insert",
EnumSet.of(Modifier.PUBLIC),
"Realm", "realm", "RealmModel", "object", "Map<RealmModel, Long>", "cache")
if (embeddedClass.contains(false)) {
emitSingleLineComment("This cast is correct because obj is either")
emitSingleLineComment("generated by RealmProxy or the original type extending directly from RealmObject")
emitStatement("@SuppressWarnings(\"unchecked\") Class<RealmModel> clazz = (Class<RealmModel>) ((object instanceof RealmObjectProxy) ? object.getClass().getSuperclass() : object.getClass())")
emitEmptyLine()
emitMediatorSwitch(writer, false, { i: Int ->
if (embeddedClass[i]) {
emitEmbeddedObjectsCannotBeCopiedException(writer)
} else {
emitStatement("return %s.insert(realm, (%s) object, cache)", qualifiedProxyClasses[i], qualifiedModelClasses[i])
}
})
} else {
emitEmbeddedObjectsCannotBeCopiedException(writer)
}
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitInsertOrUpdateObjectToRealmMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"long",
"insertOrUpdate",
EnumSet.of(Modifier.PUBLIC),
"Realm", "realm", "RealmModel", "obj", "Map<RealmModel, Long>", "cache")
if (embeddedClass.contains(false)) {
emitSingleLineComment("This cast is correct because obj is either")
emitSingleLineComment("generated by RealmProxy or the original type extending directly from RealmObject")
emitStatement("@SuppressWarnings(\"unchecked\") Class<RealmModel> clazz = (Class<RealmModel>) ((obj instanceof RealmObjectProxy) ? obj.getClass().getSuperclass() : obj.getClass())")
emitEmptyLine()
emitMediatorSwitch(writer, false, { i: Int ->
if (embeddedClass[i]) {
emitEmbeddedObjectsCannotBeCopiedException(writer)
} else {
emitStatement("return %s.insertOrUpdate(realm, (%s) obj, cache)", qualifiedProxyClasses[i], qualifiedModelClasses[i])
}
})
} else {
emitEmbeddedObjectsCannotBeCopiedException(writer)
}
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitInsertOrUpdateListToRealmMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"void",
"insertOrUpdate",
EnumSet.of(Modifier.PUBLIC),
"Realm", "realm", "Collection<? extends RealmModel>", "objects")
if (embeddedClass.contains(false)) {
emitStatement("Iterator<? extends RealmModel> iterator = objects.iterator()")
emitStatement("RealmModel object = null")
emitStatement("Map<RealmModel, Long> cache = new HashMap<RealmModel, Long>(objects.size())")
beginControlFlow("if (iterator.hasNext())")
emitSingleLineComment(" access the first element to figure out the clazz for the routing below")
emitStatement("object = iterator.next()")
emitSingleLineComment("This cast is correct because obj is either")
emitSingleLineComment("generated by RealmProxy or the original type extending directly from RealmObject")
emitStatement("@SuppressWarnings(\"unchecked\") Class<RealmModel> clazz = (Class<RealmModel>) ((object instanceof RealmObjectProxy) ? object.getClass().getSuperclass() : object.getClass())")
emitEmptyLine()
emitMediatorSwitch(writer, false) { i: Int ->
if (embeddedClass[i]) {
emitEmbeddedObjectsCannotBeCopiedException(writer)
} else {
emitStatement("%s.insertOrUpdate(realm, (%s) object, cache)", qualifiedProxyClasses[i], qualifiedModelClasses[i])
}
}
beginControlFlow("if (iterator.hasNext())")
emitMediatorSwitch(writer, false) { i: Int ->
if (embeddedClass[i]) {
emitEmbeddedObjectsCannotBeCopiedException(writer)
} else {
emitStatement("%s.insertOrUpdate(realm, iterator, cache)", qualifiedProxyClasses[i])
}
}
endControlFlow()
endControlFlow()
} else {
emitEmbeddedObjectsCannotBeCopiedException(writer)
}
endMethod()
emitEmptyLine()
}
}
private fun emitEmbeddedObjectsCannotBeCopiedException(writer: JavaWriter) {
writer.apply {
emitStatement("throw new IllegalArgumentException(\"Embedded objects cannot be copied into Realm by themselves. They need to be attached to a parent object\")")
}
}
@Throws(IOException::class)
private fun emitInsertListToRealmMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"void",
"insert",
EnumSet.of(Modifier.PUBLIC),
"Realm", "realm", "Collection<? extends RealmModel>", "objects")
if (embeddedClass.contains(false)) {
emitStatement("Iterator<? extends RealmModel> iterator = objects.iterator()")
emitStatement("RealmModel object = null")
emitStatement("Map<RealmModel, Long> cache = new HashMap<RealmModel, Long>(objects.size())")
beginControlFlow("if (iterator.hasNext())")
.emitSingleLineComment(" access the first element to figure out the clazz for the routing below")
.emitStatement("object = iterator.next()")
.emitSingleLineComment("This cast is correct because obj is either")
.emitSingleLineComment("generated by RealmProxy or the original type extending directly from RealmObject")
.emitStatement("@SuppressWarnings(\"unchecked\") Class<RealmModel> clazz = (Class<RealmModel>) ((object instanceof RealmObjectProxy) ? object.getClass().getSuperclass() : object.getClass())")
.emitEmptyLine()
emitMediatorSwitch(writer, false, { i: Int ->
if (embeddedClass[i]) {
emitEmbeddedObjectsCannotBeCopiedException(writer)
} else {
emitStatement("%s.insert(realm, (%s) object, cache)", qualifiedProxyClasses[i], qualifiedModelClasses[i])
}
})
beginControlFlow("if (iterator.hasNext())")
emitMediatorSwitch(writer, false, { i: Int ->
if (embeddedClass[i]) {
emitEmbeddedObjectsCannotBeCopiedException(writer)
} else {
emitStatement("%s.insert(realm, iterator, cache)", qualifiedProxyClasses[i])
}
})
endControlFlow()
endControlFlow()
} else {
emitEmbeddedObjectsCannotBeCopiedException(writer)
}
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitCreteOrUpdateUsingJsonObject(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"<E extends RealmModel> E",
"createOrUpdateUsingJsonObject",
EnumSet.of(Modifier.PUBLIC),
Arrays.asList("Class<E>", "clazz", "Realm", "realm", "JSONObject", "json", "boolean", "update"),
Arrays.asList("JSONException")
)
emitMediatorShortCircuitSwitch(writer, emitStatement = { i: Int ->
if (!embeddedClass[i]) {
emitStatement("return clazz.cast(%s.createOrUpdateUsingJsonObject(realm, json, update))", qualifiedProxyClasses[i])
} else {
emitStatement("throw new IllegalArgumentException(\"Importing embedded classes from JSON without a parent is not allowed\")")
}
})
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitCreateUsingJsonStream(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"<E extends RealmModel> E",
"createUsingJsonStream",
EnumSet.of(Modifier.PUBLIC),
Arrays.asList("Class<E>", "clazz", "Realm", "realm", "JsonReader", "reader"),
Arrays.asList("java.io.IOException")
)
emitMediatorShortCircuitSwitch(writer, emitStatement = { i: Int ->
if (!embeddedClass[i]) {
emitStatement("return clazz.cast(%s.createUsingJsonStream(realm, reader))", qualifiedProxyClasses[i])
} else {
emitStatement("throw new IllegalArgumentException(\"Importing embedded classes from JSON without a parent is not allowed\")")
}
})
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitCreateDetachedCopyMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"<E extends RealmModel> E",
"createDetachedCopy",
EnumSet.of(Modifier.PUBLIC),
"E", "realmObject", "int", "maxDepth", "Map<RealmModel, RealmObjectProxy.CacheData<RealmModel>>", "cache"
)
emitSingleLineComment("This cast is correct because obj is either")
emitSingleLineComment("generated by RealmProxy or the original type extending directly from RealmObject")
emitStatement("@SuppressWarnings(\"unchecked\") Class<E> clazz = (Class<E>) realmObject.getClass().getSuperclass()")
emitEmptyLine()
emitMediatorShortCircuitSwitch(writer, false, { i: Int ->
emitStatement("return clazz.cast(%s.createDetachedCopy((%s) realmObject, 0, maxDepth, cache))",
qualifiedProxyClasses[i], qualifiedModelClasses[i])
})
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitIsEmbeddedMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"<E extends RealmModel> boolean",
"isEmbedded",
EnumSet.of(Modifier.PUBLIC),
"Class<E>", "clazz"
)
emitMediatorShortCircuitSwitch(writer, false, { i: Int ->
emitStatement("return %s", if (embeddedClass[i]) "true" else "false")
})
endMethod()
emitEmptyLine()
}
}
@Throws(IOException::class)
private fun emitUpdateEmbeddedObjectMethod(writer: JavaWriter) {
writer.apply {
emitAnnotation("Override")
beginMethod(
"<E extends RealmModel> void",
"updateEmbeddedObject",
EnumSet.of(Modifier.PUBLIC),
"Realm", "realm",
"E", "unmanagedObject",
"E", "managedObject",
"Map<RealmModel, RealmObjectProxy>", "cache",
"Set<ImportFlag>", "flags"
)
emitSingleLineComment("This cast is correct because obj is either")
emitSingleLineComment("generated by RealmProxy or the original type extending directly from RealmObject")
emitStatement("@SuppressWarnings(\"unchecked\") Class<E> clazz = (Class<E>) managedObject.getClass().getSuperclass()")
emitEmptyLine()
emitMediatorSwitch(writer, false) { i: Int ->
if (embeddedClass[i]) {
emitStatement("%1\$s.updateEmbeddedObject(realm, (%2\$s) unmanagedObject, (%2\$s) managedObject, cache, flags)", qualifiedProxyClasses[i], qualifiedModelClasses[i])
} else {
emitStatement("throw getNotEmbeddedClassException(\"%s\")", qualifiedModelClasses[i])
}
}
endMethod()
emitEmptyLine()
}
}
// Emits the control flow for selecting the appropriate proxy class based on the model class
// Currently it is just if..else, which is inefficient for large amounts amounts of model classes.
// Consider switching to HashMap or similar.
@Throws(IOException::class)
private fun emitMediatorSwitch(writer: JavaWriter, nullPointerCheck: Boolean, emitStatement: (index: Int) -> Unit) {
writer.apply {
if (nullPointerCheck) {
emitStatement("checkClass(clazz)")
emitEmptyLine()
}
if (qualifiedModelClasses.isEmpty()) {
emitStatement("throw getMissingProxyClassException(clazz)")
} else {
beginControlFlow("if (clazz.equals(%s.class))", qualifiedModelClasses[0])
emitStatement(0)
for (i in 1 until qualifiedModelClasses.size) {
nextControlFlow("else if (clazz.equals(%s.class))", qualifiedModelClasses[i])
emitStatement(i)
}
nextControlFlow("else")
emitStatement("throw getMissingProxyClassException(clazz)")
endControlFlow()
}
}
}
@Throws(IOException::class)
private fun emitMediatorShortCircuitSwitch(writer: JavaWriter, nullPointerCheck: Boolean = true, emitStatement: (index: Int) -> Unit) {
writer.apply {
if (nullPointerCheck) {
emitStatement("checkClass(clazz)")
emitEmptyLine()
}
for (i in qualifiedModelClasses.indices) {
beginControlFlow("if (clazz.equals(%s.class))", qualifiedModelClasses[i])
emitStatement(i)
endControlFlow()
}
emitStatement("throw getMissingProxyClassException(clazz)")
}
}
@Throws(IOException::class)
private fun emitMediatorInverseShortCircuitSwitch(writer: JavaWriter, nullPointerCheck: Boolean = true, emitStatement: (index: Int) -> Unit) {
writer.apply {
if (nullPointerCheck) {
emitStatement("checkClassName(className)")
emitEmptyLine()
}
for (i in qualifiedModelClasses.indices) {
beginControlFlow("if (className.equals(\"%s\"))", internalClassNames[i])
emitStatement(i)
endControlFlow()
}
emitStatement("throw getMissingProxyClassException(className)")
}
}
}
| 400
| null |
1747
| 11,450
|
e564a45fbeabb4710ac5fcd231c107642dd4aa83
| 28,784
|
realm-java
|
Apache License 2.0
|
yjloginsdk/src/main/java/jp/co/yahoo/yconnect/yjloginsdk/core/OptionalParameters.kt
|
yahoojapan
| 240,211,657
| false
| null |
/*
* © 2024 LY Corporation. All Rights Reserved.
*
* 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 jp.co.yahoo.yconnect.yjloginsdk.core
/**
* 認可リクエスト時に指定する任意パラメーター。
*
* @property bail 同意画面で「同意しない」ボタンをクリックした際の遷移先
* @property display ログイン画面と同意画面で表示するページ種類
* @property maxAge 最大認証経過時間。指定された秒数よりも認証日時が経過していた場合は再認証を要求
* @property prompts ユーザーに強制させたいアクション
* @property additionalParameters その他未定義のパラメーター。定義されていないパラメーターを指定したい場合に使用
*/
class OptionalParameters(
private var bail: Boolean = false,
private var display: Display? = null,
private var maxAge: Int? = null,
private var prompts: Set<Prompt>? = null,
private var additionalParameters: Map<String, String>? = null
) {
companion object {
private const val PARAM_BAIL = "bail"
private const val PARAM_DISPLAY = "display"
private const val PARAM_MAX_AGE = "max_age"
private const val PARAM_PROMPT = "prompt"
}
internal fun generate(): Map<String, String> {
val parameters = mutableMapOf<String, String>()
if (bail) { parameters[PARAM_BAIL] = "1" }
display?.let { parameters[PARAM_DISPLAY] = it.value }
maxAge?.let { parameters[PARAM_MAX_AGE] = maxAge.toString() }
prompts?.let { prompts ->
parameters[PARAM_PROMPT] = prompts.joinToString(" ") { it.value }
}
additionalParameters?.forEach { parameters[it.key] = it.value }
return parameters
}
}
| 0
| null |
4
| 6
|
d47cbb06249213ce84ba76a2ab75265a43f313e0
| 1,967
|
yjlogin-android-sdk
|
Apache License 2.0
|
src/main/kotlin/org/incava/rando/RandIntCalculated.kt
|
jpace
| 483,382,354
| false
|
{"Kotlin": 207435, "Ruby": 674}
|
package org.incava.rando
class RandIntCalculated(size: Int, numSlots: Int) : RandCalculated(size, numSlots) {
private val intArray: List<Int> = slots.map { it.value }
fun nextInt(): Int {
val index = random.nextInt(100)
return intArray[index]
}
}
| 0
|
Kotlin
|
0
| 0
|
f7d56ea5b803c985df415863ce8dc3ee8fa6f84b
| 276
|
mmonkeys
|
MIT License
|
src/main/kotlin/org/incava/rando/RandIntCalculated.kt
|
jpace
| 483,382,354
| false
|
{"Kotlin": 207435, "Ruby": 674}
|
package org.incava.rando
class RandIntCalculated(size: Int, numSlots: Int) : RandCalculated(size, numSlots) {
private val intArray: List<Int> = slots.map { it.value }
fun nextInt(): Int {
val index = random.nextInt(100)
return intArray[index]
}
}
| 0
|
Kotlin
|
0
| 0
|
f7d56ea5b803c985df415863ce8dc3ee8fa6f84b
| 276
|
mmonkeys
|
MIT License
|
src/main/java/dev/blachut/svelte/lang/codeInsight/SvelteTypeScriptReferenceExpressionResolver.kt
|
tomblachut
| 184,821,501
| false
|
{"JavaScript": 1549586, "Kotlin": 449460, "Java": 82443, "Lex": 16407, "Svelte": 15267, "HTML": 2052, "TypeScript": 709}
|
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package dev.blachut.svelte.lang.codeInsight
import com.intellij.lang.javascript.ecmascript6.TypeScriptReferenceExpressionResolver
import com.intellij.lang.javascript.psi.impl.JSReferenceExpressionImpl
import com.intellij.lang.javascript.psi.resolve.ResolveResultSink
import com.intellij.lang.javascript.psi.resolve.SinkResolveProcessor
import com.intellij.psi.ResolveResult
import dev.blachut.svelte.lang.codeInsight.SvelteJSReferenceExpressionResolver.Companion.resolveImplicits
class SvelteTypeScriptReferenceExpressionResolver(
referenceExpression: JSReferenceExpressionImpl,
ignorePerformanceLimits: Boolean,
) : TypeScriptReferenceExpressionResolver(referenceExpression, ignorePerformanceLimits) {
override fun resolve(expression: JSReferenceExpressionImpl, incompleteCode: Boolean): Array<ResolveResult> {
val resolvedImplicits = resolveImplicits(expression)
if (resolvedImplicits.isNotEmpty()) return resolvedImplicits
// sometimes reactive declaration could've been already returned here, the proof was lost to time
val resolvedBasicOrStore = super.resolve(expression, incompleteCode)
if (resolvedBasicOrStore.isNotEmpty()) return resolvedBasicOrStore
val referencedName = myReferencedName
if (expression.qualifier != null || referencedName == null) return ResolveResult.EMPTY_ARRAY
val sink = ResolveResultSink(myRef, referencedName, false, incompleteCode)
val localProcessor = createLocalResolveProcessor(sink)
return SvelteReactiveDeclarationsUtil.resolveReactiveDeclarationsCommon(myRef, myQualifier, localProcessor)
}
private fun createLocalResolveProcessor(sink: ResolveResultSink): SinkResolveProcessor<ResolveResultSink> {
return SvelteReactiveDeclarationsUtil.SvelteTypeScriptResolveProcessor(sink, myContainingFile, myRef)
}
}
| 0
|
JavaScript
|
38
| 479
|
3dacc20896adf1f1db06c99d691b3dbadc70d267
| 1,947
|
svelte-intellij
|
MIT License
|
idea/testData/quickfix/autoImports/sameModuleImportPriority.before.Main.kt
|
JakeWharton
| 99,388,807
| true
| null |
// "Import" "true"
// ERROR: Unresolved reference: Delegates
// WITH_RUNTIME
package testing
fun foo() {
val d = <caret>Delegates()
}
| 0
|
Kotlin
|
30
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 138
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/Day02.kt
|
SimonMarquis
| 724,825,757
| false
|
{"Kotlin": 8653}
|
import Day02.Color.blue
import Day02.Color.green
import Day02.Color.red
class Day02(private val input: List<String>) {
@Suppress("EnumEntryName")
enum class Color { red, green, blue }
private val regex = """(\d+) (${Color.entries.joinToString("|")})""".toRegex()
fun part1(
target: Map<Color, Int> = mapOf(red to 12, green to 13, blue to 14),
): Int = input.withIndex().filter { (_, line) ->
line.split(";")
.map { it.cubes() }
.all { it.validate(target) }
}.sumOf { it.index + 1 }
fun part2() = input.withIndex().sumOf { (_, line) ->
val cubes = line.split(";").map { it.cubes() }
fun maxOf(color: Color) = cubes.maxOf { it.getValue(color) }
maxOf(red) * maxOf(green) * maxOf(blue)
}
private fun String.cubes(): Map<Color, Int> = regex.findAll(this)
.map { it.destructured.let { (amount, color) -> Color.valueOf(color) to amount.toInt() } }
.foldInPlace(mutableMapOf<Color, Int>().withDefault { 0 }) { (color, amount) -> merge(color, amount, Int::plus) }
private fun Map<Color, Int>.validate(target: Map<Color, Int>) = target.all { (key, value) -> getValue(key) <= value }
}
| 0
|
Kotlin
|
0
| 1
|
2a692412ee89c0b5eb0e8f0841f4f3a6dbc128fe
| 1,204
|
advent-of-code-2023
|
MIT License
|
app/src/main/java/com/entersekt/fido2/MainActivity.kt
|
RameshPokharel
| 204,686,651
| false
|
{"Gradle": 3, "Java Properties": 2, "Shell": 2, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "XML": 10, "Kotlin": 2, "Java": 1, "JSON": 2}
|
package com.entersekt.fido2
import android.content.Intent
import android.content.IntentSender
import android.os.Bundle
import android.preference.PreferenceManager
import android.util.Base64
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.edit
import com.google.android.gms.fido.Fido
import com.google.android.gms.fido.fido2.api.common.*
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.*
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.net.CookieManager
import java.net.CookiePolicy
import java.security.SecureRandom
import java.util.concurrent.TimeUnit
import java.net.CookiePolicy.ACCEPT_ALL
class MainActivity : AppCompatActivity() {
companion object {
private const val LOG_TAG = "Fido2Demo"
private const val REQUEST_CODE_REGISTER = 1
private const val REQUEST_CODE_SIGN = 2
private const val KEY_HANDLE_PREF = "key_handle"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
registerFido2Button.setOnClickListener { getChallenge() }
signFido2Button.setOnClickListener { signFido2() }
signFido2Button.isEnabled = loadKeyHandle() != null
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Log.d(LOG_TAG, "onActivityResult - requestCode: $requestCode, resultCode: $resultCode")
when (resultCode) {
RESULT_OK -> {
data?.let {
if (it.hasExtra(Fido.FIDO2_KEY_ERROR_EXTRA)) {
handleErrorResponse(data.getByteArrayExtra(Fido.FIDO2_KEY_ERROR_EXTRA))
} else if (it.hasExtra(Fido.FIDO2_KEY_RESPONSE_EXTRA)) {
val fido2Response = data.getByteArrayExtra(Fido.FIDO2_KEY_RESPONSE_EXTRA)
when (requestCode) {
REQUEST_CODE_REGISTER -> handleRegisterResponse(fido2Response)
REQUEST_CODE_SIGN -> handleSignResponse(fido2Response)
}
}
}
}
RESULT_CANCELED -> {
val result = "Operation is cancelled"
resultText.text = result
Log.d(LOG_TAG, result)
}
else -> {
val result = "Operation failed, with resultCode: $resultCode"
resultText.text = result
Log.e(LOG_TAG, result)
}
}
}
private fun getChallenge() {
val result = JSONObject()
val mediaType = MediaType.parse("application/json")
result.put("username", "test1")
val requestBody = RequestBody.create(mediaType, result.toString())
RestApi.getApi().getResultNew("username=ramesh",requestBody).enqueue(object : Callback<ResponseBody> {
override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
if (response.isSuccessful) {
var obj = JSONObject(response.body()?.string())
var challenge = obj?.getString("challenge")
var rpname = obj?.getJSONObject("rp").getString("name")
var username = obj?.getJSONObject("user").getString("name")
var userId = obj?.getJSONObject("user").getString("id")
registerFido2("call your rpid ", rpname, challenge, userId, "", username)
//{"challenge":"51DoDsakwoW6K3vFmpxFI7Kc1NPK2elN3Xcuimde-nQ",
// "rp":{"name":"Safe Bank"},
// "user":{"id":"HO4XTjFw1GOpV9eFnN2tmzQ1D5p4qXvX","name":"test1","displayName":null},
// "attestation":"direct","status":"ok","excludeCredentials":[],"errorMessage":"","pubKeyCredParams":[{"type":"public-key","alg":-7},{"type":"public-key","alg":-8},{"type":"public-key","alg":-35},{"type":"public-key","alg":-36},{"type":"public-key","alg":-37},{"type":"public-key","alg":-38},{"type":"public-key","alg":-39},{"type":"public-key","alg":-257},{"type":"public-key","alg":-258},{"type":"public-key","alg":-259}]}
// call registerFido with challenge and user information
Log.d("response", response.message())
} else {
Log.d("response", response.errorBody().toString())
}
}
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
Log.d("response", t.message)
}
})
}
private fun registerFido2(
rpId: String,
rpname: String,
challenge: String,
userId: String,
userEmail: String?,
userName: String?
) {
// All the option parameters should come from the Relying Party / server
val options = PublicKeyCredentialCreationOptions.Builder()
.setRp(PublicKeyCredentialRpEntity(rpId, rpname, null))
.setUser(
PublicKeyCredentialUserEntity(
userId.toByteArray(),
userEmail,
null,
userName
)
)
.setChallenge(challenge.toByteArray())
.setParameters(
listOf(
PublicKeyCredentialParameters(
PublicKeyCredentialType.PUBLIC_KEY.toString(),
EC2Algorithm.ES256.algoValue
)
)
)
.build()
val fido2ApiClient = Fido.getFido2ApiClient(applicationContext)
val fido2PendingIntentTask = fido2ApiClient.getRegisterIntent(options)
fido2PendingIntentTask.addOnSuccessListener { fido2PendingIntent ->
if (fido2PendingIntent.hasPendingIntent()) {
try {
Log.d(LOG_TAG, "launching Fido2 Pending Intent")
fido2PendingIntent.launchPendingIntent(this@MainActivity, REQUEST_CODE_REGISTER)
} catch (e: IntentSender.SendIntentException) {
e.printStackTrace()
}
}
}
}
private fun signFido2() {
// All the option parameters should come from the Relying Party / server
val options = PublicKeyCredentialRequestOptions.Builder()
.setRpId("strategics-fido2.firebaseapp.com")
.setAllowList(
listOf(
PublicKeyCredentialDescriptor(
PublicKeyCredentialType.PUBLIC_KEY.toString(),
loadKeyHandle(),
null
)
)
)
.setChallenge(challenge())
.build()
val fido2ApiClient = Fido.getFido2ApiClient(applicationContext)
val fido2PendingIntentTask = fido2ApiClient.getSignIntent(options)
fido2PendingIntentTask.addOnSuccessListener { fido2PendingIntent ->
if (fido2PendingIntent.hasPendingIntent()) {
try {
Log.d(LOG_TAG, "launching Fido2 Pending Intent")
fido2PendingIntent.launchPendingIntent(this@MainActivity, REQUEST_CODE_SIGN)
} catch (e: IntentSender.SendIntentException) {
e.printStackTrace()
}
}
}
}
private fun handleErrorResponse(errorBytes: ByteArray) {
val authenticatorErrorResponse = AuthenticatorErrorResponse.deserializeFromBytes(errorBytes)
val errorName = authenticatorErrorResponse.errorCode.name
val errorMessage = authenticatorErrorResponse.errorMessage
Log.e(LOG_TAG, "errorCode.name: $errorName")
Log.e(LOG_TAG, "errorMessage: $errorMessage")
val registerFidoResult = "An Error Ocurred\n\nError Name:\n$errorName\n\nError Message:\n$errorMessage"
resultText.text = registerFidoResult
}
/**
* The response should be sent to the Relying Party / server to validate and store
*/
private fun handleRegisterResponse(fido2Response: ByteArray) {
val response = AuthenticatorAttestationResponse.deserializeFromBytes(fido2Response)
val keyHandleBase64 = Base64.encodeToString(response.keyHandle, Base64.DEFAULT)
val clientDataJson = String(response.clientDataJSON, Charsets.UTF_8)
val attestationObjectBase64 = Base64.encodeToString(response.attestationObject, Base64.DEFAULT)
storeKeyHandle(response.keyHandle)
signFido2Button.isEnabled = true
Log.d(LOG_TAG, "keyHandleBase64: $keyHandleBase64")
Log.d(LOG_TAG, "clientDataJSON: $clientDataJson")
Log.d(LOG_TAG, "attestationObjectBase64: $attestationObjectBase64")
val registerFido2Result = "Authenticator Attestation Response\n\n" +
"keyHandleBase64:\n" +
"$keyHandleBase64\n\n" +
"clientDataJSON:\n" +
"$clientDataJson\n\n" +
"attestationObjectBase64:\n" +
"$attestationObjectBase64\n"
resultText.text = registerFido2Result
}
//{"type":"webauthn.create",
// "challenge":"Z2hwaG9CaGdCcVktS2lvbVRGMzBEQlFiUXJ0cml5RkJYZHliZmNvdUdEdw",
// "origin":"android:apk-key-hash:<KEY>",
// "androidPackageName":"com.entersekt.fido2"}
/**
* The response should be sent to the Relying Party / server to validate
*/
private fun handleSignResponse(fido2Response: ByteArray) {
val response = AuthenticatorAssertionResponse.deserializeFromBytes(fido2Response)
val keyHandleBase64 = Base64.encodeToString(response.keyHandle, Base64.DEFAULT)
val clientDataJson = String(response.clientDataJSON, Charsets.UTF_8)
val authenticatorDataBase64 = Base64.encodeToString(response.authenticatorData, Base64.DEFAULT)
val signatureBase64 = Base64.encodeToString(response.signature, Base64.DEFAULT)
Log.d(LOG_TAG, "keyHandleBase64: $keyHandleBase64")
Log.d(LOG_TAG, "clientDataJSON: $clientDataJson")
Log.d(LOG_TAG, "authenticatorDataBase64: $authenticatorDataBase64")
Log.d(LOG_TAG, "signatureBase64: $signatureBase64")
val signFido2Result = "Authenticator Assertion Response\n\n" +
"keyHandleBase64:\n" +
"$keyHandleBase64\n\n" +
"clientDataJSON:\n" +
"$clientDataJson\n\n" +
"authenticatorDataBase64:\n" +
"$authenticatorDataBase64\n\n" +
"signatureBase64:\n" +
"$signatureBase64\n"
resultText.text = signFido2Result
}
/**
* https://www.w3.org/TR/webauthn/#cryptographic-challenges
*/
private fun challenge(): ByteArray {
val secureRandom = SecureRandom()
val challenge = ByteArray(16)
secureRandom.nextBytes(challenge)
return challenge
}
private fun storeKeyHandle(keyHandle: ByteArray) {
PreferenceManager.getDefaultSharedPreferences(this).edit {
putString(KEY_HANDLE_PREF, Base64.encodeToString(keyHandle, Base64.DEFAULT))
}
}
private fun loadKeyHandle(): ByteArray? {
val keyHandleBase64 = PreferenceManager.getDefaultSharedPreferences(this).getString(KEY_HANDLE_PREF, null)
?: return null
return Base64.decode(keyHandleBase64, Base64.DEFAULT)
}
}
| 0
|
Kotlin
|
0
| 0
|
5fbb20a31c280a501b79f3b03683f3a10cbfa768
| 11,714
|
FidoDemo
|
Apache License 2.0
|
src/main/kotlin/platform/velocity/framework/VelocityPresentationProvider.kt
|
minecraft-dev
| 42,327,118
| false
| null |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.velocity.framework
import com.demonwav.mcdev.asset.PlatformAssets
import com.demonwav.mcdev.util.localFile
import com.intellij.framework.library.LibraryVersionProperties
import com.intellij.openapi.roots.libraries.LibraryPresentationProvider
import com.intellij.openapi.util.io.JarUtil
import com.intellij.openapi.vfs.VirtualFile
import java.io.BufferedReader
import java.util.jar.JarFile
class VelocityPresentationProvider : LibraryPresentationProvider<LibraryVersionProperties>(VELOCITY_LIBRARY_KIND) {
override fun getIcon(properties: LibraryVersionProperties?) = PlatformAssets.VELOCITY_ICON
override fun detect(classesRoots: MutableList<VirtualFile>): LibraryVersionProperties? {
for (classesRoot in classesRoots) {
runCatching {
if (JarUtil.containsClass(classesRoot.localFile, "com.velocitypowered.api.proxy.ProxyServer")) {
return LibraryVersionProperties()
}
// Velocity API jar has no Manifest entries, so we search for their annotation processor instead
val registeredAPs = JarFile(classesRoot.localFile).use { jar ->
val aps = jar.getEntry("META-INF/services/javax.annotation.processing.Processor")
?: return@use null
jar.getInputStream(aps).bufferedReader().use(BufferedReader::readLines)
} ?: return@runCatching
if (registeredAPs.contains("com.velocitypowered.api.plugin.ap.PluginAnnotationProcessor")) {
return LibraryVersionProperties()
}
}
}
return null
}
}
| 204
| null |
152
| 1,154
|
36cc3d47f7f39c847c0ebdcbf84980bc7262dab7
| 1,818
|
MinecraftDev
|
MIT License
|
yiski3/src/main/kotlin/one/devos/yiski3/data/Yiski3ConfigData.kt
|
devOS-Sanity-Edition
| 436,825,258
| false
|
{"Kotlin": 116829}
|
package one.devos.yiski3.data
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import one.devos.yiski.common.AbstractYiskiConfig
@Serializable
data class Yiski3ConfigData(
val images: ImageConfig,
val videos: VideosConfig
) : AbstractYiskiConfig {
@Serializable
data class ImageConfig(
@SerialName("static")
val inlineStaticImagesTables: StaticImageTables,
@SerialName("gif")
val inlineGifImageTables: GifImageTables
)
@Serializable
data class VideosConfig(
val antihorny: String,
val antihornyfile: String,
val gasp: String,
val gaspfile: String,
val memoryleak: String,
val memoryleakfile: String,
val rtx: String,
val rtxfile: String,
val whatareyoudoing: String,
val whatareyoudoingfile: String
)
}
@Serializable
data class StaticImageTables(
val devtools: String,
val devtoolsfile: String,
val ims: String,
val imsfile: String,
val token: String,
val tokenfile: String
)
@Serializable
data class GifImageTables(
val headcrabsuccess: String,
val headcrabsuccessfile: String,
val headcrabfail: String,
val headcrabfailfile: String,
)
| 11
|
Kotlin
|
1
| 1
|
10947f0a43420bb28ff69897ef711528415eaf21
| 1,260
|
yiski
|
MIT License
|
features/news/src/commonMain/kotlin/com/mathroda/news/components/NewsCard.kt
|
MathRoda
| 507,060,394
| false
|
{"Kotlin": 446115, "Swift": 4323, "Ruby": 2379, "Java": 624}
|
package com.mathroda.news_screen.components
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Card
import androidx.compose.material.Icon
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.mathroda.common.theme.*
import com.mathroda.domain.model.NewsDetail
import com.mathroda.news_screen.R
@Composable
fun NewsCard(
news: NewsDetail,
onClick: () -> Unit
) {
Row(
modifier = Modifier
.fillMaxWidth()
.background(
shape = RoundedCornerShape(15.dp),
color = LighterGray
)
.clickable { onClick() },
verticalAlignment = Alignment.CenterVertically
) {
Card(
modifier = Modifier
.weight(0.4f)
.padding(6.dp)
.requiredHeight(120.dp),
shape = RoundedCornerShape(15.dp),
elevation = 0.dp,
backgroundColor = DarkGray
) {
AsyncImage(
model = news.imgURL,
contentDescription = news.description,
contentScale = ContentScale.Crop,
placeholder = painterResource(id = R.drawable.ic_news),
)
}
Column(
modifier = Modifier
.fillMaxHeight()
.weight(0.6f),
verticalArrangement = Arrangement.SpaceBetween
) {
LazyRow(
modifier = Modifier
.fillMaxWidth()
.padding(4.dp),
verticalAlignment = Alignment.CenterVertically
) {
items(news.relatedCoins) { coin ->
Text(
text = coin.toString(),
color = Gold,
style = Typography.body2,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
Spacer(modifier = Modifier.size(4.dp))
}
}
Column(
modifier = Modifier.padding(4.dp),
) {
Text(
text = news.title,
color = TextWhite,
style = Typography.h4,
maxLines = 3,
overflow = TextOverflow.Ellipsis
)
}
Row(
modifier = Modifier
.fillMaxWidth()
.padding(4.dp),
verticalAlignment = Alignment.CenterVertically
) {
Icon(
modifier = Modifier.size(18.dp),
painter = painterResource(id = R.drawable.ic_news),
contentDescription = null
)
Spacer(modifier = Modifier.size(4.dp))
Text(
text = news.source,
color = Twitter,
style = Typography.body2,
fontWeight = FontWeight.SemiBold
)
}
}
}
}
| 0
|
Kotlin
|
41
| 297
|
cf303ba50bad35a816253bee5b27beee5ea364b8
| 3,787
|
DashCoin
|
Apache License 2.0
|
app/src/main/java/com/srtp/assistant/logic/dao/CampusAddressDao.kt
|
FallingStars-5
| 359,435,558
| false
| null |
package com.srtp.assistant.logic.dao
import com.srtp.assistant.logic.model.CampusAddress
import org.litepal.LitePal
import org.litepal.extension.delete
import org.litepal.extension.deleteAll
import org.litepal.extension.find
object CampusAddressDao {
/**增加一条网址记录
* @param campusAddress :CampusAddress
*/
fun addCampusAddress(campusAddress: CampusAddress){
campusAddress.save()
}
/**通过id查找一条记录并返回
* @param id:Long
* @return CampusAddress对象
*/
fun findCampusAddressById(id:Long) = LitePal.find<CampusAddress>(id)
/**通过类别名查找所有的记录并返回
* @param sortName:String
* @return CampusAddress列表
*/
fun findCampusAddressBySortName(sortName: String) = LitePal.where("sortName = ?", sortName).find<CampusAddress>()
/**查找所有的分类名称并返回
* @return String类型列表
*/
fun findAllCampusAddressName():List<String>{
val list = LitePal.where("").find<CampusAddress>()
val sortNameSet = HashSet<String>()
for (i in list){
sortNameSet.add(i.sortName)
}
return ArrayList<String>(sortNameSet)
}
/**修改一条记录
* @param campusAddress:CampusAddress
*/
fun updateCampusAddressById(campusAddress: CampusAddress){
campusAddress.update(campusAddress.id)
}
/**通过id删除一条记录
* @param id:Long
*/
fun deleteCampusAddressById(id:Long){
LitePal.delete<CampusAddress>(id)
}
/**通过类别名删掉该类别所有的记录
* @param sortName:String
*/
fun deleteCampusAddressBySortName(sortName:String){
LitePal.deleteAll<CampusAddress>("sortName = ?", sortName)
}
}
| 0
|
Kotlin
|
1
| 1
|
ec1c0a9409b44b5d4a58d5e0cf4912b6bf74cdf4
| 1,627
|
UniversityStudentAssistant
|
Apache License 2.0
|
src/main/kotlin/no/iktdev/cloud/gateway/Application.kt
|
bskjon
| 495,877,886
| false
|
{"Kotlin": 16607, "Dockerfile": 295}
|
package no.iktdev.cloud.gateway
import no.iktdev.cloud.gateway.firebase.Initializer
import org.slf4j.LoggerFactory
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.ApplicationContext
import javax.annotation.PreDestroy
@SpringBootApplication
class Application
private var context: ApplicationContext? = null
fun getContext(): ApplicationContext? {
return context
}
fun main(args: Array<String>) {
context = runApplication<Application>(*args)
Initializer()
}
@PreDestroy
fun onDestroying() {
}
inline fun <reified T> log(message: String) {
LoggerFactory.getLogger(T::class.java.simpleName).info(message)
}
fun Log(message: String) {
val caller: String = Thread.currentThread().stackTrace[2].className ?: Thread.currentThread().stackTrace[2].methodName
LoggerFactory.getLogger(caller).info(message)
}
| 0
|
Kotlin
|
0
| 0
|
053f302181dd8255f81e23260d679fbbb24dcd14
| 916
|
CloudGateway
|
Apache License 2.0
|
js/js.parser/src/org/jetbrains/kotlin/js/parser/sourcemaps/JSON.kt
|
JakeWharton
| 99,388,807
| false
| null |
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.js.parser.sourcemaps
import java.io.*
sealed class JsonNode {
abstract fun write(writer: Writer)
override fun toString(): String = StringWriter().also { write(it) }.toString()
}
object JsonNull : JsonNode() {
override fun write(writer: Writer) {
writer.append("null")
}
}
class JsonBoolean private constructor(val value: Boolean) : JsonNode() {
private val stringValue = value.toString()
override fun write(writer: Writer) {
writer.append(stringValue)
}
companion object {
val TRUE = JsonBoolean(true)
val FALSE = JsonBoolean(false)
fun of(value: Boolean): JsonBoolean = if (value) TRUE else FALSE
}
}
data class JsonObject(val properties: MutableMap<String, JsonNode>) : JsonNode() {
constructor(vararg properties: Pair<String, JsonNode>) : this(properties.toMap().toMutableMap())
override fun write(writer: Writer) {
writer.append('{')
var first = true
for ((key, value) in properties) {
if (!first) {
writer.append(',')
}
first = false
JsonString(key).write(writer)
writer.append(':')
value.write(writer)
}
writer.append('}')
}
override fun toString(): String = super.toString()
}
data class JsonArray(val elements: MutableList<JsonNode>) : JsonNode() {
constructor(vararg elements: JsonNode) : this(elements.toMutableList())
override fun write(writer: Writer) {
writer.append('[')
var first = true
for (element in elements) {
if (!first) {
writer.append(',')
}
first = false
element.write(writer)
}
writer.append(']')
}
}
data class JsonString(val value: String) : JsonNode() {
override fun write(writer: Writer) {
writer.append('"')
for (c in value) {
when (c) {
'\\' -> writer.append("\\\\")
'"' -> writer.append("\\\"")
'\r' -> writer.append("\\r")
'\n' -> writer.append("\\n")
'\t' -> writer.append("\\t")
'\b' -> writer.append("\\b")
'\u000C' -> writer.append("\\f")
in ' '..126.toChar() -> writer.append(c)
else -> {
writer.append("\\u")
var shift = 16
repeat(4) {
shift -= 4
val digit = (c.toInt() ushr shift) and 0xF
writer.append(if (digit < 10) (digit + '0'.toInt()).toChar() else (digit - 10 + 'a'.toInt()).toChar())
}
}
}
}
writer.append('"')
}
override fun toString(): String = super.toString()
}
data class JsonNumber(val value: Double) : JsonNode() {
override fun write(writer: Writer) {
if (value.toLong().toDouble() == value) {
writer.append(value.toLong().toString())
} else {
writer.append(value.toString())
}
}
override fun toString(): String = super.toString()
}
class JsonSyntaxException(val offset: Int, val line: Int, val column: Int, val text: String) :
RuntimeException("JSON syntax error at ${line + 1}, ${column + 1}: $text")
fun parseJson(file: File): JsonNode = parseJson(file.readText(Charsets.UTF_8))
fun parseJson(text: String): JsonNode = JsonParser(text).parse()
private class JsonParser(val content: String) {
private var index = -1
private var charCode = content.getOrNull(++index)?.toInt() ?: -1
private var offset = 0
private var line = 0
private var col = 0
private var wasCR = false
fun parse(): JsonNode {
val result = parseNode()
skipSpaces()
if (charCode != -1) throw error("End of input expected")
return result
}
private fun skipSpaces() {
while (true) {
when (charCode) {
' '.toInt(), '\t'.toInt(), '\n'.toInt(), '\r'.toInt() -> advance()
else -> return
}
}
}
private fun parseNode(): JsonNode {
skipSpaces()
return when (charCode) {
'['.toInt() -> parseArray()
'{'.toInt() -> parseObject()
'"'.toInt() -> JsonString(parseString())
'n'.toInt() -> {
expectString("null")
JsonNull
}
'f'.toInt() -> {
expectString("false")
JsonBoolean.FALSE
}
't'.toInt() -> {
expectString("true")
JsonBoolean.TRUE
}
'-'.toInt() -> {
advance()
JsonNumber(-parseNumber())
}
else -> if (charCode in '0'.toInt()..'9'.toInt()) {
JsonNumber(parseNumber())
} else {
error("Unexpected char")
}
}
}
private fun parseArray(): JsonArray {
advance()
val result = JsonArray()
while (true) {
skipSpaces()
if (charCode == ']'.toInt()) {
advance()
break
} else {
if (result.elements.isNotEmpty()) {
expectCharAndAdvance(',')
}
result.elements += parseNode()
}
}
return result
}
private fun parseObject(): JsonObject {
advance()
val result = JsonObject()
while (true) {
skipSpaces()
if (charCode == '}'.toInt()) {
advance()
break
} else {
if (result.properties.isNotEmpty()) {
expectCharAndAdvance(',')
}
skipSpaces()
val key = parseString()
if (key in result.properties) {
error("Duplicate property name: $key")
}
skipSpaces()
expectCharAndAdvance(':')
result.properties[key] = parseNode()
}
}
return result
}
private fun parseString(): String {
expectCharAndAdvance('"')
val sb = StringBuilder()
var leftIndex = index
while (index < content.length) {
charCode = content[index].toInt()
if (charCode < ' '.toInt()) {
error("Invalid character in string literal")
}
when (charCode) {
'"'.toInt() -> {
sb.append(content, leftIndex, index)
advance()
return sb.toString()
}
'\\'.toInt() -> {
sb.append(content, leftIndex, index)
sb.append(parseEscapeSequence())
leftIndex = index
}
else -> ++index
}
}
error("Unexpected end of file")
}
private fun parseEscapeSequence(): Char {
advance()
return when (charCode) {
'"'.toInt() -> advanceAndThen { '"' }
'\\'.toInt() -> advanceAndThen { '\\' }
'/'.toInt() -> advanceAndThen { '/' }
'b'.toInt() -> advanceAndThen { '\b' }
'n'.toInt() -> advanceAndThen { '\n' }
'r'.toInt() -> advanceAndThen { '\r' }
'f'.toInt() -> advanceAndThen { '\u000C' }
't'.toInt() -> advanceAndThen { '\t' }
'u'.toInt() -> parseHexEscapeSequence()
else -> error("Invalid escape sequence")
}
}
private fun parseHexEscapeSequence(): Char {
advance()
var value = 0
repeat(4) {
value *= 16
value += when (charCode) {
in '0'.toInt()..'9'.toInt() -> charCode - '0'.toInt()
in 'a'.toInt()..'f'.toInt() -> charCode - 'a'.toInt() + 10
in 'A'.toInt()..'F'.toInt() -> charCode - 'A'.toInt() + 10
else -> error("Invalid escape sequence, hexadecimal char expected")
}
advance()
}
return value.toChar()
}
private fun parseNumber(): Double {
val sb = StringBuilder()
takeIntegerDigitsTo(sb)
if (sb.startsWith('0') && sb.length > 1) error("Number must not start with zero")
return when (charCode) {
'.'.toInt() -> {
sb.append('.')
advance()
takeIntegerDigitsTo(sb)
if (charCode == 'e'.toInt() || charCode == 'E'.toInt()) {
takeExponentTo(sb)
}
sb.toString().toDouble()
}
'e'.toInt(), 'E'.toInt() -> {
takeExponentTo(sb)
sb.toString().toDouble()
}
else -> return sb.toString().toDouble()
}
}
private fun takeIntegerDigitsTo(buffer: StringBuilder) {
var size = 0
while (charCode in '0'.toInt()..'9'.toInt()) {
buffer.append(charCode.toChar())
advance()
size++
}
if (size == 0) error("Invalid char, decimal digit expected")
}
private fun takeExponentTo(buffer: StringBuilder) {
buffer.append('e')
advance()
if (charCode == '-'.toInt() || charCode == '+'.toInt()) {
buffer.append(charCode.toChar())
advance()
}
takeIntegerDigitsTo(buffer)
}
private fun expectString(expected: String) {
for (c in expected) {
if (charCode != c.toInt()) error("Unexpected char, '$expected' expected here")
advance()
}
}
private fun expectCharAndAdvance(expected: Char) {
if (charCode != expected.toInt()) error("Unexpected char, '$expected' expected here")
advance()
}
private inline fun <T> advanceAndThen(f: () -> T): T {
advance()
return f()
}
private fun advance() {
if (charCode == -1) return
when (charCode) {
'\r'.toInt() -> {
line++
col = 0
wasCR = true
}
'\n'.toInt() -> {
if (!wasCR) {
line++
col = 0
wasCR = false
}
}
else -> {
col++
wasCR = false
}
}
charCode = content.getOrNull(++index)?.toInt() ?: -1
offset++
}
private fun error(text: String): Nothing = throw JsonSyntaxException(offset, line, col, text)
}
| 181
| null |
5748
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 11,422
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/example/myapplication/ui/page/manager/FourFragment.kt
|
yo-lolo
| 660,058,834
| false
| null |
package com.example.myapplication.ui.page.manager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.ctq.sphone.market.base.BaseFragment
import com.example.myapplication.databinding.FragmentFourBinding
class FourFragment : BaseFragment() {
private lateinit var binding : FragmentFourBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentFourBinding.inflate(layoutInflater)
return binding.root
}
}
| 0
|
Kotlin
|
0
| 0
|
e7eb3c1d7f016b9148a8be3a9168982d1d4b8720
| 718
|
yolo
|
Apache License 2.0
|
app/src/main/java/com/shashank/moviefindermvvm/ui/home/HomeActivity.kt
|
Shashank02051997
| 255,571,550
| false
| null |
package com.shashank.moviefindermvvm.ui.home
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.Menu
import android.view.View
import android.widget.SearchView
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.shashank.moviefindermvvm.R
import com.shashank.moviefindermvvm.databinding.ActivityHomeBinding
import com.shashank.moviefindermvvm.ui.adapter.CustomAdapterMovies
import com.shashank.moviefindermvvm.ui.moviedetail.MovieDetailScrollingActivity
import com.shashank.moviefindermvvm.util.*
import org.kodein.di.KodeinAware
import org.kodein.di.android.kodein
import org.kodein.di.generic.instance
class HomeActivity : AppCompatActivity(), KodeinAware {
companion object {
const val ANIMATION_DURATION = 1000.toLong()
}
override val kodein by kodein()
private lateinit var dataBind: ActivityHomeBinding
private lateinit var viewModel: HomeViewModel
private val factory: HomeViewModelFactory by instance()
private lateinit var customAdapterMovies: CustomAdapterMovies
private lateinit var searchView: SearchView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
dataBind = DataBindingUtil.setContentView(this, R.layout.activity_home)
setupViewModel()
setupUI()
initializeObserver()
handleNetworkChanges()
setupAPICall()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.search, menu)
searchView = menu.findItem(R.id.search).actionView as SearchView
searchView.apply {
queryHint = "Search"
isSubmitButtonEnabled = true
onActionViewExpanded()
}
search(searchView)
return true
}
private fun setupUI() {
customAdapterMovies = CustomAdapterMovies()
dataBind.recyclerViewMovies.apply {
layoutManager = LinearLayoutManager(context)
itemAnimator = DefaultItemAnimator()
adapter = customAdapterMovies
addOnItemTouchListener(
RecyclerItemClickListener(
applicationContext,
object : RecyclerItemClickListener.OnItemClickListener {
override fun onItemClick(view: View, position: Int) {
if (customAdapterMovies.getData().isNotEmpty()) {
val searchItem = customAdapterMovies.getData()[position]
searchItem?.let {
val intent =
Intent(
applicationContext,
MovieDetailScrollingActivity::class.java
)
intent.putExtra(AppConstant.INTENT_POSTER, it.poster)
intent.putExtra(AppConstant.INTENT_TITLE, it.title)
startActivity(intent)
}
}
}
})
)
addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val layoutManager = recyclerView.layoutManager as LinearLayoutManager?
val visibleItemCount = layoutManager!!.childCount
val totalItemCount = layoutManager.itemCount
val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()
viewModel.checkForLoadMoreItems(
visibleItemCount,
totalItemCount,
firstVisibleItemPosition
)
}
})
}
}
private fun setupViewModel() {
viewModel = ViewModelProvider(this, factory).get(HomeViewModel::class.java)
}
private fun initializeObserver() {
viewModel.movieNameLiveData.observe(this, Observer {
Log.i("Info", "Movie Name = $it")
})
viewModel.loadMoreListLiveData.observe(this, Observer {
if (it) {
customAdapterMovies.setData(null)
Handler().postDelayed({
viewModel.loadMore()
}, 2000)
}
})
}
private fun setupAPICall() {
viewModel.moviesLiveData.observe(this, Observer { state ->
when (state) {
is State.Loading -> {
dataBind.recyclerViewMovies.hide()
dataBind.linearLayoutSearch.hide()
dataBind.progressBar.show()
}
is State.Success -> {
dataBind.recyclerViewMovies.show()
dataBind.linearLayoutSearch.hide()
dataBind.progressBar.hide()
customAdapterMovies.setData(state.data)
}
is State.Error -> {
dataBind.progressBar.hide()
showToast(state.message)
}
}
})
}
private fun handleNetworkChanges() {
NetworkUtils.getNetworkLiveData(applicationContext).observe(this, Observer { isConnected ->
if (!isConnected) {
dataBind.textViewNetworkStatus.text = getString(R.string.text_no_connectivity)
dataBind.networkStatusLayout.apply {
show()
setBackgroundColor(getColorRes(R.color.colorStatusNotConnected))
}
} else {
if (viewModel.moviesLiveData.value is State.Error || customAdapterMovies.itemCount == 0) {
viewModel.getMovies()
}
dataBind.textViewNetworkStatus.text = getString(R.string.text_connectivity)
dataBind.networkStatusLayout.apply {
setBackgroundColor(getColorRes(R.color.colorStatusConnected))
animate()
.alpha(1f)
.setStartDelay(ANIMATION_DURATION)
.setDuration(ANIMATION_DURATION)
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
hide()
}
})
}
}
})
}
private fun search(searchView: SearchView) {
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
dismissKeyboard(searchView)
searchView.clearFocus()
viewModel.searchMovie(query)
return true
}
override fun onQueryTextChange(newText: String): Boolean {
return false
}
})
}
}
| 1
| null |
24
| 76
|
8f24b851dc1befaffe2163aa4e08c02daf76feaf
| 7,632
|
MovieFinderUsingMVVM-Android
|
MIT License
|
src/main/kotlin/org/unbrokendome/gradle/plugins/helm/dsl/dependencies/ResolvedChartDependency.kt
|
Haardt
| 243,044,316
| true
|
{"Kotlin": 260778}
|
package org.unbrokendome.gradle.plugins.helm.dsl.dependencies
import java.io.File
internal data class ResolvedChartDependency(
/** Resolved version. */
val version: String,
/** Path to the resolved chart artifact. */
val file: File
)
| 0
| null |
0
| 0
|
f5e5ef51272526eaf2cf2f8f94a51d7a7da4bbd9
| 253
|
gradle-helm-plugin
|
MIT License
|
features/register/onboard/src/main/kotlin/team/applemango/runnerbe/feature/register/onboard/constant/EmailVerifyState.kt
|
ricky-buzzni
| 485,390,072
| false
|
{"Kotlin": 615137}
|
/*
* RunnerBe © 2022 Team AppleMango. all rights reserved.
* RunnerBe license is under the MIT.
*
* [EmailVerifyState.kt] created by <NAME> on 22. 2. 10. 오후 5:24
*
* Please see: https://github.com/applemango-runnerbe/RunnerBe-Android/blob/main/LICENSE.
*/
package team.applemango.runnerbe.feature.register.onboard.constant
internal sealed class EmailVerifyState {
object None : EmailVerifyState()
object Sent : EmailVerifyState()
object Loading : EmailVerifyState()
object Duplicate : EmailVerifyState()
object ErrorUuid : EmailVerifyState()
data class Exception(val throwable: Throwable) : EmailVerifyState()
}
| 0
| null |
0
| 0
|
f48fb298c07732a9c32afcff0bddb16f9fe2e37a
| 645
|
RunnerBe-Android
|
MIT License
|
app/src/main/java/echo/engineer/happymaven/MainActivity.kt
|
a42803488
| 203,913,919
| false
|
{"Markdown": 1, "Gradle": 8, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "Proguard": 4, "Java": 7, "XML": 18, "INI": 2, "Kotlin": 5, "Checksums": 18, "Public Key": 4, "Groovy": 4}
|
package echo.engineer.happymaven
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
/**
* MainActivity.kt
* Info: MainActivity.kt
* Created by Plucky(plucky@echo.engineer) on 2018/12/21 - 6:55 PM
* more about me: http://www.1991th.com
*/
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
| 1
| null |
1
| 1
|
e79ea039885cf418fcafd94b5c14925d0f53394c
| 470
|
HappyMaven
|
Apache License 2.0
|
src/main/kotlin/club/pisquad/minecraft/csgrenades/enums/GrenadeType.kt
|
ThePiSquad
| 839,453,704
| false
|
{"Kotlin": 83211}
|
package club.pisquad.minecraft.csgrenades.enums
enum class GrenadeType {
FLASH_BANG,
SMOKE_GRENADE,
HEGRENADE,
INCENDIARY
}
| 0
|
Kotlin
|
0
| 0
|
d50e9db22ab374d5550e06d8e0c7acc9855b42c8
| 140
|
CounterStrikeGrenades
|
MIT License
|
sampleapp/src/main/java/com/kirkbushman/sampleapp/models/TrophyModel.kt
|
ShaishavGandhi
| 282,130,827
| true
|
{"Kotlin": 389434}
|
package com.kirkbushman.sampleapp.models
import android.widget.TextView
import com.airbnb.epoxy.EpoxyAttribute
import com.airbnb.epoxy.EpoxyModelClass
import com.airbnb.epoxy.EpoxyModelWithHolder
import com.kirkbushman.sampleapp.R
@EpoxyModelClass(layout = R.layout.item_trophy)
abstract class TrophyModel : EpoxyModelWithHolder<TrophyHolder>() {
@EpoxyAttribute
lateinit var name: String
override fun bind(holder: TrophyHolder) {
holder.name.text = name
}
}
class TrophyHolder : KotlinHolder() {
val name by bind<TextView>(R.id.name)
}
| 0
| null |
0
| 0
|
056eb8e6084148af6bed984f8be25e44b00e8255
| 572
|
ARAW
|
MIT License
|
compiler/tests-spec/testData/codegen/box/linked/expressions/try-expression/p-5/pos/1.1.kt
|
JetBrains
| 3,432,266
| false
| null |
// WITH_RUNTIME
/*
* KOTLIN CODEGEN BOX SPEC TEST (POSITIVE)
*
* SPEC VERSION: 0.1-218
* PLACE: expressions, try-expression -> paragraph 5 -> sentence 1
* RELEVANT PLACES: expressions, try-expression -> paragraph 4 -> sentence 1
* NUMBER: 1
* DESCRIPTION: If no exception is thrown during the evaluation of the try body, no catch blocks are executed, the finally block is evaluated after the try body, and the program execution continues as normal.
*/
fun box(): String {
var isTryExecuted = false
var isCatched = false
var isFinallyExecuted = false
try {
isTryExecuted = true
} catch (e: Exception) {
isCatched = true
} finally {
isFinallyExecuted = true
}
return if (isTryExecuted && !isCatched && isFinallyExecuted) "OK"
else "NOK"
}
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 807
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/anytypeio/anytype/other/Deeplinks.kt
|
anyproto
| 647,371,233
| false
| null |
package com.anytypeio.anytype.other
import android.net.Uri
import com.anytypeio.anytype.core_models.Id
import com.anytypeio.anytype.core_models.Url
import com.anytypeio.anytype.core_models.primitives.SpaceId
import com.anytypeio.anytype.domain.misc.DeepLinkResolver
import com.anytypeio.anytype.domain.multiplayer.SpaceInviteResolver
const val DEEP_LINK_PATTERN = "anytype://"
/**
* Regex pattern for matching
*/
const val DEEP_LINK_INVITE_REG_EXP = "invite.any.coop/([a-zA-Z0-9]+)#([a-zA-Z0-9]+)"
const val DEE_LINK_INVITE_CUSTOM_REG_EXP = "anytype://invite/\\?cid=([a-zA-Z0-9]+)&key=([a-zA-Z0-9]+)"
const val MAIN_PATH = "main"
const val OBJECT_PATH = "object"
const val IMPORT_PATH = "import"
const val INVITE_PATH = "invite"
const val TYPE_PARAM = "type"
const val OBJECT_ID_PARAM = "objectId"
const val SPACE_ID_PARAM = "spaceId"
const val SOURCE_PARAM = "source"
const val TYPE_VALUE_EXPERIENCE = "experience"
const val IMPORT_EXPERIENCE_DEEPLINK = "$DEEP_LINK_PATTERN$MAIN_PATH/$IMPORT_PATH/?$TYPE_PARAM=$TYPE_VALUE_EXPERIENCE"
object DefaultDeepLinkResolver : DeepLinkResolver {
private val defaultInviteRegex = Regex(DEEP_LINK_INVITE_REG_EXP)
override fun resolve(
deeplink: String
): DeepLinkResolver.Action = when {
deeplink.contains(IMPORT_EXPERIENCE_DEEPLINK) -> {
try {
val type = Uri.parse(deeplink).getQueryParameter(TYPE_PARAM)
val source = Uri.parse(deeplink).getQueryParameter(SOURCE_PARAM)
DeepLinkResolver.Action.Import.Experience(
type = type.orEmpty(),
source = source.orEmpty()
)
} catch (e: Exception) {
DeepLinkResolver.Action.Unknown
}
}
deeplink.contains(INVITE_PATH) -> {
DeepLinkResolver.Action.Invite(deeplink)
}
defaultInviteRegex.containsMatchIn(deeplink) -> {
DeepLinkResolver.Action.Invite(deeplink)
}
deeplink.contains(OBJECT_PATH) -> {
val uri = Uri.parse(deeplink)
val obj = uri.getQueryParameter(OBJECT_ID_PARAM)
val space = uri.getQueryParameter(SPACE_ID_PARAM)
if (!obj.isNullOrEmpty() && !space.isNullOrEmpty()) {
DeepLinkResolver.Action.DeepLinkToObject(
obj = obj,
space = SpaceId(space)
)
} else {
DeepLinkResolver.Action.Unknown
}
}
else -> DeepLinkResolver.Action.Unknown
}
override fun createObjectDeepLink(obj: Id, space: SpaceId): Url {
return "${DEEP_LINK_PATTERN}${OBJECT_PATH}?${OBJECT_ID_PARAM}=$obj&${SPACE_ID_PARAM}=${space.id}"
}
override fun isDeepLink(link: String): Boolean {
return link.contains(defaultInviteRegex) || link.contains(DEEP_LINK_PATTERN)
}
}
object DefaultSpaceInviteResolver : SpaceInviteResolver {
private val customRegex = Regex(DEE_LINK_INVITE_CUSTOM_REG_EXP)
private val defaultRegex = Regex(DEEP_LINK_INVITE_REG_EXP)
override fun parseContentId(link: String): Id? {
return if (link.matches(customRegex)) {
val uri = Uri.parse(link)
uri.getQueryParameter(CONTENT_ID_KEY)
} else {
val result = defaultRegex.find(link)
result?.groupValues?.getOrNull(CONTENT_INDEX)
}
}
override fun parseFileKey(link: String): Id? {
return if (link.matches(customRegex)) {
val uri = Uri.parse(link)
uri.getQueryParameter(FILE_KEY_KEY)
} else {
val result = defaultRegex.find(link)
result?.groupValues?.getOrNull(KEY_INDEX)
}
}
private const val CONTENT_INDEX = 1
private const val KEY_INDEX = 2
private const val CONTENT_ID_KEY = "cid"
private const val FILE_KEY_KEY = "key"
}
| 45
| null |
43
| 528
|
c708958dcb96201ab7bb064c838ffa8272d5f326
| 3,908
|
anytype-kotlin
|
RSA Message-Digest License
|
MyApplication/app/src/main/java/com/example/myapplication/viewmodelfactory/KisiDetaySayfaviewmodelfactory.kt
|
HERIS00
| 752,560,884
| false
|
{"Kotlin": 27771}
|
package com.example.myapplication.viewmodelfactory
import android.app.Application
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.myapplication.viewmmodel.KisininDetaySayfasiViewModel
class KisiDetaySayfaviewmodelfactory(var application: Application): ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return KisininDetaySayfasiViewModel(application) as T
}
}
| 0
|
Kotlin
|
0
| 0
|
1f693a92e6105267dd0272022094c2054c018d5f
| 483
|
Kisiler_Uygulamas-_Apk
|
MIT License
|
actions-kotlin/src/jsMain/kotlin/actions/tool/cache/IToolRelease.kt
|
karakum-team
| 393,199,102
| false
|
{"Kotlin": 6914539}
|
// Automatically generated - do not modify!
package actions.tool.cache
import js.array.ReadonlyArray
import js.objects.JsPlainObject
@JsPlainObject
sealed external interface IToolRelease {
var version: String
var stable: Boolean
var release_url: String
var files: ReadonlyArray<IToolReleaseFile>
}
| 0
|
Kotlin
|
7
| 31
|
c3de7c4098277a67bd40a9f0687579a6b9956cb2
| 317
|
types-kotlin
|
Apache License 2.0
|
plugin/src/main/kotlin/io/github/dejankos/RockyBuildCachePlugin.kt
|
dejankos
| 538,162,622
| false
| null |
package io.github.dejankos
import org.gradle.api.Plugin
import org.gradle.api.initialization.Settings
class RockyBuildCachePlugin : Plugin<Settings> {
override fun apply(settings: Settings) {
settings.buildCache {
registerBuildCacheService(RockyBuildCacheProperties::class.java, RockyBuildCacheServiceFactory::class.java)
remote(RockyBuildCacheProperties::class.java) {
isPush = true
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
26e65a21bee1da2f1f73837dbf660db4c079ec51
| 470
|
gradle-rocky-build-cache
|
MIT License
|
src/main/java/net/ccbluex/liquidbounce/utils/MovementUtils.kt
|
Rmejia39
| 733,988,804
| false
|
{"Kotlin": 2304965, "Java": 1271227, "GLSL": 13515, "JavaScript": 8926}
|
/*
* FDPClient Hacked Client
* A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge by LiquidBounce.
* https://github.com/SkidderMC/FDPClient/
*/
package net.ccbluex.liquidbounce.utils
import net.ccbluex.liquidbounce.event.MoveEvent
import net.minecraft.client.Minecraft
import net.minecraft.entity.EntityLivingBase
import net.minecraft.network.play.client.C03PacketPlayer.C04PacketPlayerPosition
import net.minecraft.potion.Potion
import net.minecraft.util.AxisAlignedBB
import kotlin.math.asin
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt
object MovementUtils : MinecraftInstance() {
fun resetMotion(y: Boolean) {
mc.thePlayer.motionX = 0.0
mc.thePlayer.motionZ = 0.0
if(y) mc.thePlayer.motionY = 0.0
}
fun getSpeed(): Float {
return sqrt(mc.thePlayer.motionX * mc.thePlayer.motionX + mc.thePlayer.motionZ * mc.thePlayer.motionZ).toFloat()
}
/**
* Calculate speed based on the speed potion effect level/amplifier
*/
fun getSpeedWithPotionEffects(speed: Double) =
mc.thePlayer.getActivePotionEffect(Potion.moveSpeed)?.let {
speed * (1 + (it.amplifier + 1) * 0.2)
} ?: speed
fun strafe() {
strafe(getSpeed())
}
fun move() {
move(getSpeed())
}
fun isMoving(): Boolean {
return mc.thePlayer != null && (mc.thePlayer.movementInput.moveForward != 0f || mc.thePlayer.movementInput.moveStrafe != 0f)
}
fun hasMotion(): Boolean {
return mc.thePlayer.motionX != 0.0 && mc.thePlayer.motionZ != 0.0 && mc.thePlayer.motionY != 0.0
}
fun strafe(speed: Float) {
if (!isMoving()) return
mc.thePlayer.motionX = -sin(direction) * speed
mc.thePlayer.motionZ = cos(direction) * speed
}
fun defaultSpeed(): Double {
var baseSpeed = 0.2873
if (Minecraft.getMinecraft().thePlayer.isPotionActive(Potion.moveSpeed)) {
val amplifier = Minecraft.getMinecraft().thePlayer.getActivePotionEffect(Potion.moveSpeed)
.amplifier
baseSpeed *= 1.0 + 0.2 * (amplifier + 1)
}
return baseSpeed
}
fun doTargetStrafe(curTarget: EntityLivingBase, direction_: Float, radius: Float, moveEvent: MoveEvent, mathRadius: Int = 0) {
if(!isMoving()) return
var forward_ = 0.0
var strafe_ = 0.0
val speed_ = sqrt(moveEvent.x * moveEvent.x + moveEvent.z * moveEvent.z)
if(speed_ <= 0.0001)
return
var _direction = 0.0
if(direction_ > 0.001) {
_direction = 1.0
}else if(direction_ < -0.001) {
_direction = -1.0
}
var curDistance = (0.01).toFloat()
if (mathRadius == 1) {
curDistance = mc.thePlayer.getDistanceToEntity(curTarget)
}else if (mathRadius == 0) {
curDistance = sqrt((mc.thePlayer.posX - curTarget.posX) * (mc.thePlayer.posX - curTarget.posX) + (mc.thePlayer.posZ - curTarget.posZ) * (mc.thePlayer.posZ - curTarget.posZ)).toFloat()
}
if(curDistance < radius - speed_) {
forward_ = -1.0
}else if(curDistance > radius + speed_) {
forward_ = 1.0
}else {
forward_ = (curDistance - radius) / speed_
}
if(curDistance < radius + speed_*2 && curDistance > radius - speed_*2) {
strafe_ = 1.0
}
strafe_ *= _direction
var strafeYaw = RotationUtils.getRotationsEntity(curTarget).yaw.toDouble()
val covert_ = sqrt(forward_ * forward_ + strafe_ * strafe_)
forward_ /= covert_
strafe_ /= covert_
var turnAngle = Math.toDegrees(asin(strafe_))
if(turnAngle > 0) {
if(forward_ < 0)
turnAngle = 180F - turnAngle
}else {
if(forward_ < 0)
turnAngle = -180F - turnAngle
}
strafeYaw = Math.toRadians((strafeYaw + turnAngle))
moveEvent.x = -sin(strafeYaw) * speed_
moveEvent.z = cos(strafeYaw) * speed_
mc.thePlayer.motionX = moveEvent.x
mc.thePlayer.motionZ = moveEvent.z
}
fun move(speed: Float) {
if (!isMoving()) return
val yaw = direction
mc.thePlayer.motionX += -sin(yaw) * speed
mc.thePlayer.motionZ += cos(yaw) * speed
}
fun limitSpeed(speed: Float) {
val yaw = direction
val maxXSpeed = -sin(yaw) * speed
val maxZSpeed = cos(yaw) * speed
if (mc.thePlayer.motionX > maxZSpeed) {
mc.thePlayer.motionX = maxXSpeed
}
if (mc.thePlayer.motionZ > maxZSpeed) {
mc.thePlayer.motionZ = maxZSpeed
}
}
/**
* make player move slowly like when using item
* @author liulihaocai
*/
fun limitSpeedByPercent(percent: Float) {
mc.thePlayer.motionX *= percent
mc.thePlayer.motionZ *= percent
}
fun forward(length: Double) {
val yaw = Math.toRadians(mc.thePlayer.rotationYaw.toDouble())
mc.thePlayer.setPosition(
mc.thePlayer.posX + -sin(yaw) * length,
mc.thePlayer.posY,
mc.thePlayer.posZ + cos(yaw) * length
)
}
val direction: Double
get() {
var rotationYaw = mc.thePlayer.rotationYaw
if (mc.thePlayer.movementInput.moveForward < 0f) rotationYaw += 180f
var forward = 1f
if (mc.thePlayer.movementInput.moveForward < 0f) forward = -0.5f else if (mc.thePlayer.movementInput.moveForward > 0f) forward = 0.5f
if (mc.thePlayer.movementInput.moveStrafe > 0f) rotationYaw -= 90f * forward
if (mc.thePlayer.movementInput.moveStrafe < 0f) rotationYaw += 90f * forward
return Math.toRadians(rotationYaw.toDouble())
}
val jumpMotion: Float
get() {
var mot = 0.42f
if (mc.thePlayer.isPotionActive(Potion.jump)) {
mot += (mc.thePlayer.getActivePotionEffect(Potion.jump).amplifier + 1).toFloat() * 0.1f
}
return mot
}
val movingYaw: Float
get() = (direction * 180f / Math.PI).toFloat()
var bps = 0.0
private set
private var lastX = 0.0
private var lastY = 0.0
private var lastZ = 0.0
fun setMotion(speed: Double) {
var forward = mc.thePlayer.movementInput.moveForward.toDouble()
var strafe = mc.thePlayer.movementInput.moveStrafe.toDouble()
var yaw = mc.thePlayer.rotationYaw
if (forward == 0.0 && strafe == 0.0) {
mc.thePlayer.motionX = 0.0
mc.thePlayer.motionZ = 0.0
} else {
if (forward != 0.0) {
if (strafe > 0.0) {
yaw += (if (forward > 0.0) -45 else 45).toFloat()
} else if (strafe < 0.0) {
yaw += (if (forward > 0.0) 45 else -45).toFloat()
}
strafe = 0.0
if (forward > 0.0) {
forward = 1.0
} else if (forward < 0.0) {
forward = -1.0
}
}
val cos = cos(Math.toRadians((yaw + 90.0f).toDouble()))
val sin = sin(Math.toRadians((yaw + 90.0f).toDouble()))
mc.thePlayer.motionX = (forward * speed * cos +
strafe * speed * sin)
mc.thePlayer.motionZ = (forward * speed * sin -
strafe * speed * cos)
}
}
fun updateBlocksPerSecond() {
if (mc.thePlayer == null || mc.thePlayer.ticksExisted < 1) {
bps = 0.0
}
val distance = mc.thePlayer.getDistance(lastX, lastY, lastZ)
lastX = mc.thePlayer.posX
lastY = mc.thePlayer.posY
lastZ = mc.thePlayer.posZ
bps = distance * (20 * mc.timer.timerSpeed)
}
fun setSpeed(
moveEvent: MoveEvent,
moveSpeed: Double,
pseudoYaw: Float,
pseudoStrafe: Double,
pseudoForward: Double
) {
var forward = pseudoForward
var strafe = pseudoStrafe
var yaw = pseudoYaw
if (forward == 0.0 && strafe == 0.0) {
moveEvent.z = 0.0
moveEvent.x = 0.0
} else {
if (forward != 0.0) {
if (strafe > 0.0) {
yaw += (if (forward > 0.0) -45 else 45).toFloat()
} else if (strafe < 0.0) {
yaw += (if (forward > 0.0) 45 else -45).toFloat()
}
strafe = 0.0
if (forward > 0.0) {
forward = 1.0
} else if (forward < 0.0) {
forward = -1.0
}
}
val cos = cos(Math.toRadians((yaw + 90.0f).toDouble()))
val sin = sin(Math.toRadians((yaw + 90.0f).toDouble()))
moveEvent.x = forward * moveSpeed * cos + strafe * moveSpeed * sin
moveEvent.z = forward * moveSpeed * sin - strafe * moveSpeed * cos
}
}
private fun calculateGround(): Double {
val playerBoundingBox = mc.thePlayer.entityBoundingBox
var blockHeight = 1.0
var ground = mc.thePlayer.posY
while (ground > 0.0) {
val customBox = AxisAlignedBB(
playerBoundingBox.maxX,
ground + blockHeight,
playerBoundingBox.maxZ,
playerBoundingBox.minX,
ground,
playerBoundingBox.minZ
)
if (mc.theWorld.checkBlockCollision(customBox)) {
if (blockHeight <= 0.05) return ground + blockHeight
ground += blockHeight
blockHeight = 0.05
}
ground -= blockHeight
}
return 0.0
}
fun isOnGround(height: Double): Boolean {
return !mc.theWorld.getCollidingBoundingBoxes(mc.thePlayer, mc.thePlayer.entityBoundingBox.offset(0.0, -height, 0.0)).isEmpty()
}
fun getBaseMoveSpeed(): Double {
var baseSpeed = 0.2875
if (mc.thePlayer.isPotionActive(Potion.moveSpeed)) {
baseSpeed *= 1.0 + 0.2 * (mc.thePlayer.getActivePotionEffect(Potion.moveSpeed)
.getAmplifier() + 1)
}
return baseSpeed
}
fun handleVanillaKickBypass() {
val ground = calculateGround()
run {
var posY = mc.thePlayer.posY
while (posY > ground) {
mc.netHandler.addToSendQueue(C04PacketPlayerPosition(mc.thePlayer.posX, posY, mc.thePlayer.posZ, true))
if (posY - 8.0 < ground) break // Prevent next step
posY -= 8.0
}
}
mc.netHandler.addToSendQueue(C04PacketPlayerPosition(mc.thePlayer.posX, ground, mc.thePlayer.posZ, true))
var posY = ground
while (posY < mc.thePlayer.posY) {
mc.netHandler.addToSendQueue(C04PacketPlayerPosition(mc.thePlayer.posX, posY, mc.thePlayer.posZ, true))
if (posY + 8.0 > mc.thePlayer.posY) break // Prevent next step
posY += 8.0
}
mc.netHandler.addToSendQueue(
C04PacketPlayerPosition(
mc.thePlayer.posX,
mc.thePlayer.posY,
mc.thePlayer.posZ,
true
)
)
}
fun isBlockUnder(): Boolean {
if (mc.thePlayer == null) return false
if (mc.thePlayer.posY < 0.0) {
return false
}
var off = 0
while (off < mc.thePlayer.posY.toInt() + 2) {
val bb = mc.thePlayer.entityBoundingBox.offset(0.0, (-off).toDouble(), 0.0)
if (!mc.theWorld.getCollidingBoundingBoxes(mc.thePlayer, bb).isEmpty()) {
return true
}
off += 2
}
return false
}
}
| 3
|
Kotlin
|
0
| 0
|
b48c4e83c888568111a6665037db7fd3f7813ed3
| 11,921
|
FDPClient
|
MIT License
|
clients/src/commonMain/kotlin/app/softwork/composetodo/viewmodels/Failure.kt
|
hfhbd
| 286,300,714
| false
|
{"Kotlin": 68059, "Swift": 12186, "HTML": 385, "JavaScript": 319}
|
package app.softwork.composetodo.viewmodels
enum class Failure(val reason: String) {
WrongCredentials("Wrong credentials"),
NoNetwork("Server not available")
}
| 9
|
Kotlin
|
11
| 99
|
16e1d95cad1edabab9a1afdb16fe3f8bac81fd9d
| 169
|
ComposeTodo
|
Apache License 2.0
|
idea/idea-completion/testData/basic/common/visibility/VisibilityPrivateToThisWithReceiver2.kt
|
JakeWharton
| 99,388,807
| false
| null |
class A<in I> {
private val bar: I
private fun foo(): I = null!!
fun test(a: A<Int>) {
a.<caret>
}
}
// INVOCATION_COUNT: 1
// ABSENT: bar, foo
| 284
| null |
5162
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 172
|
kotlin
|
Apache License 2.0
|
compiler/testData/codegen/box/controlStructures/kt769.kt
|
JakeWharton
| 99,388,807
| false
| null |
// IGNORE_BACKEND: JS_IR
// IGNORE_BACKEND: JS_IR_ES6
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
package w_range
fun box() : String {
var i = 0
when (i) {
1 -> i--
else -> { i = 2 }
}
System.out?.println(i)
return "OK"
}
| 155
| null |
5553
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 319
|
kotlin
|
Apache License 2.0
|
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/ses/CfnTemplate.kt
|
cloudshiftinc
| 667,063,030
| false
|
{"Kotlin": 149148378}
|
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.ses
import io.cloudshiftdev.awscdk.CfnResource
import io.cloudshiftdev.awscdk.IInspectable
import io.cloudshiftdev.awscdk.IResolvable
import io.cloudshiftdev.awscdk.TreeInspector
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.common.CdkObject
import io.cloudshiftdev.awscdk.common.CdkObjectWrappers
import kotlin.Any
import kotlin.String
import kotlin.Unit
import kotlin.jvm.JvmName
import io.cloudshiftdev.constructs.Construct as CloudshiftdevConstructsConstruct
import software.constructs.Construct as SoftwareConstructsConstruct
/**
* Specifies an email template.
*
* Email templates enable you to send personalized email to one or more destinations in a single API
* operation.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.ses.*;
* CfnTemplate cfnTemplate = CfnTemplate.Builder.create(this, "MyCfnTemplate")
* .template(TemplateProperty.builder()
* .subjectPart("subjectPart")
* // the properties below are optional
* .htmlPart("htmlPart")
* .templateName("templateName")
* .textPart("textPart")
* .build())
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ses-template.html)
*/
public open class CfnTemplate(
cdkObject: software.amazon.awscdk.services.ses.CfnTemplate,
) : CfnResource(cdkObject),
IInspectable {
public constructor(scope: CloudshiftdevConstructsConstruct, id: String) :
this(software.amazon.awscdk.services.ses.CfnTemplate(scope.let(CloudshiftdevConstructsConstruct.Companion::unwrap),
id)
)
public constructor(
scope: CloudshiftdevConstructsConstruct,
id: String,
props: CfnTemplateProps,
) :
this(software.amazon.awscdk.services.ses.CfnTemplate(scope.let(CloudshiftdevConstructsConstruct.Companion::unwrap),
id, props.let(CfnTemplateProps.Companion::unwrap))
)
public constructor(
scope: CloudshiftdevConstructsConstruct,
id: String,
props: CfnTemplateProps.Builder.() -> Unit,
) : this(scope, id, CfnTemplateProps(props)
)
/**
*
*/
public open fun attrId(): String = unwrap(this).getAttrId()
/**
* Examines the CloudFormation resource and discloses attributes.
*
* @param inspector tree inspector to collect and process attributes.
*/
public override fun inspect(inspector: TreeInspector) {
unwrap(this).inspect(inspector.let(TreeInspector.Companion::unwrap))
}
/**
* The content of the email, composed of a subject line and either an HTML part or a text-only
* part.
*/
public open fun template(): Any? = unwrap(this).getTemplate()
/**
* The content of the email, composed of a subject line and either an HTML part or a text-only
* part.
*/
public open fun template(`value`: IResolvable) {
unwrap(this).setTemplate(`value`.let(IResolvable.Companion::unwrap))
}
/**
* The content of the email, composed of a subject line and either an HTML part or a text-only
* part.
*/
public open fun template(`value`: TemplateProperty) {
unwrap(this).setTemplate(`value`.let(TemplateProperty.Companion::unwrap))
}
/**
* The content of the email, composed of a subject line and either an HTML part or a text-only
* part.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("57f6de4491d980050e3f3d30941f0e0f693cabcc717af8906ad79a609cd784fe")
public open fun template(`value`: TemplateProperty.Builder.() -> Unit): Unit =
template(TemplateProperty(`value`))
/**
* A fluent builder for [io.cloudshiftdev.awscdk.services.ses.CfnTemplate].
*/
@CdkDslMarker
public interface Builder {
/**
* The content of the email, composed of a subject line and either an HTML part or a text-only
* part.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ses-template.html#cfn-ses-template-template)
* @param template The content of the email, composed of a subject line and either an HTML part
* or a text-only part.
*/
public fun template(template: IResolvable)
/**
* The content of the email, composed of a subject line and either an HTML part or a text-only
* part.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ses-template.html#cfn-ses-template-template)
* @param template The content of the email, composed of a subject line and either an HTML part
* or a text-only part.
*/
public fun template(template: TemplateProperty)
/**
* The content of the email, composed of a subject line and either an HTML part or a text-only
* part.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ses-template.html#cfn-ses-template-template)
* @param template The content of the email, composed of a subject line and either an HTML part
* or a text-only part.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("cddd8ef62379e20dc50fd9f980b0aed4918a48b7c1a2aa51a0ff288116c8f0ff")
public fun template(template: TemplateProperty.Builder.() -> Unit)
}
private class BuilderImpl(
scope: SoftwareConstructsConstruct,
id: String,
) : Builder {
private val cdkBuilder: software.amazon.awscdk.services.ses.CfnTemplate.Builder =
software.amazon.awscdk.services.ses.CfnTemplate.Builder.create(scope, id)
/**
* The content of the email, composed of a subject line and either an HTML part or a text-only
* part.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ses-template.html#cfn-ses-template-template)
* @param template The content of the email, composed of a subject line and either an HTML part
* or a text-only part.
*/
override fun template(template: IResolvable) {
cdkBuilder.template(template.let(IResolvable.Companion::unwrap))
}
/**
* The content of the email, composed of a subject line and either an HTML part or a text-only
* part.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ses-template.html#cfn-ses-template-template)
* @param template The content of the email, composed of a subject line and either an HTML part
* or a text-only part.
*/
override fun template(template: TemplateProperty) {
cdkBuilder.template(template.let(TemplateProperty.Companion::unwrap))
}
/**
* The content of the email, composed of a subject line and either an HTML part or a text-only
* part.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ses-template.html#cfn-ses-template-template)
* @param template The content of the email, composed of a subject line and either an HTML part
* or a text-only part.
*/
@kotlin.Suppress("INAPPLICABLE_JVM_NAME")
@JvmName("cddd8ef62379e20dc50fd9f980b0aed4918a48b7c1a2aa51a0ff288116c8f0ff")
override fun template(template: TemplateProperty.Builder.() -> Unit): Unit =
template(TemplateProperty(template))
public fun build(): software.amazon.awscdk.services.ses.CfnTemplate = cdkBuilder.build()
}
public companion object {
public val CFN_RESOURCE_TYPE_NAME: String =
software.amazon.awscdk.services.ses.CfnTemplate.CFN_RESOURCE_TYPE_NAME
public operator fun invoke(
scope: CloudshiftdevConstructsConstruct,
id: String,
block: Builder.() -> Unit = {},
): CfnTemplate {
val builderImpl = BuilderImpl(CloudshiftdevConstructsConstruct.unwrap(scope), id)
return CfnTemplate(builderImpl.apply(block).build())
}
internal fun wrap(cdkObject: software.amazon.awscdk.services.ses.CfnTemplate): CfnTemplate =
CfnTemplate(cdkObject)
internal fun unwrap(wrapped: CfnTemplate): software.amazon.awscdk.services.ses.CfnTemplate =
wrapped.cdkObject as software.amazon.awscdk.services.ses.CfnTemplate
}
/**
* An object that defines the email template to use for an email message, and the values to use
* for any message variables in that template.
*
* An *email template* is a type of message template that contains content that you want to
* define, save, and reuse in email messages that you send.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.ses.*;
* TemplateProperty templateProperty = TemplateProperty.builder()
* .subjectPart("subjectPart")
* // the properties below are optional
* .htmlPart("htmlPart")
* .templateName("templateName")
* .textPart("textPart")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ses-template-template.html)
*/
public interface TemplateProperty {
/**
* The HTML body of the email.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ses-template-template.html#cfn-ses-template-template-htmlpart)
*/
public fun htmlPart(): String? = unwrap(this).getHtmlPart()
/**
* The subject line of the email.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ses-template-template.html#cfn-ses-template-template-subjectpart)
*/
public fun subjectPart(): String
/**
* The name of the template.
*
* You will refer to this name when you send email using the `SendTemplatedEmail` or
* `SendBulkTemplatedEmail` operations.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ses-template-template.html#cfn-ses-template-template-templatename)
*/
public fun templateName(): String? = unwrap(this).getTemplateName()
/**
* The email body that is visible to recipients whose email clients do not display HTML content.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ses-template-template.html#cfn-ses-template-template-textpart)
*/
public fun textPart(): String? = unwrap(this).getTextPart()
/**
* A builder for [TemplateProperty]
*/
@CdkDslMarker
public interface Builder {
/**
* @param htmlPart The HTML body of the email.
*/
public fun htmlPart(htmlPart: String)
/**
* @param subjectPart The subject line of the email.
*/
public fun subjectPart(subjectPart: String)
/**
* @param templateName The name of the template.
* You will refer to this name when you send email using the `SendTemplatedEmail` or
* `SendBulkTemplatedEmail` operations.
*/
public fun templateName(templateName: String)
/**
* @param textPart The email body that is visible to recipients whose email clients do not
* display HTML content.
*/
public fun textPart(textPart: String)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.ses.CfnTemplate.TemplateProperty.Builder =
software.amazon.awscdk.services.ses.CfnTemplate.TemplateProperty.builder()
/**
* @param htmlPart The HTML body of the email.
*/
override fun htmlPart(htmlPart: String) {
cdkBuilder.htmlPart(htmlPart)
}
/**
* @param subjectPart The subject line of the email.
*/
override fun subjectPart(subjectPart: String) {
cdkBuilder.subjectPart(subjectPart)
}
/**
* @param templateName The name of the template.
* You will refer to this name when you send email using the `SendTemplatedEmail` or
* `SendBulkTemplatedEmail` operations.
*/
override fun templateName(templateName: String) {
cdkBuilder.templateName(templateName)
}
/**
* @param textPart The email body that is visible to recipients whose email clients do not
* display HTML content.
*/
override fun textPart(textPart: String) {
cdkBuilder.textPart(textPart)
}
public fun build(): software.amazon.awscdk.services.ses.CfnTemplate.TemplateProperty =
cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.ses.CfnTemplate.TemplateProperty,
) : CdkObject(cdkObject),
TemplateProperty {
/**
* The HTML body of the email.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ses-template-template.html#cfn-ses-template-template-htmlpart)
*/
override fun htmlPart(): String? = unwrap(this).getHtmlPart()
/**
* The subject line of the email.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ses-template-template.html#cfn-ses-template-template-subjectpart)
*/
override fun subjectPart(): String = unwrap(this).getSubjectPart()
/**
* The name of the template.
*
* You will refer to this name when you send email using the `SendTemplatedEmail` or
* `SendBulkTemplatedEmail` operations.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ses-template-template.html#cfn-ses-template-template-templatename)
*/
override fun templateName(): String? = unwrap(this).getTemplateName()
/**
* The email body that is visible to recipients whose email clients do not display HTML
* content.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ses-template-template.html#cfn-ses-template-template-textpart)
*/
override fun textPart(): String? = unwrap(this).getTextPart()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): TemplateProperty {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.ses.CfnTemplate.TemplateProperty):
TemplateProperty = CdkObjectWrappers.wrap(cdkObject) as? TemplateProperty ?:
Wrapper(cdkObject)
internal fun unwrap(wrapped: TemplateProperty):
software.amazon.awscdk.services.ses.CfnTemplate.TemplateProperty = (wrapped as
CdkObject).cdkObject as software.amazon.awscdk.services.ses.CfnTemplate.TemplateProperty
}
}
}
| 1
|
Kotlin
|
0
| 4
|
ddf2bfd2275b50bb86a667c4298dd92f59d7e342
| 15,109
|
kotlin-cdk-wrapper
|
Apache License 2.0
|
common/src/commonMain/kotlin/com/darkrockstudios/apps/hammer/common/DataVersion.kt
|
Wavesonics
| 499,367,913
| false
| null |
package com.darkrockstudios.apps.hammer.common
import com.darkrockstudios.apps.hammer.base.BuildMetadata
internal var DATA_VERSION = BuildMetadata.DATA_VERSION
fun setDataVersion(version: String) {
DATA_VERSION = version
}
fun getDataVersion() = DATA_VERSION
| 0
|
Kotlin
|
1
| 8
|
37fa39e536151ba2b15eb81feddfd8435bf8a1d7
| 263
|
hammer-editor
|
MIT License
|
cinescout/settings/data/local/src/commonMain/kotlin/cinescout/settings/data/local/SettingsDataLocalModule.kt
|
fardavide
| 280,630,732
| false
|
{"Kotlin": 2374797, "Shell": 11599}
|
package cinescout.anticipated.data.local
import org.koin.core.annotation.ComponentScan
import org.koin.core.annotation.Module
@Module
@ComponentScan
class AnticipatedDataLocalModule
| 8
|
Kotlin
|
2
| 6
|
f2e3993816452afaf6c3f1e7c7a384eb9a66c06e
| 184
|
CineScout
|
Apache License 2.0
|
boat-egg/src/main/kotlin/xyz/srclab/common/egg/nest/o/OUnits.kt
|
srclab-projects
| 247,777,997
| false
| null |
package xyz.srclab.common.egg.nest.o
import java.awt.Color
internal const val HUMAN_FORCE = 1
internal const val ENEMY_FORCE = 2
internal const val STEP_UNIT = 1.0
internal const val STEP_45_DEGREE_ANGLE = STEP_UNIT * 0.7071067812
internal interface OElement {
var id: Long
}
internal interface OObjectUnit : OElement {
var x: Double
var y: Double
var lastX: Double
var lastY: Double
var stepX: Double
var stepY: Double
var radius: Double
var moveSpeed: Int
var lastMoveTime: Long
var deathTime: Long
var deathDuration: Long
var keepBody: Boolean
var player: OPlayer
var drawResource: DrawResource
val isDead: Boolean
get() = deathTime > 0
fun isDisappeared(tickTime: Long): Boolean {
return isDead && tickTime - deathTime > deathDuration
}
fun isBody(tickTime: Long): Boolean {
return keepBody && isDisappeared(tickTime)
}
}
internal interface OSubjectUnit : OObjectUnit {
var type: OSubjectType
var hp: Int
var defense: Int
var weapons: List<OWeapon>
}
internal interface OAmmoUnit : OObjectUnit {
var weapon: OWeapon
var createTime: Long
var preparedTime: Long
}
internal open class OBaseUnit : OElement {
override var id: Long = idSequence++
companion object {
private var idSequence: Long = 100000L
}
}
internal data class OSubject(
override var x: Double,
override var y: Double,
override var lastX: Double,
override var lastY: Double,
override var stepX: Double,
override var stepY: Double,
override var radius: Double,
override var moveSpeed: Int,
override var lastMoveTime: Long,
override var deathTime: Long,
override var deathDuration: Long,
override var keepBody: Boolean,
override var player: OPlayer,
override var drawResource: DrawResource,
override var type: OSubjectType,
override var hp: Int,
override var defense: Int,
override var weapons: List<OWeapon>,
var score: Long,
) : OBaseUnit(), OSubjectUnit
internal data class OAmmo(
override var x: Double,
override var y: Double,
override var lastX: Double,
override var lastY: Double,
override var stepX: Double,
override var stepY: Double,
override var radius: Double,
override var moveSpeed: Int,
override var lastMoveTime: Long,
override var deathTime: Long,
override var deathDuration: Long,
override var keepBody: Boolean,
override var player: OPlayer,
override var drawResource: DrawResource,
var weapon: OWeapon,
var createTime: Long,
var preparedTime: Long,
) : OBaseUnit(), OObjectUnit
internal data class OWeapon(
var holder: OSubjectUnit,
var damage: Int,
var fireSpeed: Int,
var lastFireTime: Long,
var actor: WeaponActor,
var type: OWeaponType,
) : OBaseUnit()
internal data class OPlayer(
var number: Int = 0,
var hit: Long,
var score: Long,
var force: Int,
var color: Color,
)
| 0
|
Kotlin
|
1
| 4
|
a630d2897d5299af34ec17cfe335f3df3221851e
| 3,016
|
boat
|
Apache License 2.0
|
nav/editor/testSrc/com/android/tools/idea/naveditor/actions/ActivateSelectionActionTest.kt
|
JetBrains
| 60,701,247
| false
| null |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.naveditor.actions
import com.android.tools.idea.DesignSurfaceTestUtil
import com.android.tools.idea.actions.DESIGN_SURFACE
import com.android.tools.idea.naveditor.NavModelBuilderUtil.navigation
import com.android.tools.idea.naveditor.NavTestCase
import com.android.tools.idea.naveditor.surface.NavDesignSurface
import com.intellij.testFramework.TestActionEvent
import org.mockito.ArgumentMatchers.any
import org.mockito.Mockito.never
import org.mockito.Mockito.spy
import org.mockito.Mockito.verify
class ActivateSelectionActionTest : NavTestCase() {
fun testActivateSelectionAction() {
val model =
model("nav.xml") {
navigation("root") {
fragment("fragment")
navigation("nested")
}
}
val surface = NavDesignSurface(project, project)
DesignSurfaceTestUtil.setModelToSurfaceAndWait(surface, model)
val spy = spy(surface)
val action = ActivateSelectionAction()
val event = TestActionEvent.createTestEvent { if (DESIGN_SURFACE.`is`(it)) spy else null }
surface.selectionModel.setSelection(listOf())
action.actionPerformed(event)
verify(spy, never()).notifyComponentActivate(any())
val nested = model.treeReader.find("nested")!!
val fragment = model.treeReader.find("fragment")!!
surface.selectionModel.setSelection(listOf(nested, fragment))
action.actionPerformed(event)
verify(spy, never()).notifyComponentActivate(any())
surface.selectionModel.setSelection(listOf(nested))
action.actionPerformed(event)
verify(spy).notifyComponentActivate(nested)
}
}
| 5
| null |
227
| 948
|
10110983c7e784122d94c7467e9d243aba943bf4
| 2,229
|
android
|
Apache License 2.0
|
app/src/main/java/com/drewcodesit/afiexplorer/view/MainActivity.kt
|
DrewStephensCoding
| 509,035,000
| false
| null |
package com.drewcodesit.afiexplorer.view
import android.annotation.SuppressLint
import android.app.SearchManager
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.graphics.Typeface
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.RadioButton
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.appcompat.widget.SearchView
import androidx.core.content.res.ResourcesCompat
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.volley.Request
import com.android.volley.toolbox.JsonArrayRequest
import com.drewcodesit.afiexplorer.MyApplication
import com.drewcodesit.afiexplorer.MyApplication.Companion.TAG
import com.drewcodesit.afiexplorer.R
import com.drewcodesit.afiexplorer.R.*
import com.drewcodesit.afiexplorer.adapters.MainAdapter
import com.drewcodesit.afiexplorer.database.FavoriteDatabase
import com.drewcodesit.afiexplorer.databinding.MainActivityBinding
import com.drewcodesit.afiexplorer.model.Pubs
import com.drewcodesit.afiexplorer.utils.Config
import com.drewcodesit.afiexplorer.utils.MyDividerItemDecoration
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.rajat.pdfviewer.PdfViewerActivity
import es.dmoral.toasty.Toasty
import java.util.*
// PubsAdapterListener opens publications
class MainActivity : AppCompatActivity(), MainAdapter.PubsAdapterListener {
// Migration to View Binding from Kotlin Synthetics
// Source: https://medium.com/codex/android-viewbinding-migration-16070e24b752
private lateinit var _binding: MainActivityBinding
private var pubsList: ArrayList<Pubs>? = null
private var adapter: MainAdapter? = null
private var searchView: SearchView? = null
private var request: JsonArrayRequest? = null
private var exit: Boolean = false
// Shared Prefs
private lateinit var sharedPreferences: SharedPreferences
// BottomSheet for Filtering
private lateinit var bottomSheetDialog: BottomSheetDialog
// Radio Buttons for Filtering
private lateinit var cbALL: RadioButton
private lateinit var cbHAF: RadioButton
private lateinit var cbLeMayCenter: RadioButton
private lateinit var cbACC: RadioButton
private lateinit var cbAMC: RadioButton
private lateinit var cbPACAF: RadioButton
private lateinit var cbAFMC: RadioButton
private lateinit var cbAFSOC: RadioButton
private lateinit var cbUSAFE: RadioButton
private lateinit var cbAFRC: RadioButton
private lateinit var cbAFGSC: RadioButton
private lateinit var cbAETC: RadioButton
private lateinit var cbTravel: RadioButton
//The OnBackPressedDispatcher is a class that allows you
// to register a OnBackPressedCallback to a LifecycleOwner
private val onBackPressedCallback: OnBackPressedCallback = object : OnBackPressedCallback(true) {
@RequiresApi(Build.VERSION_CODES.N)
override fun handleOnBackPressed() {
closeOrRefreshApp()
}
}
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// View Binding
_binding = MainActivityBinding.inflate(layoutInflater)
setContentView(_binding.root)
toastyConfig()
setSupportActionBar(_binding.toolbar)
supportActionBar?.apply {
setDisplayHomeAsUpEnabled(false)
setDisplayShowHomeEnabled(true)
title = resources.getString(string.app_name)
}
// View Binding
//recyclerView = _binding.contentMain.recyclerView
_binding.contentMain.recyclerView.layoutManager = LinearLayoutManager(this)
_binding.contentMain.recyclerView.apply {
itemAnimator = DefaultItemAnimator()
addItemDecoration(
MyDividerItemDecoration(
this@MainActivity,
DividerItemDecoration.VERTICAL,
36
)
)
}
pubsList = ArrayList()
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
favoriteDatabase = FavoriteDatabase.getDatabase(applicationContext)
fetchPubs()
setUpBottomSheet()
onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
}
// SearchView
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
searchView = menu.findItem(id.action_search)?.actionView as SearchView
searchView?.apply {
setSearchableInfo(searchManager.getSearchableInfo(componentName))
setIconifiedByDefault(true)
maxWidth = Int.MAX_VALUE
setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
adapter?.filter?.filter(newText!!) {
when (adapter?.itemCount) {
0 -> {
// Kotlin View Binding
_binding.contentMain.noResultsFound.visibility = View.VISIBLE
_binding.contentMain.noResultsFound.text = getString(string.no_results_found, newText)
}
else -> {
_binding.contentMain.noResultsFound.visibility = View.GONE
}
}
}
Log.i("MAIN_ACTIVITY", newText!!)
return false
}
})
/*
* Hides other menu items when searchview is active
* Source: https://stackoverflow.com/questions/32840576/actionbar-hiding-all-menu-items-except-search-field
*/
setOnQueryTextFocusChangeListener { _, _ ->
menu.findItem(R.id.action_bookmark).isVisible = !hasFocus()
}
}
return true
}
@RequiresApi(Build.VERSION_CODES.N)
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
// Search function for looking up publications
id.action_search -> {
true
}
// App Feedback Links
id.action_feedback -> {
startActivity(
Intent(
this@MainActivity,
SettingsActivity::class.java
)
)
true
}
// Change App Theme (Light, Dark, System Follow)
id.action_change_theme -> {
val themeSelections = getThemeSelections()
AlertDialog.Builder(this)
.setTitle("Change Theme")
.setSingleChoiceItems(
themeSelections.first,
themeSelections.second
) { dialog, which ->
// Respond to item chosen
when (which) {
0 -> {
sharedPreferences.edit().putInt(
getString(string.pref_key_mode_night),
AppCompatDelegate.MODE_NIGHT_NO
).apply()
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}
1 -> {
sharedPreferences.edit().putInt(
getString(string.pref_key_mode_night),
AppCompatDelegate.MODE_NIGHT_YES
).apply()
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
}
2 -> {
sharedPreferences.edit().putInt(
getString(string.pref_key_mode_night),
AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
).apply()
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
}
}
dialog.dismiss()
}
.show()
true
}
// View Saved Publications
id.action_bookmark -> {
startActivity(
Intent(
this@MainActivity,
FavoritesActivity::class.java
)
)
true
}
else -> super.onOptionsItemSelected(item)
}
}
// App Theme Selection (Light, Dark, and System Follow)
private fun getThemeSelections(): Pair<Array<String>, Int> {
val modeNight = sharedPreferences.getInt(
getString(string.pref_key_mode_night),
AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
)
val themeSelection =
when (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) {
Configuration.UI_MODE_NIGHT_NO -> {
if (modeNight != AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) 0 else 2
}
Configuration.UI_MODE_NIGHT_YES -> {
if (modeNight != AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) 1 else 2
}
else -> 2
}
return Pair(arrayOf("Light", "Dark", "System"), themeSelection)
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
(application as MyApplication).applyTheme()
getOrientation()
recreate()
}
// ClickListener in MainAdapter.kt, allows user to open publication
// in installed PDF viewer or defaults to PDF-Viewer (bitmap converter so lower quality)
override fun onPubsSelected(pubs: Pubs) {
try{
// Checks if Document URL from E-Pubs is restricted and shows Toast Message indicating
// Official Source Doc can be found through E-Pubs Website
if (pubs.DocumentUrl?.contains("generic_restricted.pdf") == true
|| (pubs.DocumentUrl?.contains("restricted_access.pdf")) == true
|| (pubs.DocumentUrl?.contains("for_official_use_only.pdf")) == true
|| (pubs.DocumentUrl?.contains("generic_fouo.pdf")) == true
|| (pubs.DocumentUrl?.contains("stocked_and_issued")) == true
|| (pubs.DocumentUrl?.contains("generic_opr1.pdf")) == true
|| (pubs.DocumentUrl?.contains("generic_opr.pdf")) == true) {
Toasty.error(applicationContext, getString(string.pub_restricted), Toast.LENGTH_SHORT, false).show()
} else{
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(Uri.parse(pubs.DocumentUrl), "application/pdf")
startActivity(intent)
}
} catch (e:ActivityNotFoundException){
startActivity(
// Use 'launchPdfFromPath' if you want to use assets file (enable "fromAssets" flag) / internal directory
PdfViewerActivity.launchPdfFromUrl( //PdfViewerActivity.Companion.launchPdfFromUrl(.. :: incase of JAVA
applicationContext,
"${pubs.DocumentUrl}", // PDF URL in String format
"${pubs.Title}", // PDF Name/Title in String format
"", // If nothing specific, Put "" it will save to Downloads
enableDownload = true // This param is true by default.
)
)
}
}
/**
* Bug Fix for Version 1.3.2 / Version Code 18
* Auto rotate issue even when turned off.
* https://www.reddit.com/user/goldfishfollies
*/
private fun getOrientation(){
requestedOrientation =
if (Settings.System.getInt(contentResolver, Settings.System.ACCELEROMETER_ROTATION, 0) == 1){
//Auto Rotate is on, so don't lock
ActivityInfo.SCREEN_ORIENTATION_SENSOR
} else{
//Auto Rotate is off, so lock
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
}
// Fetches JSON from API
//pubJSON is companion object below/web api for pubs
@RequiresApi(Build.VERSION_CODES.M)
@SuppressLint("NotifyDataSetChanged")
private fun fetchPubs() {
_binding.contentMain.loading.visibility = View.VISIBLE
request = JsonArrayRequest(
Request.Method.GET,
Config.BASE_URL,
null,{ response ->
val items: List<Pubs> =
Gson().fromJson(response.toString(), object : TypeToken<List<Pubs>>() {}.type)
//val sortedItems = items.sortedWith(compareBy { it.Number })
val sortedItems = items.sortedByDescending {
it.getCertDate()
}
pubsList?.clear()
pubsList?.addAll(sortedItems)
// Hardcoded pubs moved to Publications Gitlab Repo
// https://gitlab.com/afi-explorer/pubs
_binding.contentMain.recyclerView.recycledViewPool.clear()
adapter?.notifyDataSetChanged()
_binding.contentMain.loading.visibility = View.GONE
setupData()
},
{error ->
println(error.printStackTrace())
Toasty.error(applicationContext, getString(string.no_internet), Toast.LENGTH_SHORT, true).show()
}
)
MyApplication.instance.addToRequestQueue(request!!)
}
private fun setupData(){
adapter = MainAdapter(applicationContext, pubsList!!, this)
_binding.contentMain.recyclerView.adapter = adapter
}
// Bottom Sheet Dialog for Filtering
@RequiresApi(Build.VERSION_CODES.N)
@SuppressLint("InflateParams")
private fun setUpBottomSheet(){
_binding.fabFilter.setOnClickListener{
val dialogView = layoutInflater.inflate(layout.bottom_sheet_filter, null)
// radio buttons in bottom_sheet_filter.xml
cbALL = dialogView.findViewById(id.cbALL)
cbHAF = dialogView.findViewById(id.cbHAF)
cbLeMayCenter = dialogView.findViewById(id.cbLeMayCenter)
cbACC = dialogView.findViewById(id.cbACC)
cbAMC = dialogView.findViewById(id.cbAMC)
cbAETC = dialogView.findViewById(id.cbAETC)
cbAFMC = dialogView.findViewById(id.cbAFMC)
cbAFSOC = dialogView.findViewById(id.cbAFSOC)
cbAFGSC = dialogView.findViewById(id.cbAFGSC)
cbUSAFE = dialogView.findViewById(id.cbUSAFE)
cbPACAF = dialogView.findViewById(id.cbPACAF)
cbAFRC= dialogView.findViewById(id.cbAFRC)
cbTravel = dialogView.findViewById(id.cbTravel)
bottomSheetDialog = BottomSheetDialog(this@MainActivity)
bottomSheetDialog.setContentView(dialogView)
bottomSheetDialog.show()
val filterMap = mapOf(
cbALL to Pair("", resources.getString(string.app_name)),
cbHAF to Pair("AF/", "HAF"),
cbLeMayCenter to Pair("LeMay Center", "Doctrine"),
cbACC to Pair("ACC", "ACC"),
cbAMC to Pair("AMC", "AMC"),
cbAETC to Pair("AETC", "AETC"),
cbAFMC to Pair("AFMC", "AFMC"),
cbAFSOC to Pair("AFSOC", "AFSOC"),
cbAFGSC to Pair("AFGSC", "AFGSC"),
cbUSAFE to Pair("USAFE-AFAFRICA", "USAFE-AFAFRICA"),
cbPACAF to Pair("PACAF", "PACAF"),
cbAFRC to Pair("AFRC", "AFRC"),
cbTravel to Pair("DoD", "DoD")
)
for ((checkbox, filter) in filterMap) {
checkbox.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
updateFilter(filter.first, filter.second)
bottomSheetDialog.dismiss()
}
}
}
}
}
private fun updateFilter(org: String, title: String) {
adapter?.filterByRescindOrg()?.filter(org)
supportActionBar?.title = title
bottomSheetDialog.dismiss()
}
private fun toastyConfig(){
val typeface: Typeface? = ResourcesCompat.getFont(applicationContext, font.ibm_plex_sans)
Toasty.Config.getInstance()
.setTextSize(15)
.setToastTypeface(typeface!!)
.supportDarkTheme(true)
.apply()
}
@RequiresApi(Build.VERSION_CODES.N)
private fun closeOrRefreshApp(){
supportActionBar?.title = getString(string.app_name)
fetchPubs()
if (exit){
finish() // finish activity
}else{
Toasty.normal(this, getString(string.action_exit_app)).show()
exit = true
Handler(Looper.getMainLooper()).postDelayed({ exit = false }, 3 * 1000)
}
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "onDestroy: --------")
}
companion object {
// Database to save frequent pubs
var favoriteDatabase: FavoriteDatabase? = null
}
}
| 0
|
Kotlin
|
0
| 1
|
0387b394b55a144d749041e5cef6792712ca37e0
| 18,739
|
AFIExplorer
|
MIT License
|
simplified-ui-settings/src/main/java/org/nypl/simplified/ui/settings/SettingsCustomOPDSFragment.kt
|
ThePalaceProject
| 367,082,997
| false
| null |
package org.nypl.simplified.ui.settings
import android.app.Activity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.ProgressBar
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import io.reactivex.disposables.CompositeDisposable
import org.nypl.simplified.accounts.api.AccountEvent
import org.nypl.simplified.android.ktx.supportActionBar
import org.slf4j.LoggerFactory
import java.net.URI
/**
* A fragment that allows to add a custom OPDS feed.
*/
class SettingsFragmentCustomOPDS : Fragment(R.layout.settings_custom_opds) {
private val logger = LoggerFactory.getLogger(SettingsFragmentCustomOPDS::class.java)
private val viewModel: SettingsCustomOPDSViewModel by viewModels()
private val subscriptions: CompositeDisposable = CompositeDisposable()
private lateinit var create: Button
private lateinit var feedURL: EditText
private lateinit var progress: ProgressBar
private lateinit var progressText: TextView
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
this.feedURL =
view.findViewById(R.id.settingsCustomOPDSURL)
this.create =
view.findViewById(R.id.settingsCustomOPDSCreate)
this.progress =
view.findViewById(R.id.settingsCustomOPDSProgressBar)
this.progressText =
view.findViewById(R.id.settingsCustomOPDSProgressText)
if (savedInstanceState == null) {
this.progressText.text = ""
}
this.viewModel.taskRunning.observe(viewLifecycleOwner, this::onTaskRunningChanged)
}
override fun onStart() {
super.onStart()
this.configureToolbar(this.requireActivity())
this.feedURL.addTextChangedListener(this.URITextWatcher())
this.viewModel.accountEvents
.subscribe(this::onAccountEvent)
.let { subscriptions.add(it) }
this.create.setOnClickListener {
this.viewModel.createCustomOPDSFeed(this.feedURL.text.toString())
}
}
override fun onStop() {
super.onStop()
subscriptions.clear()
}
private fun configureToolbar(activity: Activity) {
this.supportActionBar?.apply {
title = getString(R.string.settingsCustomOPDS)
subtitle = null
}
}
private fun onTaskRunningChanged(running: Boolean) {
if (running) {
this.create.isEnabled = false
this.progress.visibility = View.VISIBLE
this.progressText.text = ""
} else {
this.progress.visibility = View.INVISIBLE
this.create.isEnabled = this.isValidURI()
}
}
private fun onAccountEvent(event: AccountEvent) {
this.progressText.append(event.message)
this.progressText.append("\n")
for (name in event.attributes.keys) {
this.progressText.append(" ")
this.progressText.append(name)
this.progressText.append(": ")
this.progressText.append(event.attributes[name])
this.progressText.append("\n")
}
}
private fun isValidURI(): Boolean {
val text = this.feedURL.text
return if (text.isNotEmpty()) {
try {
URI(text.toString())
this.feedURL.setError(null, null)
true
} catch (e: Exception) {
this.logger.error("not a valid URI: ", e)
this.feedURL.error = this.resources.getString(R.string.settingsCustomOPDSInvalidURI)
false
}
} else {
false
}
}
inner class URITextWatcher : 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) {
this@SettingsFragmentCustomOPDS.create.isEnabled =
this@SettingsFragmentCustomOPDS.isValidURI()
}
}
}
| 109
| null |
4
| 8
|
91e03d505fc718dcc977930eb668761898ccdfc1
| 3,928
|
android-core
|
Apache License 2.0
|
Backpack/src/main/java/net/skyscanner/backpack/text/BpkTextField.kt
|
Skyscanner
| 117,813,847
| false
| null |
/**
* Backpack for Android - Skyscanner's Design System
*
* Copyright 2018-2021 Skyscanner Ltd
*
* 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 net.skyscanner.backpack.text
import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import androidx.appcompat.content.res.AppCompatResources
import androidx.appcompat.widget.AppCompatEditText
import net.skyscanner.backpack.R
import net.skyscanner.backpack.util.colorStateList
import net.skyscanner.backpack.util.createContextThemeWrapper
import net.skyscanner.backpack.util.use
open class BpkTextField @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0,
) : AppCompatEditText(
createContextThemeWrapper(
createContextThemeWrapper(context, attrs, androidx.appcompat.R.attr.editTextStyle),
attrs, R.attr.bpkTextFieldStyle
),
attrs,
defStyleAttr,
) {
private var iconTintColor: Int = 0
set(value) {
field = value
iconStart?.setTint(value)
iconEnd?.setTint(value)
}
var iconStart: Drawable? = null
set(value) {
unscheduleDrawable(field)
field = value
?.mutate()
?.also { it.setTint(iconTintColor) }
setCompoundDrawablesRelativeWithIntrinsicBounds(iconStart, null, iconEnd, null)
}
var iconEnd: Drawable? = null
set(value) {
unscheduleDrawable(field)
field = value
?.mutate()
?.also { it.setTint(iconTintColor) }
setCompoundDrawablesRelativeWithIntrinsicBounds(iconStart, null, iconEnd, null)
}
var hasError: Boolean = false
set(value) {
field = value
refreshDrawableState()
}
init {
initialize(attrs, defStyleAttr)
}
private fun initialize(attrs: AttributeSet?, defStyleAttr: Int) {
BpkText.getFont(context, BpkText.BASE, BpkText.Weight.NORMAL).applyTo(paint)
var textColor = context.getColor(R.color.bpkTextPrimary)
var textColorDisabled = context.getColor(R.color.__textFieldTextDisabled)
var hintNormalColor = context.getColor(R.color.__textFieldHint)
var hintFocusedColor = context.getColor(R.color.__textFieldHint)
var iconColor = context.getColor(R.color.__textFieldIcon)
var background: Drawable = AppCompatResources.getDrawable(context, R.drawable.bpk_text_field_background)!!
context.theme.obtainStyledAttributes(
attrs,
R.styleable.BpkTextField,
defStyleAttr,
0
).use {
textColor = it.getColor(R.styleable.BpkTextField_textFieldColor, textColor)
hintNormalColor = it.getColor(R.styleable.BpkTextField_textFieldColorHintNormal, hintNormalColor)
hintFocusedColor = it.getColor(R.styleable.BpkTextField_textFieldColorHintFocused, hintFocusedColor)
iconColor = it.getColor(R.styleable.BpkTextField_textFieldColorIcon, iconColor)
iconStart = it.getDrawable(R.styleable.BpkTextField_textFieldIconStart)
iconEnd = it.getDrawable(R.styleable.BpkTextField_textFieldIconEnd)
background = it.getDrawable(R.styleable.BpkTextField_textFieldBackground) ?: background
}
this.iconTintColor = iconColor
setTextColor(
colorStateList(
color = textColor,
disabledColor = textColorDisabled,
)
)
setHintTextColor(
colorStateList(
color = hintNormalColor,
pressedColor = hintNormalColor,
focusedColor = hintFocusedColor,
activatedColor = hintFocusedColor,
disabledColor = textColorDisabled,
)
)
val paddingHorizontal = resources.getDimensionPixelSize(R.dimen.bpkSpacingBase)
val paddingVertical = resources.getDimensionPixelSize(R.dimen.bpkSpacingMd) +
resources.getDimensionPixelSize(R.dimen.bpkSpacingSm)
setPaddingRelative(paddingHorizontal, paddingVertical, paddingHorizontal, paddingVertical)
compoundDrawablePadding = resources.getDimensionPixelSize(R.dimen.bpkSpacingMd) +
resources.getDimensionPixelSize(R.dimen.bpkSpacingSm)
gravity = Gravity.START or Gravity.CENTER_VERTICAL
this.background = background
this.minHeight = resources.getDimensionPixelSize(R.dimen.bpkSpacingXxl) +
resources.getDimensionPixelSize(R.dimen.bpkSpacingMd)
}
override fun onRtlPropertiesChanged(layoutDirection: Int) {
super.onRtlPropertiesChanged(layoutDirection)
textDirection = if (layoutDirection == View.LAYOUT_DIRECTION_RTL) View.TEXT_DIRECTION_RTL else View.TEXT_DIRECTION_LTR
}
override fun onCreateDrawableState(extraSpace: Int): IntArray {
val drawableState = super.onCreateDrawableState(extraSpace + 1)
if (hasError) {
mergeDrawableStates(drawableState, ERROR_STATE_SET)
}
return drawableState
}
}
private val ERROR_STATE_SET = intArrayOf(R.attr.state_error)
| 8
| null |
31
| 94
|
9b5448b446c7bc46560e430595829e5f4f090e6b
| 5,333
|
backpack-android
|
Apache License 2.0
|
shared/src/commonTest/kotlin/ui/MjImagesViewModelTest.kt
|
mbakgun
| 629,040,507
| false
| null |
package ui
import app.cash.turbine.test
import data.source.MjImagesDataSource
import di.initKoin
import domain.model.State
import fakes.ErrorMjImagesDataSource
import fakes.SuccessMjImagesDataSource
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.koin.core.context.loadKoinModules
import org.koin.core.context.stopKoin
import org.koin.dsl.module
import org.koin.test.KoinTest
import org.koin.test.get
import util.getDispatcherProvider
@OptIn(ExperimentalCoroutinesApi::class)
class MjImagesViewModelTest : KoinTest {
@BeforeTest
fun setUp() {
initKoin {
modules(module {
factory { MjImagesViewModel(get()) }
})
}
Dispatchers.setMain(getDispatcherProvider().unconfined)
}
@AfterTest
fun tearDown() {
stopKoin()
Dispatchers.resetMain()
}
@Test
fun `when fetch images gets success then state should be updated`() = runTest {
// given
setupDataSource(SuccessMjImagesDataSource())
// when
val viewModel = get<MjImagesViewModel>()
// then
viewModel.state.onEach {
assertEquals(State.CONTENT, it)
}
}
@Test
fun `when fetch images gets success then images should be updated`() = runTest {
// given
setupDataSource(SuccessMjImagesDataSource())
// when
val viewModel = get<MjImagesViewModel>()
// then
viewModel.images.onEach {
assertEquals(1, it.images.size)
}
}
@Test
fun `when refresh images called images should be empty`() = runTest {
// given
setupDataSource(SuccessMjImagesDataSource())
// when
val viewModel = get<MjImagesViewModel>()
// then
viewModel.images.test {
assertEquals(1, awaitItem().images.size)
viewModel.refreshImages()
assertEquals(0, awaitItem().images.size)
cancelAndIgnoreRemainingEvents()
}
}
@Test
fun `when load more called with page=maxPage then nothing happens`() = runTest {
// given
setupDataSource(SuccessMjImagesDataSource())
// when
val viewModel = get<MjImagesViewModel>()
// then
viewModel.state.test {
assertEquals(State.CONTENT, awaitItem())
viewModel.loadMore()
expectNoEvents()
}
}
@Test
fun `when fetch images gets error then state should be updated`() = runTest {
// given
setupDataSource(ErrorMjImagesDataSource())
// when
val viewModel = get<MjImagesViewModel>()
// then
viewModel.state.onEach {
assertEquals(State.ERROR, it)
}
}
private fun setupDataSource(
dataSource: MjImagesDataSource.Remote
) {
loadKoinModules(module {
factory { dataSource }
})
}
}
| 3
| null |
4
| 60
|
5b2962dbd9f9313972014b67b74f06c9af6cab7a
| 3,253
|
midjourney-images-compose-multiplatform
|
The Unlicense
|
sdk/src/test/java/com/moyasar/android/sdk/presentation/viewmodel/FormValidatorTest.kt
|
moyasar
| 389,428,787
| false
|
{"Kotlin": 91616}
|
package com.moyasar.android.sdk.presentation.viewmodel
import android.app.Application
import android.arch.core.executor.testing.InstantTaskExecutorRule
import com.moyasar.android.sdk.R
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Mockito
import org.mockito.MockitoAnnotations
class FormValidatorTest {
@get:Rule
val instantExecutorRule = InstantTaskExecutorRule()
private lateinit var application: Application
private lateinit var formValidator: FormValidator
@Before
fun setUp() {
MockitoAnnotations.openMocks(this)
application = Mockito.mock(Application::class.java)
Mockito.`when`(application.getString(R.string.name_is_required)).thenReturn("Name is required")
Mockito.`when`(application.getString(R.string.only_english_alpha)).thenReturn("Only English alphabet characters are allowed")
Mockito.`when`(application.getString(R.string.both_names_required)).thenReturn("Both names are required")
Mockito.`when`(application.getString(R.string.card_number_required)).thenReturn("Card number is required")
Mockito.`when`(application.getString(R.string.invalid_card_number)).thenReturn("Invalid card number")
Mockito.`when`(application.getString(R.string.unsupported_network)).thenReturn("Unsupported network")
Mockito.`when`(application.getString(R.string.cvc_required)).thenReturn("CVC is required")
Mockito.`when`(application.getString(R.string.invalid_cvc)).thenReturn("Invalid CVC")
Mockito.`when`(application.getString(R.string.expiry_is_required)).thenReturn("Expiry date is required")
Mockito.`when`(application.getString(R.string.invalid_expiry)).thenReturn("Invalid expiry date")
Mockito.`when`(application.getString(R.string.expired_card)).thenReturn("Card is expired")
formValidator = FormValidator(application)
}
@Test
fun testNameValidation() {
formValidator.name.value = ""
assertFalse(formValidator.nameValidator.isValid())
formValidator.name.value = "John"
assertFalse(formValidator.nameValidator.isValid())
formValidator.name.value = "<NAME>"
assertTrue(formValidator.nameValidator.isValid())
}
@Test
fun testNumberValidation() {
formValidator.number.value = ""
assertFalse(formValidator.numberValidator.isValid())
formValidator.number.value = "1234567812345670" // assuming this is an invalid Luhn number
assertFalse(formValidator.numberValidator.isValid())
formValidator.number.value = "4111111111111111" // assuming this is a valid Luhn number
assertTrue(formValidator.numberValidator.isValid())
}
@Test
fun testCvcValidation() {
formValidator.cvc.value = ""
assertFalse(formValidator.cvcValidator.isValid())
formValidator.cvc.value = "12"
assertFalse(formValidator.cvcValidator.isValid())
formValidator.cvc.value = "123"
assertTrue(formValidator.cvcValidator.isValid())
formValidator.cvc.value = "1234"
assertTrue(formValidator.cvcValidator.isValid())
}
@Test
fun testExpiryValidation() {
formValidator.expiry.value = ""
assertFalse(formValidator.expiryValidator.isValid())
formValidator.expiry.value = "12/25" // assuming this is a valid expiry
assertTrue(formValidator.expiryValidator.isValid())
formValidator.expiry.value = "12/18" // assuming this is an expired date
assertFalse(formValidator.expiryValidator.isValid())
}
@Test
fun testFormValidation() {
formValidator.name.value = "<NAME>"
formValidator.number.value = "4111111111111111" // Example valid card number
formValidator.cvc.value = "123"
formValidator.expiry.value = "12/25" // Example valid expiry date
assertTrue(formValidator.validate())
}
}
| 0
|
Kotlin
|
3
| 0
|
233daf2f5e7b107f75a980fc15d4b28af2f75a96
| 3,734
|
moyasar-android-sdk
|
MIT License
|
elmslie-core/src/main/java/vivid/money/elmslie/core/config/ElmslieConfig.kt
|
vivid-money
| 328,970,240
| false
| null |
package vivid.money.elmslie.core.config
import vivid.money.elmslie.core.logger.ElmslieLogger
import vivid.money.elmslie.core.logger.ElmslieLogConfiguration
import vivid.money.elmslie.core.logger.strategy.IgnoreLog
import vivid.money.elmslie.core.store.StateReducer
import vivid.money.elmslie.core.switcher.Switcher
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
object ElmslieConfig {
@Volatile
private lateinit var loggerInternal: ElmslieLogger
@Volatile
private lateinit var reducerExecutorInternal: ScheduledExecutorService
val logger: ElmslieLogger
get() = loggerInternal
val backgroundExecutor: ScheduledExecutorService
get() = reducerExecutorInternal
init {
logger { always(IgnoreLog) }
backgroundExecutor { Executors.newSingleThreadScheduledExecutor() }
}
/**
* Configures logging and error handling
*
* Example:
* ```
* ElmslieConfig.logger {
* fatal(Crash)
* nonfatal(AndroidLog)
* debug(Ignore)
* }
* ```
*/
fun logger(config: (ElmslieLogConfiguration.() -> Unit)) {
ElmslieLogConfiguration().apply(config).build().also { loggerInternal = it }
}
/**
* Configures an executor for running background operations for [StateReducer] and [Switcher].
*
* Example:
* ```
* ElmslieConfig.backgroundExecutor { Executors.newScheduledThreadPool(4) }
* ```
*/
fun backgroundExecutor(builder: () -> ScheduledExecutorService) {
reducerExecutorInternal = builder()
}
}
| 7
|
Kotlin
|
12
| 94
|
fb50f3714da87a912e50bfe95edd6b08eb020b26
| 1,616
|
elmslie
|
Apache License 2.0
|
test-app-reactive/src/test/kotlin/uk/gov/justice/digital/hmpps/testappreactive/integration/auth/customizer/AuthorizeExchangeCustomizerTest.kt
|
ministryofjustice
| 750,400,333
| false
|
{"Kotlin": 161094, "Dockerfile": 2277}
|
package uk.gov.justice.digital.hmpps.testappreactive.integration.auth.customizer
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Import
import uk.gov.justice.digital.hmpps.testappreactive.integration.IntegrationTestBase
import uk.gov.justice.hmpps.kotlin.auth.dsl.ResourceServerConfigurationCustomizer
@Import(AuthorizeExchangeCustomizerTest.CustomizerConfiguration::class)
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
// allow overriding of the ResourceServerConfigurationCustomizer bean definition
properties = ["spring.main.allow-bean-definition-overriding=true"],
)
class AuthorizeExchangeCustomizerTest : IntegrationTestBase() {
@TestConfiguration
class CustomizerConfiguration {
@Bean
fun resourceServerCustomizer() = ResourceServerConfigurationCustomizer {
authorizeExchange {
authorize("/info", hasRole("INFO"))
authorize(anyExchange, hasRole("ANY_REQUEST"))
}
}
}
@BeforeEach
fun beforeEach() {
stubPingWithResponse(200)
}
@Test
fun `should return unauthorized as default unauthorized request paths are overridden`() {
webTestClient.get()
.uri("/health")
.exchange()
.expectStatus()
.isUnauthorized
}
@Test
fun `should return ok as this falls under the any request role`() {
webTestClient.get()
.uri("/health")
.headers(setAuthorisation(roles = listOf("ROLE_ANY_REQUEST")))
.exchange()
.expectStatus()
.isOk
}
@Test
fun `should return unauthorized as we have protected on a role`() {
webTestClient.get()
.uri("/info")
.exchange()
.expectStatus()
.isUnauthorized
}
@Test
fun `should return forbidden if we try with the wrong role`() {
webTestClient.get()
.uri("/info")
.headers(setAuthorisation(roles = listOf("ROLE_ANY_REQUEST")))
.exchange()
.expectStatus()
.isForbidden
}
@Test
fun `should return OK if we use the correct role`() {
webTestClient.get()
.uri("/info")
.headers(setAuthorisation(roles = listOf("ROLE_INFO")))
.exchange()
.expectStatus()
.isOk
}
@Test
fun `should not override a PreAuthorize with the default role`() {
webTestClient.get()
.uri("/time")
.headers(setAuthorisation(roles = listOf("ROLE_ANY_REQUEST")))
.exchange()
.expectStatus()
.isForbidden
}
}
| 1
|
Kotlin
|
1
| 2
|
1bf38c08142996598c7ebc9b206186a5518ff854
| 2,662
|
hmpps-kotlin-lib
|
MIT License
|
plugins/kotlin/gradle/gradle-tooling/impl/src/org/jetbrains/kotlin/idea/gradleTooling/reflect/KotlinSourceSetReflection.kt
|
ingokegel
| 72,937,917
| true
| null |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleTooling.reflect
import org.gradle.api.Named
import org.gradle.api.file.SourceDirectorySet
import org.gradle.api.plugins.ExtensionAware
fun KotlinSourceSetReflection(kotlinSourceSet: Named): KotlinSourceSetReflection {
return KotlinSourceSetReflectionImpl(kotlinSourceSet)
}
interface KotlinSourceSetReflection {
val instance: Named
val name: String
val languageSettings: KotlinLanguageSettingsReflection?
val kotlin: SourceDirectorySet?
val resources: SourceDirectorySet?
val dependsOn: Set<KotlinSourceSetReflection>
val additionalVisibleSourceSets: Set<KotlinSourceSetReflection>
val androidSourceSetInfo: KotlinAndroidSourceSetInfoReflection?
}
private class KotlinSourceSetReflectionImpl(override val instance: Named) : KotlinSourceSetReflection {
override val name: String get() = instance.name
override val languageSettings: KotlinLanguageSettingsReflection? by lazy {
instance.callReflectiveAnyGetter("getLanguageSettings", logger)
?.let { KotlinLanguageSettingsReflection(it) }
}
override val kotlin: SourceDirectorySet? by lazy {
instance.callReflectiveGetter("getKotlin", logger)
}
override val resources: SourceDirectorySet? by lazy {
instance.callReflectiveGetter("getResources", logger)
}
override val dependsOn: Set<KotlinSourceSetReflection> by lazy {
instance.callReflectiveGetter<Iterable<Named>>("getDependsOn", logger)?.map {
KotlinSourceSetReflection(it)
}.orEmpty().toSet()
}
override val additionalVisibleSourceSets: Set<KotlinSourceSetReflection> by lazy {
instance.callReflectiveGetter<Iterable<Named>>("getAdditionalVisibleSourceSets", logger)?.map {
KotlinSourceSetReflection(it)
}.orEmpty().toSet()
}
override val androidSourceSetInfo: KotlinAndroidSourceSetInfoReflection? by lazy {
if (instance !is ExtensionAware) {
logger.logIssue("KotlinSourceSet $instance does not implement 'ExtensionAware'")
return@lazy null
}
val instance = instance.extensions.findByName("androidSourceSetInfo") ?: return@lazy null
KotlinAndroidSourceSetInfoReflection(instance)
}
companion object {
val logger = ReflectionLogger(KotlinSourceSetReflection::class.java)
}
}
| 1
| null |
1
| 2
|
b07eabd319ad5b591373d63c8f502761c2b2dfe8
| 2,501
|
intellij-community
|
Apache License 2.0
|
app/src/main/java/org/kiteio/punica/MainActivity.kt
|
Kiteio
| 815,391,946
| false
|
{"Kotlin": 446759}
|
package org.kiteio.punica
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.compose.rememberNavController
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import org.kiteio.punica.candy.catching
import org.kiteio.punica.datastore.Keys
import org.kiteio.punica.datastore.Preferences
import org.kiteio.punica.datastore.Users
import org.kiteio.punica.datastore.get
import org.kiteio.punica.edu.foundation.User
import org.kiteio.punica.ui.AppViewModel
import org.kiteio.punica.ui.LocalNavController
import org.kiteio.punica.ui.LocalViewModel
import org.kiteio.punica.ui.PunicaTheme
import org.kiteio.punica.ui.navigation.NavHost
import org.kiteio.punica.ui.navigation.Route
import org.kiteio.punica.ui.navigation.composable
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
AppContext = applicationContext
setContent {
PunicaTheme {
val viewModel = viewModel { AppViewModel() }
// 自动登录
LaunchedEffect(key1 = Unit) {
catching {
flow {
Preferences.data.collect {
it[Keys.lastUsername]?.let { username -> emit(username) }
}
}.collect { username ->
Users.data.collect {
it.get<User>(username)?.let { user ->
viewModel.login(user).first()
}
}
}
}
}
val navController = rememberNavController()
CompositionLocalProvider(
LocalViewModel provides viewModel,
LocalNavController provides navController
) {
NavHost(
navController = navController,
startRoute = Route.Main,
enterTransition = { fadeIn() + slideInHorizontally { it / 2 } },
exitTransition = { fadeOut() + slideOutHorizontally { -it / 2 } },
popEnterTransition = { fadeIn() + slideInHorizontally { -it / 2 } },
popExitTransition = { fadeOut() + slideOutHorizontally { it / 2 } },
) {
composable(Route.Main)
composable(Route.Login)
composable(Route.Account)
composable(Route.Version)
composable(Route.Settings)
composable(Route.Module.values)
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
b1d3f06f3727c876842b2c7cfe74835f6e89a66a
| 3,353
|
Punica
|
MIT License
|
plugins/core/src/main/kotlin/de/fayard/refreshVersions/core/RefreshVersionsCorePlugin.kt
|
Splitties
| 150,827,271
| false
| null |
package de.fayard.refreshVersions.core
import de.fayard.refreshVersions.core.extensions.gradle.isBuildSrc
import de.fayard.refreshVersions.core.extensions.gradle.isRootProject
import de.fayard.refreshVersions.core.internal.InternalRefreshVersionsApi
import de.fayard.refreshVersions.core.internal.RefreshVersionsConfigHolder
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.register
import org.slf4j.Marker
import org.slf4j.helpers.BasicMarkerFactory
open class RefreshVersionsCorePlugin : Plugin<Project> {
override fun apply(project: Project) {
check(project.isRootProject) { "ERROR: de.fayard.refreshVersions.core should not be applied manually" }
if (project.isBuildSrc.not()) {
// In the case where this runs in includedBuilds, the task configuration lambda may (will) run
// after the `Gradle.buildFinished { … }` callback is executed, which means the
// RefreshVersionsConfigHolder content will be cleared, so we get the value before.
val versionsFileName = RefreshVersionsConfigHolder.versionsPropertiesFile.name
project.tasks.register<RefreshVersionsTask>(name = "refreshVersions") {
group = "refreshVersions"
description = "Search for new dependencies versions and update $versionsFileName"
}
project.tasks.register<RefreshVersionsCleanupTask>(name = "refreshVersionsCleanup") {
group = "refreshVersions"
description = "Cleanup versions availability comments"
}
}
cleanFilesFromPreviousVersions(project)
}
private fun cleanFilesFromPreviousVersions(project: Project) {
if (project.isBuildSrc) {
project.buildDir.resolve("refreshVersions_used_dependencies.txt").delete()
project.buildDir.resolve("refreshVersions_used_repositories_maven.txt").delete()
} else {
project.buildDir.resolve("refreshVersions_used_dependencies_plugins.txt").delete()
project.buildDir.resolve("refreshVersions_used_repositories_plugins_maven.txt").delete()
}
}
@InternalRefreshVersionsApi
object LogMarkers {
@JvmField
val default: Marker = BasicMarkerFactory().getMarker("refreshVersions")
}
@InternalRefreshVersionsApi
companion object {
val currentVersion by lazy {
RefreshVersionsCorePlugin::class.java.getResourceAsStream("/version.txt")!!
.bufferedReader()
.useLines { it.first() }
}
}
}
| 80
|
Kotlin
|
92
| 1,571
|
2c04a6047e586cd25236916f7be6bc81ccd25997
| 2,606
|
refreshVersions
|
MIT License
|
app/src/main/java/com/lelestacia/hayate/domain/state/AppBarState.kt
|
gab-stargazer
| 717,145,817
| false
|
{"Kotlin": 459698}
|
package com.lelestacia.hayate.domain.state
import androidx.annotation.StringRes
import com.lelestacia.hayate.R
import com.lelestacia.hayate.core.common.Screen
data class AppBarState(
// Current route, i don't want to pass navController around
val currentRoute: String = Screen.Init.route,
// This part is for how the Appbar styled
val isDarkTheme: Boolean = false,
// This part determined General Appbar Condition
@StringRes val appBarTitle: Int = R.string.japanese_app_name,
val shouldAppBarBeVisible: Boolean = false,
val shouldNavigationIconBeVisible: Boolean = false,
// This part is for search query stuff
val searchQuery: String = "",
val isSearchModeActive: Boolean = false,
val shouldSearchIconBeVisible: Boolean = false,
// This part is for Detail Screen
val animeID: Int? = null,
val trailerURL: String? = null,
)
| 0
|
Kotlin
|
0
| 4
|
892b443a225f787aa99631a3fb02fad517f7f19f
| 896
|
hayate
|
MIT License
|
educational-core/src/com/jetbrains/edu/learning/stepik/hyperskill/widget/HyperskillWidget.kt
|
telezhnaya
| 264,863,128
| true
|
{"Kotlin": 2477547, "Java": 634238, "HTML": 131915, "CSS": 12844, "Python": 3994, "JavaScript": 315}
|
package com.jetbrains.edu.learning.stepik.hyperskill.widget
import com.intellij.openapi.project.Project
import com.jetbrains.edu.learning.EduLogInListener
import com.jetbrains.edu.learning.EduNames
import com.jetbrains.edu.learning.LoginWidget
import com.jetbrains.edu.learning.authUtils.OAuthAccount
import com.jetbrains.edu.learning.stepik.hyperskill.api.HyperskillConnector
import com.jetbrains.edu.learning.stepik.hyperskill.settings.HyperskillSettings
import icons.EducationalCoreIcons
import javax.swing.Icon
class HyperskillWidget(project: Project) : LoginWidget(project, HyperskillConnector.AUTHORIZATION_TOPIC, EduNames.JBA) {
override val account: OAuthAccount<out Any>? get() = HyperskillSettings.INSTANCE.account
override val icon: Icon get() = EducationalCoreIcons.JB_ACADEMY_ENABLED
override val disabledIcon: Icon get() = EducationalCoreIcons.JB_ACADEMY_DISABLED
override fun ID() = "HyperskillAccountWidget"
override fun authorize() {
HyperskillConnector.getInstance().doAuthorize()
}
override fun resetAccount() {
HyperskillSettings.INSTANCE.account = null
project.messageBus.syncPublisher<EduLogInListener>(HyperskillConnector.AUTHORIZATION_TOPIC).userLoggedOut()
}
}
| 0
| null |
0
| 0
|
9f9492f7505fb86df37c9d582814c075aa3a611d
| 1,219
|
educational-plugin
|
Apache License 2.0
|
core/ui/src/main/kotlin/com/ekezet/othello/core/ui/navigation/Finishable.kt
|
atomgomba
| 754,770,216
| false
|
{"Kotlin": 218762}
|
package com.ekezet.othello.core.ui.navigation
interface Finishable {
fun finish()
}
| 0
|
Kotlin
|
0
| 1
|
fd6e9345379768da5de5dbe42be377802f3e18c8
| 89
|
othello
|
Apache License 2.0
|
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/Scribble.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.bold
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 me.localx.icons.straight.Icons
public val Icons.Bold.Scribble: ImageVector
get() {
if (_scribble != null) {
return _scribble!!
}
_scribble = Builder(name = "Scribble", 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) {
moveToRelative(17.5f, 24.043f)
curveToRelative(-1.432f, 0.0f, -2.76f, -0.539f, -3.739f, -1.519f)
curveToRelative(-0.98f, -0.979f, -1.52f, -2.282f, -1.52f, -3.667f)
reflectiveCurveToRelative(0.54f, -2.688f, 1.52f, -3.668f)
lineToRelative(6.964f, -6.965f)
curveToRelative(0.189f, -0.188f, 0.292f, -0.439f, 0.292f, -0.707f)
reflectiveCurveToRelative(-0.104f, -0.519f, -0.293f, -0.707f)
curveToRelative(-0.377f, -0.377f, -1.037f, -0.379f, -1.414f, 0.0f)
lineToRelative(-12.5f, 12.5f)
curveToRelative(-1.51f, 1.512f, -4.146f, 1.512f, -5.657f, 0.0f)
curveTo(0.398f, 18.555f, -0.018f, 17.551f, -0.018f, 16.482f)
reflectiveCurveToRelative(0.416f, -2.073f, 1.171f, -2.828f)
lineTo(10.213f, 4.701f)
curveToRelative(0.183f, -0.184f, 0.287f, -0.435f, 0.287f, -0.701f)
reflectiveCurveToRelative(-0.104f, -0.518f, -0.293f, -0.707f)
curveToRelative(-0.378f, -0.379f, -1.037f, -0.379f, -1.414f, 0.0f)
lineToRelative(-6.679f, 6.572f)
lineTo(0.01f, 7.727f)
lineTo(6.68f, 1.163f)
curveToRelative(0.747f, -0.747f, 1.751f, -1.163f, 2.82f, -1.163f)
reflectiveCurveToRelative(2.073f, 0.416f, 2.829f, 1.172f)
curveToRelative(1.559f, 1.56f, 1.559f, 4.097f, 0.0f, 5.656f)
lineTo(3.269f, 15.781f)
curveToRelative(-0.183f, 0.183f, -0.286f, 0.434f, -0.286f, 0.701f)
reflectiveCurveToRelative(0.104f, 0.519f, 0.293f, 0.707f)
curveToRelative(0.377f, 0.377f, 1.037f, 0.379f, 1.414f, 0.0f)
lineToRelative(12.5f, -12.5f)
curveToRelative(1.51f, -1.512f, 4.146f, -1.512f, 5.657f, 0.0f)
curveToRelative(0.755f, 0.756f, 1.171f, 1.76f, 1.171f, 2.828f)
reflectiveCurveToRelative(-0.416f, 2.073f, -1.171f, 2.828f)
lineToRelative(-6.964f, 6.965f)
curveToRelative(-0.413f, 0.413f, -0.641f, 0.962f, -0.641f, 1.547f)
reflectiveCurveToRelative(0.228f, 1.133f, 0.641f, 1.546f)
curveToRelative(0.413f, 0.412f, 0.987f, 0.64f, 1.618f, 0.64f)
curveToRelative(2.231f, 0.0f, 3.221f, -0.69f, 4.368f, -1.49f)
lineToRelative(0.424f, -0.294f)
lineToRelative(1.686f, 2.482f)
lineToRelative(-0.394f, 0.271f)
curveToRelative(-1.296f, 0.904f, -2.91f, 2.03f, -6.084f, 2.03f)
close()
}
}
.build()
return _scribble!!
}
private var _scribble: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 3,865
|
icons
|
MIT License
|
app/src/main/java/com/example/cs567_3d_ui_project/qgis_driver/resource_objects/wms_resources/GetSchemaExtensionResponse.kt
|
csu-hci-projects
| 694,848,698
| false
|
{"Kotlin": 91009}
|
package com.example.cs567_3d_ui_project.qgis_driver.resource_objects.wms_resources
import com.example.cs567_3d_ui_project.qgis_driver.resource_objects.HttpResponse
import com.example.cs567_3d_ui_project.qgis_driver.resource_objects.HttpResponseContent
import com.google.gson.GsonBuilder
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.google.gson.annotations.SerializedName
class GetSchemaExtensionResponse(content: String, responseCode: Int)
: HttpResponse(content, responseCode)
{
val getSchemaExtensionResponseContent = deserializeJsonObject(content)
override fun deserializeJsonObject(properties: String): GetSchemaExtensionResponseContent {
val builder = GsonBuilder()
builder.setPrettyPrinting()
val gson = builder.create()
try {
return gson.fromJson(properties, GetSchemaExtensionResponseContent::class.java)
} catch (e: Exception) {
throw e
}
}
}
data class GetSchemaExtensionResponseContent(
@SerializedName("schema")
var schema: GetSchemaExtensionContent
) : HttpResponseContent()
data class GetSchemaExtensionContent(
@SerializedName("xmlns")
var xmlns: String,
@SerializedName("elementFormDefault")
var elementFormDefault: String,
@SerializedName("import")
var import: JsonObject,
@SerializedName("xmlns:wms")
var xmlnsWms: String,
@SerializedName("xmlns:qgs")
var xmlnsQgs: String,
@SerializedName("targetNamespace")
var targetNamespace: String,
@SerializedName("version")
var version: String,
@SerializedName("element")
var element: JsonArray,
)
| 0
|
Kotlin
|
0
| 0
|
40ca9d803c4349d3b088e3e82d366de129c51b4d
| 1,664
|
FA23-Visualization-of-Infrastructure-with-a-3D-GIS-Mobile-Application
|
MIT License
|
src/main/kotlin/io/github/marco4413/kwasm/runtime/Label.kt
|
Marco4413
| 590,497,284
| false
| null |
package io.github.marco4413.kwasm.runtime
import io.github.marco4413.kwasm.bytecode.Expression
import io.github.marco4413.kwasm.bytecode.U32
import io.github.marco4413.kwasm.instructions.Instruction
open class Label(val body: Expression) : Iterator<Instruction> {
var index: Int = 0
protected set
override fun hasNext(): Boolean {
return index in body.indices
}
override fun next(): Instruction {
return body[index++]
}
// WHY DID IT TAKE SO LONG TO ACTUALLY FIGURE THIS OUT
fun jumpToStart() { index = 0 }
fun jumpToEnd() { index = body.size }
// I SPENT LIKE 2 DAYS DEBUGGING A LOOP TO FIND THIS OUT
open fun branch() = jumpToEnd()
}
class LoopLabel(body: Expression) : Label(body) {
override fun branch() = jumpToStart()
}
| 0
|
Kotlin
|
0
| 0
|
0a70626d5f2f1c103242810e24b9626c843e474b
| 800
|
kwasm
|
MIT License
|
src/main/kotlin/io/github/marco4413/kwasm/runtime/Label.kt
|
Marco4413
| 590,497,284
| false
| null |
package io.github.marco4413.kwasm.runtime
import io.github.marco4413.kwasm.bytecode.Expression
import io.github.marco4413.kwasm.bytecode.U32
import io.github.marco4413.kwasm.instructions.Instruction
open class Label(val body: Expression) : Iterator<Instruction> {
var index: Int = 0
protected set
override fun hasNext(): Boolean {
return index in body.indices
}
override fun next(): Instruction {
return body[index++]
}
// WHY DID IT TAKE SO LONG TO ACTUALLY FIGURE THIS OUT
fun jumpToStart() { index = 0 }
fun jumpToEnd() { index = body.size }
// I SPENT LIKE 2 DAYS DEBUGGING A LOOP TO FIND THIS OUT
open fun branch() = jumpToEnd()
}
class LoopLabel(body: Expression) : Label(body) {
override fun branch() = jumpToStart()
}
| 0
|
Kotlin
|
0
| 0
|
0a70626d5f2f1c103242810e24b9626c843e474b
| 800
|
kwasm
|
MIT License
|
gradle-dsl/src/com/android/tools/idea/gradle/dsl/model/ext/transforms/CompactToMapCatalogDependencyTransform.kt
|
JetBrains
| 60,701,247
| false
| null |
/*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.gradle.dsl.model.ext.transforms
import com.android.tools.idea.gradle.dsl.api.ext.ReferenceTo
import com.android.tools.idea.gradle.dsl.model.dependencies.ArtifactDependencySpecImpl
import com.android.tools.idea.gradle.dsl.model.ext.PropertyUtil
import com.android.tools.idea.gradle.dsl.parser.dependencies.FakeArtifactElement
import com.android.tools.idea.gradle.dsl.parser.elements.GradleDslElement
import com.android.tools.idea.gradle.dsl.parser.elements.GradleDslExpression
import com.android.tools.idea.gradle.dsl.parser.elements.GradleDslExpressionMap
import com.android.tools.idea.gradle.dsl.parser.elements.GradleDslLiteral
import com.android.tools.idea.gradle.dsl.parser.elements.GradleNameElement
import com.android.tools.idea.gradle.dsl.parser.files.GradleVersionCatalogFile
/**
* Class transforms compact notation to map notation if user wants to set variable to compact dependency notation
* that is at catalog file. Toml syntax does not support interpolation.
*/
class CompactToMapCatalogDependencyTransform : PropertyTransform() {
override fun test(e: GradleDslElement?, holder: GradleDslElement): Boolean {
if (e == null)
return false
return (e is FakeArtifactElement &&
e.realExpression is GradleDslLiteral &&
e.realExpression.dslFile is GradleVersionCatalogFile)
}
override fun transform(e: GradleDslElement?): GradleDslElement? = e
override fun bind(holder: GradleDslElement, oldElement: GradleDslElement?, value: Any, name: String): GradleDslExpression? {
if (oldElement is FakeArtifactElement) {
val literal = when(value) {
is ReferenceTo -> GradleVersionCatalogFile.GradleDslVersionLiteral(holder, GradleNameElement.create(name), value)
else -> oldElement
}
literal.setValue(value)
return literal
}
return null
}
override fun replace(holder: GradleDslElement,
oldElement: GradleDslElement?,
newElement: GradleDslExpression,
name: String): GradleDslElement {
val fakeElement = (oldElement as FakeArtifactElement)
val literal = fakeElement.realExpression as GradleDslLiteral
val spec = ArtifactDependencySpecImpl.create(literal.value as String)!!
val expressionMap = GradleDslExpressionMap(holder, GradleNameElement.create(literal.name))
spec.group?.let {
expressionMap.setNewLiteral("group", it)
}
expressionMap.setNewLiteral("name", spec.name)
// adding version
expressionMap.setNewElement(newElement)
// toml does not support classifier of extension - omit them here
PropertyUtil.replaceElement(holder, literal, expressionMap)
return newElement
}
}
| 5
| null |
230
| 948
|
10110983c7e784122d94c7467e9d243aba943bf4
| 3,380
|
android
|
Apache License 2.0
|
src/main/kotlin/io/github/tsb99x/trakt/core/entity/ApiTokenEntity.kt
|
tsb99x
| 203,202,702
| false
| null |
package io.github.tsb99x.trakt.core.entity
import java.time.Instant
import java.util.*
data class ApiTokenEntity(
val id: UUID,
val userId: UUID,
val createdAt: Instant,
val lastUsedAt: Instant
)
| 12
|
Kotlin
|
0
| 0
|
8c664fb60d185c4fc466d8026a76eb3ccd4ccae8
| 214
|
trakt
|
MIT License
|
app/src/main/java/com/lizongying/mytv/api/LiveInfo.kt
|
lizongying
| 727,213,319
| false
|
{"C": 1971354, "Kotlin": 342893, "Java": 143291, "CMake": 3899, "Makefile": 204}
|
package com.lizongying.mytv.api
import android.util.Log
import okhttp3.MediaType
import okhttp3.RequestBody
import okio.BufferedSink
import java.io.IOException
data class LiveInfo(
val code: Int,
val msg: String,
val data: LiveInfoData,
)
data class LiveInfoData(
val extended_param: String,
val chanll: String,
val playurl: String,
val errinfo: String,
)
data class LiveInfoRequest(
var data: String,
) : RequestBody() {
override fun contentType(): MediaType? {
return MediaType.parse("application/json;charset=UTF-8")
}
override fun writeTo(sink: BufferedSink) {
try {
sink.writeUtf8(data)
} catch (e: IOException) {
Log.e(TAG, "$e")
}
}
companion object {
private const val TAG = "LiveInfoRequest"
}
}
| 126
|
C
|
3005
| 26,803
|
b372d52510a494bfc57b3c05fa8cf95a78028c82
| 830
|
my-tv
|
Apache License 2.0
|
kmdc/kmdc-slider/src/jsMain/kotlin/MDCSliderTrack.kt
|
mpetuska
| 430,798,310
| false
| null |
package dev.petuska.kmdc.slider
import androidx.compose.runtime.Composable
import dev.petuska.kmdc.core.MDCDsl
import org.jetbrains.compose.web.dom.AttrBuilderContext
import org.jetbrains.compose.web.dom.Div
import org.w3c.dom.HTMLDivElement
/**
* [JS API](https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc-slider)
*/
@MDCDsl
@Composable
internal fun MDCSliderOpts.MDCSliderTrack(
attrs: AttrBuilderContext<HTMLDivElement>? = null,
) {
Div(attrs = {
classes("mdc-slider__track")
attrs?.invoke(this)
}) {
Div(attrs = {
classes("mdc-slider__track--inactive")
})
Div(attrs = {
classes("mdc-slider--active")
}) {
Div(attrs = {
classes("mdc-slider__track--active_fill")
})
}
if (tickMarks) MDCSliderTickMarks()
}
}
/**
* [JS API](https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc-slider)
*/
@MDCDsl
@Composable
private fun MDCSliderTickMarks(
attrs: AttrBuilderContext<HTMLDivElement>? = null,
) {
Div(
attrs = {
classes("mdc-slider__tick-marks")
attrs?.invoke(this)
},
)
}
| 22
|
Kotlin
|
8
| 29
|
67b31502b5f76b64f7571821fdd0b78a3df0a68c
| 1,152
|
kmdc
|
Apache License 2.0
|
nuget-feed/src/jetbrains/buildServer/nuget/feed/server/index/impl/NuGetBuildMetadataProvider.kt
|
38438-38438-org
| 193,887,431
| false
|
{"INI": 2, "Text": 14, "Gradle": 9, "Shell": 1, "EditorConfig": 2, "Markdown": 1, "Batchfile": 1, "Ignore List": 1, "Java": 418, "XML": 116, "Kotlin": 80, "JSON": 2, "Java Server Pages": 18, "CSS": 1, "JavaScript": 1, "Microsoft Visual Studio Solution": 20, "C#": 101}
|
package jetbrains.buildServer.nuget.feed.server.index.impl
import jetbrains.buildServer.serverSide.SBuild
interface NuGetBuildMetadataProvider {
fun getPackagesMetadata(build: SBuild): Collection<Map<String, String>>
}
| 1
| null |
1
| 1
|
6cff9f41569191e258c63b1140fdfbfe5f9a7be9
| 225
|
teamcity-nuget-support
|
Apache License 2.0
|
src/main/kotlin/io/holunda/camunda/platform/login/ExtendedContainerBasedAuthenticationFilter.kt
|
holunda-io
| 485,963,351
| false
|
{"Kotlin": 6657}
|
package io.holunda.camunda.platform.login
import jakarta.servlet.FilterConfig
import org.camunda.bpm.engine.rest.security.auth.AuthenticationProvider
import org.camunda.bpm.webapp.impl.security.auth.ContainerBasedAuthenticationFilter
/**
* Uses provided instance of authentication provider instead of creation of it by reflection.
*/
open class ExtendedContainerBasedAuthenticationFilter(
private val provider: AuthenticationProvider
) : ContainerBasedAuthenticationFilter() {
override fun init(filterConfig: FilterConfig) {
super.authenticationProvider = provider
}
}
| 1
|
Kotlin
|
0
| 10
|
4c6307481866eaaad616e4e4c52e8b15561adff4
| 584
|
camunda-platform-7-autologin
|
Apache License 2.0
|
app/src/main/java/com/mapswithme/maps/settings/StorageItem.kt
|
dnemov
| 245,413,600
| false
| null |
package com.mapswithme.maps.settings
import com.mapswithme.util.Constants
/**
* Represents storage option.
*/
class StorageItem internal constructor(// Path to the root of writable directory.
val mPath: String?, // Free size.
val mFreeSize: Long
) {
override fun equals(o: Any?): Boolean {
if (o === this) return true
if (o == null || o !is StorageItem) return false
val other = o
// Storage equal is considered equal, either its path OR size equals to another one's.
// Size of storage free space can change dynamically, so that hack provides us with better results identifying the same storages.
return mFreeSize == other.mFreeSize || mPath == other.mPath
}
override fun hashCode(): Int { // Yes, do not put StorageItem to Hash containers, performance will be awful.
// At least such hash is compatible with hacky equals.
return 0
}
override fun toString(): String {
return "$mPath, $mFreeSize"
}
val fullPath: String
get() = mPath + Constants.MWM_DIR_POSTFIX
}
| 0
|
Kotlin
|
0
| 1
|
8b75114193e141aee14fcbc207a208c4a39de1db
| 1,072
|
omim.kt
|
Apache License 2.0
|
sdk/src/main/java/com/qonversion/android/sdk/internal/QProductCenterManager.kt
|
qonversion
| 224,974,105
| false
| null |
package com.qonversion.android.sdk.internal
import android.app.Activity
import android.app.Application
import android.content.pm.PackageManager
import android.os.Build
import android.util.Pair
import com.android.billingclient.api.BillingFlowParams
import com.android.billingclient.api.Purchase
import com.android.billingclient.api.*
import com.qonversion.android.sdk.dto.entitlements.QEntitlement
import com.qonversion.android.sdk.listeners.QonversionEligibilityCallback
import com.qonversion.android.sdk.dto.QonversionError
import com.qonversion.android.sdk.dto.QonversionErrorCode
import com.qonversion.android.sdk.listeners.QonversionLaunchCallback
import com.qonversion.android.sdk.listeners.QonversionOfferingsCallback
import com.qonversion.android.sdk.listeners.QonversionEntitlementsCallback
import com.qonversion.android.sdk.listeners.QonversionProductsCallback
import com.qonversion.android.sdk.internal.LoadStoreProductsState.NotStartedYet
import com.qonversion.android.sdk.internal.LoadStoreProductsState.Loaded
import com.qonversion.android.sdk.internal.LoadStoreProductsState.Failed
import com.qonversion.android.sdk.internal.LoadStoreProductsState.Loading
import com.qonversion.android.sdk.internal.billing.QonversionBillingService
import com.qonversion.android.sdk.internal.converter.GoogleBillingPeriodConverter
import com.qonversion.android.sdk.internal.converter.GooglePurchaseConverter
import com.qonversion.android.sdk.internal.converter.PurchaseConverter
import com.qonversion.android.sdk.internal.dto.QLaunchResult
import com.qonversion.android.sdk.internal.dto.QPermission
import com.qonversion.android.sdk.dto.entitlements.QEntitlementSource
import com.qonversion.android.sdk.dto.QUser
import com.qonversion.android.sdk.dto.eligibility.QEligibility
import com.qonversion.android.sdk.dto.offerings.QOfferings
import com.qonversion.android.sdk.dto.products.QProduct
import com.qonversion.android.sdk.internal.dto.QProductRenewState
import com.qonversion.android.sdk.internal.billing.BillingError
import com.qonversion.android.sdk.internal.billing.BillingService
import com.qonversion.android.sdk.internal.billing.sku
import com.qonversion.android.sdk.internal.dto.request.data.InitRequestData
import com.qonversion.android.sdk.internal.extractor.SkuDetailsTokenExtractor
import com.qonversion.android.sdk.internal.logger.Logger
import com.qonversion.android.sdk.internal.provider.AppStateProvider
import com.qonversion.android.sdk.internal.provider.UserStateProvider
import com.qonversion.android.sdk.internal.purchase.PurchaseHistory
import com.qonversion.android.sdk.internal.services.QUserInfoService
import com.qonversion.android.sdk.internal.storage.LaunchResultCacheWrapper
import com.qonversion.android.sdk.internal.storage.PurchasesCache
import com.qonversion.android.sdk.listeners.QEntitlementsUpdateListener
import com.qonversion.android.sdk.listeners.QonversionUserCallback
import java.util.Date
@SuppressWarnings("LongParameterList")
internal class QProductCenterManager internal constructor(
private val context: Application,
private val repository: QonversionRepository,
private val logger: Logger,
private val purchasesCache: PurchasesCache,
private val handledPurchasesCache: QHandledPurchasesCache,
private val launchResultCache: LaunchResultCacheWrapper,
private val userInfoService: QUserInfoService,
private val identityManager: QIdentityManager,
private val internalConfig: InternalConfig,
private val appStateProvider: AppStateProvider,
private val remoteConfigManager: QRemoteConfigManager
) : QonversionBillingService.PurchasesListener, UserStateProvider {
override val isUserStable: Boolean
get() = isLaunchingFinished &&
processingPartnersIdentityId == null &&
pendingPartnersIdentityId.isNullOrEmpty() &&
!unhandledLogoutAvailable
private val isLaunchingFinished: Boolean
get() = launchError != null || launchResultCache.sessionLaunchResult != null
private var isRestoreInProgress = false
private var loadProductsState = NotStartedYet
@Suppress("DEPRECATION")
private var skuDetails = mapOf<String, SkuDetails>()
private var launchError: QonversionError? = null
private var productsCallbacks = mutableListOf<QonversionProductsCallback>()
private var entitlementCallbacks = mutableListOf<QonversionEntitlementsCallback>()
private var purchasingCallbacks = mutableMapOf<String, QonversionEntitlementsCallback>()
private var restoreCallbacks = mutableListOf<QonversionEntitlementsCallback>()
private var processingPartnersIdentityId: String? = null
private var pendingPartnersIdentityId: String? = null
private var unhandledLogoutAvailable: Boolean = false
private var installDate: Long = 0
private var advertisingID: String? = null
private var pendingInitRequestData: InitRequestData? = null
@Suppress("DEPRECATION")
private var converter: PurchaseConverter<Pair<SkuDetails, Purchase>> =
GooglePurchaseConverter(SkuDetailsTokenExtractor())
@Volatile
lateinit var billingService: BillingService
@Synchronized set
@Synchronized get
@Volatile
lateinit var consumer: Consumer
@Synchronized set
@Synchronized get
init {
val packageInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
context.packageManager.getPackageInfo(
context.packageName,
PackageManager.PackageInfoFlags.of(PackageManager.GET_META_DATA.toLong())
)
} else {
@Suppress("DEPRECATION")
context.packageManager.getPackageInfo(context.packageName, PackageManager.GET_META_DATA)
}
installDate = packageInfo.firstInstallTime.milliSecondsToSeconds()
}
// Public functions
fun onAppForeground() {
handlePendingPurchases()
processPendingInitIfAvailable()
}
fun launch(
callback: QonversionLaunchCallback? = null
) {
val launchCallback: QonversionLaunchCallback = getLaunchCallback(callback)
launchError = null
launchResultCache.resetSessionCache()
if (!internalConfig.primaryConfig.isKidsMode) {
val adProvider = AdvertisingProvider()
adProvider.init(context, object : AdvertisingProvider.Callback {
override fun onSuccess(advertisingId: String) {
advertisingID = advertisingId
continueLaunchWithPurchasesInfo(launchCallback)
}
override fun onFailure(t: Throwable) {
continueLaunchWithPurchasesInfo(launchCallback)
}
})
} else {
continueLaunchWithPurchasesInfo(launchCallback)
}
}
fun loadProducts(
callback: QonversionProductsCallback
) {
productsCallbacks.add(callback)
val isProductsLoaded = loadProductsState in listOf(Loaded, Failed)
if (!isProductsLoaded || !isLaunchingFinished) {
return
}
retryLaunchForProducts { executeProductsBlocks() }
}
fun offerings(
callback: QonversionOfferingsCallback
) {
loadProducts(object : QonversionProductsCallback {
override fun onSuccess(products: Map<String, QProduct>) =
executeOfferingCallback(callback)
override fun onError(error: QonversionError) = callback.onError(error)
})
}
fun identify(userID: String) {
if (processingPartnersIdentityId == userID || identityManager.currentPartnersIdentityId == userID) {
return
}
unhandledLogoutAvailable = false
pendingPartnersIdentityId = userID
if (!isLaunchingFinished || isRestoreInProgress) {
return
}
processingPartnersIdentityId = userID
if (launchError != null) {
val callback = object : QonversionLaunchCallback {
override fun onSuccess(launchResult: QLaunchResult) {
processIdentity(userID)
}
override fun onError(error: QonversionError, httpCode: Int?) {
processingPartnersIdentityId = null
remoteConfigManager.userChangingRequestFailedWithError(error)
executeEntitlementsBlock(error)
}
}
val initRequestData = InitRequestData(installDate, advertisingID, callback = callback)
repository.init(initRequestData)
} else {
processIdentity(userID)
}
}
private fun processIdentity(userID: String) {
val currentUserID = userInfoService.obtainUserID()
identityManager.identify(userID, object : IdentityManagerCallback {
override fun onSuccess(identityID: String) {
pendingPartnersIdentityId = null
processingPartnersIdentityId = null
if (currentUserID == identityID) {
handlePendingRequests()
} else {
internalConfig.uid = identityID
remoteConfigManager.onUserUpdate()
launchResultCache.clearPermissionsCache()
launch()
}
}
override fun onError(error: QonversionError) {
processingPartnersIdentityId = null
executeEntitlementsBlock(error)
remoteConfigManager.userChangingRequestFailedWithError(error)
}
})
}
fun checkTrialIntroEligibilityForProductIds(
productIds: List<String>,
callback: QonversionEligibilityCallback
) {
loadProducts(object : QonversionProductsCallback {
override fun onSuccess(products: Map<String, QProduct>) {
val storeIds = products.map { it.value.skuDetail?.sku }.filterNotNull()
repository.eligibilityForProductIds(
storeIds,
installDate,
object : QonversionEligibilityCallback {
override fun onSuccess(eligibilities: Map<String, QEligibility>) {
val resultForRequiredProductIds =
eligibilities.filter { it.key in productIds }
callback.onSuccess(resultForRequiredProductIds)
}
override fun onError(error: QonversionError) = callback.onError(error)
})
}
override fun onError(error: QonversionError) = callback.onError(error)
})
}
private fun executeOfferingCallback(callback: QonversionOfferingsCallback) {
val offerings = getOfferings()
if (offerings != null) {
offerings.availableOfferings.forEach { offering ->
addSkuDetailForProducts(offering.products)
}
callback.onSuccess(offerings)
} else {
val error = launchError ?: QonversionError(QonversionErrorCode.OfferingsNotFound)
callback.onError(error)
}
}
private fun getOfferings(): QOfferings? {
return launchResultCache.getLaunchResult()?.offerings
}
private fun addSkuDetailForProducts(products: Collection<QProduct>) {
products.forEach { product ->
product.skuDetail = skuDetails[product.storeID]
}
}
fun purchaseProduct(
context: Activity,
product: QProduct,
oldProductId: String?,
@Suppress("DEPRECATION") @BillingFlowParams.ProrationMode prorationMode: Int?,
callback: QonversionEntitlementsCallback
) {
purchaseProduct(
context,
product.qonversionID,
oldProductId,
prorationMode,
callback
)
}
fun purchaseProduct(
context: Activity,
productId: String,
oldProductId: String?,
@Suppress("DEPRECATION") @BillingFlowParams.ProrationMode prorationMode: Int?,
callback: QonversionEntitlementsCallback
) {
if (launchError != null) {
retryLaunch(
onSuccess = {
tryToPurchase(
context,
productId,
oldProductId,
prorationMode,
callback
)
},
onError = {
tryToPurchase(
context,
productId,
oldProductId,
prorationMode,
callback
)
}
)
} else {
tryToPurchase(context, productId, oldProductId, prorationMode, callback)
}
}
private fun tryToPurchase(
context: Activity,
id: String,
oldProductId: String?,
@Suppress("DEPRECATION") @BillingFlowParams.ProrationMode prorationMode: Int?,
callback: QonversionEntitlementsCallback
) {
when (loadProductsState) {
Loading, NotStartedYet -> {
productsCallbacks.add(object : QonversionProductsCallback {
override fun onSuccess(products: Map<String, QProduct>) =
processPurchase(
context,
id,
oldProductId,
prorationMode,
callback
)
override fun onError(error: QonversionError) = callback.onError(error)
})
}
Loaded, Failed -> {
processPurchase(context, id, oldProductId, prorationMode, callback)
}
}
}
private fun processPurchase(
context: Activity,
productId: String,
oldProductId: String?,
@Suppress("DEPRECATION") @BillingFlowParams.ProrationMode prorationMode: Int?,
callback: QonversionEntitlementsCallback
) {
val launchResult = launchResultCache.getLaunchResult() ?: run {
callback.onError(launchError ?: QonversionError(QonversionErrorCode.LaunchError))
return
}
val product: QProduct? = getProductForPurchase(productId, launchResult)
val oldProduct: QProduct? = launchResult.products[oldProductId]
if (product?.storeID == null) {
callback.onError(QonversionError(QonversionErrorCode.ProductNotFound))
return
}
val purchasingCallback = purchasingCallbacks[product.storeID]
purchasingCallback?.let {
logger.release(
"purchaseProduct() -> Purchase with id = " +
"$productId is already in progress. This one call will be ignored"
)
return
}
val skuDetail = skuDetails[product.storeID]
val oldSkuDetail = skuDetails[oldProduct?.storeID]
if (skuDetail != null) {
purchasingCallbacks[product.storeID] = callback
billingService.purchase(context, skuDetail, oldSkuDetail, prorationMode)
} else {
if (loadProductsState == Loaded) {
val error = QonversionError(QonversionErrorCode.SkuDetailsError)
callback.onError(error)
return
}
loadStoreProductsIfPossible(
onLoadCompleted = { skuDetailsList ->
val sku = skuDetailsList.find { detail ->
detail.sku == product.storeID
}
if (sku != null) {
purchasingCallbacks[product.storeID] = callback
billingService.purchase(context, sku)
}
}, onLoadFailed = { error ->
callback.onError(error)
})
}
}
private fun getProductForPurchase(
productId: String?,
launchResult: QLaunchResult
): QProduct? {
if (productId == null) {
return null
}
return launchResult.products[productId]
}
fun checkEntitlements(callback: QonversionEntitlementsCallback) {
entitlementCallbacks.add(callback)
handlePendingRequests()
}
fun restore(callback: QonversionEntitlementsCallback? = null) {
callback?.let { restoreCallbacks.add(it) }
if (isRestoreInProgress) {
return
}
isRestoreInProgress = true
billingService.queryPurchasesHistory(
onQueryHistoryCompleted = { historyRecords ->
consumer.consumeHistoryRecords(historyRecords)
val skuIds = historyRecords.mapNotNull { it.historyRecord.sku }
val loadedSkuDetails =
skuDetails.filter { skuIds.contains(it.value.sku) }.toMutableMap()
val resultSkuIds = (skuIds - loadedSkuDetails.keys).toSet()
if (resultSkuIds.isNotEmpty()) {
billingService.loadProducts(resultSkuIds, onLoadCompleted = {
it.forEach { singleSkuDetails ->
run {
loadedSkuDetails[singleSkuDetails.sku] = singleSkuDetails
skuDetails = skuDetails + (singleSkuDetails.sku to singleSkuDetails)
}
}
processRestore(historyRecords, loadedSkuDetails)
}, onLoadFailed = {
processRestore(historyRecords, loadedSkuDetails)
})
} else {
processRestore(historyRecords, loadedSkuDetails)
}
},
onQueryHistoryFailed = {
executeRestoreBlocksOnError(it.toQonversionError())
})
}
fun syncPurchases() {
restore()
}
override fun onPurchasesCompleted(purchases: List<Purchase>) {
handlePurchases(purchases)
}
override fun onPurchasesFailed(purchases: List<Purchase>, error: BillingError) {
if (purchases.isNotEmpty()) {
purchases.forEach { purchase ->
val purchaseCallback = purchasingCallbacks[purchase.sku]
purchasingCallbacks.remove(purchase.sku)
purchaseCallback?.onError(error.toQonversionError())
}
} else {
purchasingCallbacks.values.forEach {
it.onError(error.toQonversionError())
}
purchasingCallbacks.clear()
}
}
// Private functions
private fun processRestore(
purchaseHistoryRecords: List<PurchaseHistory>,
@Suppress("DEPRECATION") loadedSkuDetails: Map<String, SkuDetails>
) {
purchaseHistoryRecords.forEach { purchaseHistory ->
val skuDetails = loadedSkuDetails[purchaseHistory.historyRecord.sku]
purchaseHistory.skuDetails = skuDetails
}
repository.restore(
installDate,
purchaseHistoryRecords,
object : QonversionLaunchCallback {
override fun onSuccess(launchResult: QLaunchResult) {
updateLaunchResult(launchResult)
executeRestoreBlocksOnSuccess(launchResult.permissions.toEntitlementsMap())
}
override fun onError(error: QonversionError, httpCode: Int?) {
if (shouldCalculatePermissionsLocally(error, httpCode)) {
calculateRestorePermissionsLocally(purchaseHistoryRecords, error)
} else {
executeRestoreBlocksOnError(error)
}
}
})
}
private fun calculateRestorePermissionsLocally(
purchaseHistoryRecords: List<PurchaseHistory>,
restoreError: QonversionError
) {
val launchResult = launchResultCache.getLaunchResult() ?: run {
failLocallyGrantingRestorePermissionsWithError(
launchError ?: QonversionError(QonversionErrorCode.LaunchError)
)
return
}
launchResultCache.productPermissions?.let {
if (launchResult.products.values.all { product -> product.skuDetail == null }) {
addSkuDetailForProducts(launchResult.products.values)
}
val permissions = grantPermissionsAfterFailedRestore(
purchaseHistoryRecords,
launchResult.products.values,
it
)
executeRestoreBlocksOnSuccess(permissions.toEntitlementsMap())
} ?: failLocallyGrantingRestorePermissionsWithError(restoreError)
}
private fun calculatePurchasePermissionsLocally(
purchase: Purchase,
purchaseCallback: QonversionEntitlementsCallback?,
purchaseError: QonversionError
) {
val launchResult = launchResultCache.getLaunchResult() ?: run {
failLocallyGrantingPurchasePermissionsWithError(
purchaseCallback,
launchError ?: QonversionError(QonversionErrorCode.LaunchError)
)
return
}
launchResultCache.productPermissions?.let {
if (launchResult.products.values.all { product -> product.skuDetail == null }) {
addSkuDetailForProducts(launchResult.products.values)
}
val purchasedProduct = launchResult.products.values.find { product ->
product.skuDetail?.sku == purchase.sku
} ?: run {
failLocallyGrantingPurchasePermissionsWithError(purchaseCallback, purchaseError)
return
}
val permissions = grantPermissionsAfterFailedPurchaseTracking(
purchase,
purchasedProduct,
it
)
purchaseCallback?.onSuccess(permissions.toEntitlementsMap())
} ?: failLocallyGrantingPurchasePermissionsWithError(purchaseCallback, purchaseError)
}
private fun failLocallyGrantingPurchasePermissionsWithError(
callback: QonversionEntitlementsCallback?,
error: QonversionError
) {
launchResultCache.clearPermissionsCache()
callback?.onError(error)
}
private fun failLocallyGrantingRestorePermissionsWithError(
error: QonversionError
) {
launchResultCache.clearPermissionsCache()
executeRestoreBlocksOnError(error)
}
private fun grantPermissionsAfterFailedPurchaseTracking(
purchase: Purchase,
purchasedProduct: QProduct,
productPermissions: Map<String, List<String>>
): Map<String, QPermission> {
val newPermissions = productPermissions[purchasedProduct.qonversionID]?.mapNotNull {
createPermission(it, purchase.purchaseTime, purchasedProduct)
} ?: emptyList()
return mergeManuallyCreatedPermissions(newPermissions)
}
private fun grantPermissionsAfterFailedRestore(
historyRecords: List<PurchaseHistory>,
products: Collection<QProduct>,
productPermissions: Map<String, List<String>>
): Map<String, QPermission> {
val newPermissions = historyRecords
.filter { it.skuDetails != null }
.mapNotNull { record ->
val product = products.find { it.skuDetail?.sku === record.skuDetails?.sku }
product?.let {
productPermissions[product.qonversionID]?.map {
createPermission(it, record.historyRecord.purchaseTime, product)
}
}
}
.flatten()
.filterNotNull()
return mergeManuallyCreatedPermissions(newPermissions)
}
private fun createPermission(
id: String,
purchaseTime: Long,
purchasedProduct: QProduct
): QPermission? {
val purchaseDurationInDays = GoogleBillingPeriodConverter.convertPeriodToDays(
purchasedProduct.skuDetail?.subscriptionPeriod
)
val expirationDate = purchaseDurationInDays?.let { Date(purchaseTime + it.daysToMs) }
return if (expirationDate == null || Date() < expirationDate) {
return QPermission(
id,
purchasedProduct.qonversionID,
QProductRenewState.Unknown,
Date(purchaseTime),
expirationDate,
QEntitlementSource.PlayStore,
1
)
} else null
}
private fun mergeManuallyCreatedPermissions(
newPermissions: List<QPermission>
): Map<String, QPermission> {
val existingPermissions = launchResultCache.getActualPermissions() ?: emptyMap()
val resultPermissions = existingPermissions.toMutableMap()
newPermissions.forEach { newPermission ->
val id = newPermission.permissionID
resultPermissions[id] = choosePermissionToSave(resultPermissions[id], newPermission)
}
launchResultCache.updatePermissions(resultPermissions)
return resultPermissions
}
private fun choosePermissionToSave(
existingPermission: QPermission?,
localCreatedPermission: QPermission
): QPermission {
existingPermission ?: return localCreatedPermission
// If expiration date is null then it's permanent permissions and thus should take precedence over expiring one.
val newPermissionExpirationTime =
localCreatedPermission.expirationDate?.time ?: Long.MAX_VALUE
val existingPermissionExpirationTime =
existingPermission.expirationDate?.time ?: Long.MAX_VALUE
val doesNewOneExpireLater =
newPermissionExpirationTime > existingPermissionExpirationTime
// replace if new permission is active and expires later
return if (!existingPermission.isActive() || doesNewOneExpireLater) {
localCreatedPermission
} else {
existingPermission
}
}
private fun processPendingInitIfAvailable() {
pendingInitRequestData?.let {
processInit(it)
pendingInitRequestData = null
}
}
private fun processInit(initRequestData: InitRequestData) {
if (appStateProvider.appState.isBackground()) {
pendingInitRequestData = initRequestData
return
}
repository.init(initRequestData)
}
private fun continueLaunchWithPurchasesInfo(
callback: QonversionLaunchCallback?
) {
billingService.queryPurchases(
onQueryCompleted = { purchases ->
if (purchases.isEmpty()) {
val initRequestData =
InitRequestData(installDate, advertisingID, callback = callback)
processInit(initRequestData)
return@queryPurchases
}
val completedPurchases =
purchases.filter { it.purchaseState == Purchase.PurchaseState.PURCHASED }
billingService.getSkuDetailsFromPurchases(
completedPurchases,
onCompleted = { skuDetails ->
val skuDetailsMap = skuDetails.associateBy { it.sku }
val purchasesInfo =
converter.convertPurchases(skuDetailsMap, completedPurchases)
val handledPurchasesCallback =
getWrappedPurchasesCallback(completedPurchases, callback)
val initRequestData = InitRequestData(
installDate,
advertisingID,
purchasesInfo,
handledPurchasesCallback
)
processInit(initRequestData)
},
onFailed = {
val initRequestData =
InitRequestData(installDate, advertisingID, callback = callback)
processInit(initRequestData)
})
},
onQueryFailed = {
val initRequestData =
InitRequestData(installDate, advertisingID, callback = callback)
processInit(initRequestData)
})
}
private fun getWrappedPurchasesCallback(
trackingPurchases: List<Purchase>,
outerCallback: QonversionLaunchCallback?
): QonversionLaunchCallback {
return object : QonversionLaunchCallback {
override fun onSuccess(launchResult: QLaunchResult) {
handledPurchasesCache.saveHandledPurchases(trackingPurchases)
outerCallback?.onSuccess(launchResult)
}
override fun onError(error: QonversionError, httpCode: Int?) {
outerCallback?.onError(error, httpCode)
}
}
}
private fun getLaunchCallback(callback: QonversionLaunchCallback?): QonversionLaunchCallback {
return object : QonversionLaunchCallback {
override fun onSuccess(launchResult: QLaunchResult) {
updateLaunchResult(launchResult)
launchError = null
handlePendingRequests()
loadStoreProductsIfPossible()
handleCachedPurchases()
callback?.onSuccess(launchResult)
}
override fun onError(error: QonversionError, httpCode: Int?) {
launchError = error
handlePendingRequests(error)
loadStoreProductsIfPossible()
callback?.onError(error, httpCode)
}
}
}
fun logout() {
pendingPartnersIdentityId = null
val isLogoutNeeded = identityManager.logoutIfNeeded()
if (isLogoutNeeded) {
remoteConfigManager.onUserUpdate()
launchResultCache.clearPermissionsCache()
unhandledLogoutAvailable = true
val userID = userInfoService.obtainUserID()
internalConfig.uid = userID
}
}
fun getUserInfo(callback: QonversionUserCallback) {
val user = QUser(internalConfig.uid, identityManager.currentPartnersIdentityId)
callback.onSuccess(user)
}
fun setEntitlementsUpdateListener(entitlementsUpdateListener: QEntitlementsUpdateListener) {
internalConfig.entitlementsUpdateListener = entitlementsUpdateListener
}
private fun handleLogout() {
unhandledLogoutAvailable = false
launch()
}
private fun updateLaunchResult(launchResult: QLaunchResult) {
launchResultCache.save(launchResult)
}
private fun loadStoreProductsIfPossible(
@Suppress("DEPRECATION") onLoadCompleted: ((products: List<SkuDetails>) -> Unit)? = null,
onLoadFailed: ((error: QonversionError) -> Unit)? = null
) {
when (loadProductsState) {
Loading -> return
Loaded -> {
executeProductsBlocks()
onLoadCompleted?.let { skuDetails.values.toList() }
return
}
else -> Unit
}
val launchResult = launchResultCache.getLaunchResult() ?: run {
loadProductsState = Failed
val error = launchError ?: QonversionError(QonversionErrorCode.LaunchError)
executeProductsBlocks(error)
onLoadFailed?.let { it(error) }
return
}
val productStoreIds = launchResult.products.values.mapNotNull {
it.storeID
}.toSet()
if (productStoreIds.isNotEmpty()) {
loadProductsState = Loading
billingService.loadProducts(productStoreIds,
onLoadCompleted = { details ->
val skuDetailsMap = details.associateBy { it.sku }
skuDetails = skuDetailsMap.toMutableMap()
loadProductsState = Loaded
executeProductsBlocks()
onLoadCompleted?.let { it(details) }
},
onLoadFailed = { error ->
loadProductsState = Failed
executeProductsBlocks(error.toQonversionError())
onLoadFailed?.let { it(error.toQonversionError()) }
})
} else {
executeProductsBlocks()
@Suppress("DEPRECATION")
onLoadCompleted?.let { listOf<SkuDetails>() }
}
}
/**
* Executes identity changing operations (identify or logout) if pending requests exist.
* Else executes awaiting entitlements requests.
*/
private fun handlePendingRequests(lastError: QonversionError? = null) {
if (!isLaunchingFinished || isRestoreInProgress || processingPartnersIdentityId != null) {
return
}
val pendingIdentityId = pendingPartnersIdentityId
if (!pendingIdentityId.isNullOrEmpty()) {
identify(pendingIdentityId)
} else if (unhandledLogoutAvailable) {
handleLogout()
} else {
executeEntitlementsBlock(lastError)
remoteConfigManager.handlePendingRequests()
}
}
private fun handleCachedPurchases() {
val cachedPurchases = purchasesCache.loadPurchases()
cachedPurchases.forEach { purchase ->
repository.purchase(installDate, purchase, null, object :
QonversionLaunchCallback {
override fun onSuccess(launchResult: QLaunchResult) {
updateLaunchResult(launchResult)
purchasesCache.clearPurchase(purchase)
}
override fun onError(error: QonversionError, httpCode: Int?) {}
})
}
}
@Synchronized
private fun executeProductsBlocks(loadStoreProductsError: QonversionError? = null) {
if (productsCallbacks.isEmpty()) {
return
}
val callbacks = productsCallbacks.toList()
productsCallbacks.clear()
loadStoreProductsError?.let {
handleFailureProducts(callbacks, it)
return
}
val launchResult = launchResultCache.getLaunchResult() ?: run {
handleFailureProducts(callbacks, launchError)
return
}
addSkuDetailForProducts(launchResult.products.values)
callbacks.forEach {
it.onSuccess(launchResult.products)
}
}
@Synchronized
private fun executeEntitlementsBlock(error: QonversionError? = null) {
if (entitlementCallbacks.isEmpty()) {
return
}
val callbacks = entitlementCallbacks.toList()
entitlementCallbacks.clear()
error?.let {
callbacks.forEach { it.onError(error) }
} ?: run {
preparePermissionsResult(
{ permissions ->
callbacks.forEach {
it.onSuccess(permissions.toEntitlementsMap())
}
},
{ error ->
callbacks.forEach {
it.onError(error)
}
})
}
}
private fun executeRestoreBlocksOnSuccess(entitlements: Map<String, QEntitlement>) {
val callbacks = restoreCallbacks.toList()
restoreCallbacks.clear()
isRestoreInProgress = false
callbacks.forEach { callback -> callback.onSuccess(entitlements) }
handlePendingRequests()
}
private fun executeRestoreBlocksOnError(error: QonversionError) {
val callbacks = restoreCallbacks.toList()
restoreCallbacks.clear()
isRestoreInProgress = false
callbacks.forEach { callback -> callback.onError(error) }
handlePendingRequests(error)
}
private fun retryLaunchForProducts(onCompleted: () -> Unit) {
launchResultCache.sessionLaunchResult?.let {
handleLoadStateForProducts(onCompleted)
} ?: retryLaunch(
onSuccess = {
handleLoadStateForProducts(onCompleted)
},
onError = {
handleLoadStateForProducts(onCompleted)
})
}
private fun retryLaunch(
onSuccess: (QLaunchResult) -> Unit,
onError: (QonversionError) -> Unit
) {
launch(object : QonversionLaunchCallback {
override fun onSuccess(launchResult: QLaunchResult) = onSuccess(launchResult)
override fun onError(error: QonversionError, httpCode: Int?) = onError(error)
})
}
private fun handleLoadStateForProducts(onCompleted: () -> Unit) {
when (loadProductsState) {
Loaded -> onCompleted()
Failed -> loadStoreProductsIfPossible()
else -> Unit
}
}
private fun handleFailureProducts(
callbacks: List<QonversionProductsCallback>,
error: QonversionError?
) {
callbacks.forEach {
it.onError(error ?: QonversionError(QonversionErrorCode.LaunchError))
}
}
private fun preparePermissionsResult(
onSuccess: (permissions: Map<String, QPermission>) -> Unit,
onError: (QonversionError) -> Unit
) {
if (launchError != null || unhandledLogoutAvailable) {
retryLaunch(
onSuccess = { launchResult ->
onSuccess(launchResult.permissions)
unhandledLogoutAvailable = false
},
onError = { error ->
val cachedPermissions = launchResultCache.getActualPermissions()
cachedPermissions?.let {
onSuccess(it)
} ?: onError(error)
})
} else {
val permissions = launchResultCache.getActualPermissions() ?: emptyMap()
onSuccess(permissions)
}
}
private fun handlePendingPurchases() {
if (!isLaunchingFinished) return
billingService.queryPurchases(
onQueryCompleted = { purchases ->
handlePurchases(purchases)
},
onQueryFailed = {}
)
}
private fun handlePurchases(purchases: List<Purchase>) {
consumer.consumePurchases(purchases, skuDetails)
purchases.forEach { purchase ->
val purchaseCallback = purchasingCallbacks[purchase.sku]
purchasingCallbacks.remove(purchase.sku)
when (purchase.purchaseState) {
Purchase.PurchaseState.PENDING -> {
purchaseCallback?.onError(QonversionError(QonversionErrorCode.PurchasePending))
return@forEach
}
Purchase.PurchaseState.UNSPECIFIED_STATE -> {
purchaseCallback?.onError(QonversionError(QonversionErrorCode.PurchaseUnspecified))
return@forEach
}
}
if (!handledPurchasesCache.shouldHandlePurchase(purchase)) return@forEach
val skuDetail = skuDetails[purchase.sku] ?: return@forEach
val purchaseInfo = Pair.create(skuDetail, purchase)
purchase(purchaseInfo, object : QonversionLaunchCallback {
override fun onSuccess(launchResult: QLaunchResult) {
updateLaunchResult(launchResult)
val entitlements = launchResult.permissions.toEntitlementsMap()
purchaseCallback?.onSuccess(entitlements) ?: run {
internalConfig.entitlementsUpdateListener?.onEntitlementsUpdated(entitlements)
}
handledPurchasesCache.saveHandledPurchase(purchase)
}
override fun onError(error: QonversionError, httpCode: Int?) {
if (shouldCalculatePermissionsLocally(error, httpCode)) {
calculatePurchasePermissionsLocally(
purchase,
purchaseCallback,
error
)
} else {
purchaseCallback?.onError(error)
}
}
})
}
}
private fun purchase(
@Suppress("DEPRECATION") purchaseInfo: Pair<SkuDetails, Purchase>,
callback: QonversionLaunchCallback
) {
val sku = purchaseInfo.first.sku
val product: QProduct? = launchResultCache.getLaunchResult()?.products?.values?.find { it.storeID == sku }
val purchase = converter.convertPurchase(purchaseInfo) ?: run {
callback.onError(
QonversionError(
QonversionErrorCode.ProductUnavailable,
"There is no SKU for the qonversion product ${product?.qonversionID ?: ""}"
),
null
)
return
}
repository.purchase(installDate, purchase, product?.qonversionID, callback)
}
private fun shouldCalculatePermissionsLocally(error: QonversionError, httpCode: Int?): Boolean {
return !internalConfig.isAnalyticsMode && (
error.code == QonversionErrorCode.NetworkConnectionFailed ||
httpCode?.isInternalServerError() == true
)
}
}
| 7
|
Kotlin
|
21
| 117
|
e0f90e56a4a9679afce6e91d724b1ffda13b8b65
| 41,893
|
android-sdk
|
MIT License
|
src/main/kotlin/at/searles/parsing/lexer/regexp/Text.kt
|
searles
| 837,100,761
| false
|
{"Kotlin": 63697}
|
package at.searles.parsing.lexer.regexp
import at.searles.parsing.lexer.Automaton
class Text(private val text: String): Regexp {
override fun <A> toAutomaton(): Automaton<A> {
return Automaton.ofString(text)
}
override fun toString(): String {
return text
}
}
| 0
|
Kotlin
|
0
| 0
|
99ddf66881d529a89bd95671956c620e425d7ada
| 294
|
parsingKotlin
|
MIT License
|
app/src/main/java/com/droid/newsapiclient/presentation/di/AdapterModule.kt
|
peter-wachira
| 401,620,074
| false
| null |
package com.droid.newsapiclient.presentation.di
import com.droid.newsapiclient.presentation.adapter.NewsAdapter
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class AdapterModule {
@Singleton
@Provides
fun provideNewsAdapter(): NewsAdapter {
return NewsAdapter()
}
}
| 1
|
Kotlin
|
0
| 4
|
5be82560acd890700af836f318e56be53735ac42
| 441
|
PixelNewsApp
|
The Unlicense
|
appupdatewrapper/src/test/java/com/motorro/appupdatewrapper/testUtils.kt
|
motorro
| 198,185,007
| false
| null |
/*
* Copyright 2019 <NAME> (motorro).
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package com.motorro.appupdatewrapper
import android.os.Handler
import android.os.Looper.getMainLooper
import com.google.android.play.core.appupdate.AppUpdateInfo
import com.google.android.play.core.appupdate.testing.FakeAppUpdateManager
import com.google.android.gms.tasks.OnFailureListener
import com.google.android.gms.tasks.OnSuccessListener
import com.google.android.gms.tasks.Task
import com.nhaarman.mockitokotlin2.spy
import org.robolectric.annotation.LooperMode
import java.util.*
/**
* Detects Windows OS
*/
fun isRunningWindows() = true == System.getProperty("os.name")?.lowercase(Locale.US)?.contains("windows")
/**
* A task that may [succeed] or [fail] on demand
*/
abstract class TestTask<T>: Task<T>() {
private lateinit var onSuccessListener: OnSuccessListener<in T>
private lateinit var onFailureListener: OnFailureListener
override fun addOnSuccessListener(p0: OnSuccessListener<in T>): Task<T> {
onSuccessListener = p0
return this
}
override fun addOnFailureListener(p0: OnFailureListener): Task<T> {
onFailureListener = p0
return this
}
/**
* Calls success listener with [result]
*/
fun succeed(result: T?) {
onSuccessListener.onSuccess(result)
}
/**
* Calls failure listener with [error]
*/
fun fail(error: Exception) {
onFailureListener.onFailure(error)
}
}
/**
* A task to check update info
*/
abstract class TestUpdateInfoTask: TestTask<AppUpdateInfo>()
/**
* A task to install update
*/
abstract class TestInstallTask: TestTask<Void>()
/**
* Creates a test info task
*/
fun createTestInfoTask(): TestUpdateInfoTask = spy()
/**
* Creates a test install task
*/
fun createTestInstallTask(): TestInstallTask = spy()
/**
* Requests update info and executes [block] when returned
* Requires `@LooperMode(LooperMode.Mode.PAUSED)`
* @see LooperMode
*/
inline fun FakeAppUpdateManager.withInfo(crossinline block: FakeAppUpdateManager.(AppUpdateInfo) -> Unit) {
appUpdateInfo
.addOnSuccessListener {
Handler(getMainLooper()).post { block(it) }
}
.addOnFailureListener { throw IllegalStateException("Unexpected update check error") }
}
| 1
| null |
2
| 35
|
53f96f89b0dace51c46f34b9912007dd261d7596
| 2,832
|
AppUpdateWrapper
|
Apache License 2.0
|
plugins/scripting/scripting-compiler/testData/compiler/constructAnnotations/TestAnnotationWithArrayLiteral.kts
|
JetBrains
| 3,432,266
| false
|
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
@file:TestAnnotation(options = ["option"])
| 181
|
Kotlin
|
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 43
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/yorick/cokotools/util/ShizukuSystemServerApi.kt
|
Yorick-Ryu
| 542,501,945
| false
| null |
package com.yorick.cokotools.util
import android.content.pm.IPackageInstaller
import android.content.pm.IPackageManager
import android.os.RemoteException
import rikka.shizuku.ShizukuBinderWrapper
import rikka.shizuku.SystemServiceHelper
object ShizukuSystemServerApi {
private val PACKAGE_MANAGER: Singleton<IPackageManager?> =
object : Singleton<IPackageManager?>() {
override fun create(): IPackageManager {
return IPackageManager.Stub.asInterface(
ShizukuBinderWrapper(
SystemServiceHelper.getSystemService("package")
)
)
}
}
@Throws(RemoteException::class)
fun getPackageInstallerByPackageManager(): IPackageInstaller {
val packageInstaller = PACKAGE_MANAGER.get()!!.packageInstaller
return IPackageInstaller.Stub.asInterface(ShizukuBinderWrapper(packageInstaller.asBinder()))
}
}
| 1
| null |
2
| 3
|
6e2b0f838546aa940211287d01aa2f1e8da8b7ce
| 955
|
CokoTools
|
Apache License 2.0
|
services/spring-graphql-redis/src/main/kotlin/micro/apps/service/domain/user/models.kt
|
xmlking
| 236,108,779
| false
| null |
package micro.apps.service
import com.redis.om.spring.annotations.Bloom
import com.redis.om.spring.annotations.Indexed
import com.redis.om.spring.annotations.Searchable
import org.springframework.data.annotation.Id
import org.springframework.data.annotation.Reference
import org.springframework.data.redis.core.RedisHash
@RedisHash
data class Role(
@Id
var id: String?,
@Indexed
var roleName: String?
)
@RedisHash
data class User(
@Id
val id: String?,
@Indexed
val firstName: String,
@Indexed
val middleName: String?,
@Searchable
val lastName: String,
@Indexed
@Bloom(name = "bf_user_email", capacity = 100000, errorRate = 0.001)
var email: String,
// HINT: Reference fields should be marked as nullable.???
@Reference
val role: Role?
)
| 9
| null |
11
| 48
|
135c0f6b8ccfe17121a367bbfdd8024c77ea3c51
| 812
|
micro-apps
|
MIT License
|
app/src/main/java/com/jensencelestial/ghiblibrary/android/ui/vehicle/VehicleFragment.kt
|
jensencelestial
| 293,452,579
| false
| null |
package com.jensencelestial.ghiblibrary.android.ui.vehicle
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.navArgs
import coil.load
import coil.transform.RoundedCornersTransformation
import com.jensencelestial.ghiblibrary.android.R
import com.jensencelestial.ghiblibrary.android.data.model.Vehicle
import com.jensencelestial.ghiblibrary.android.databinding.FragmentVehicleBinding
import com.jensencelestial.ghiblibrary.android.ui.UIState
import com.jensencelestial.ghiblibrary.android.viewmodel.VehicleViewModel
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class VehicleFragment : Fragment() {
private val vehicleViewModel: VehicleViewModel by viewModels()
private var _binding: FragmentVehicleBinding? = null
private val binding get() = _binding!!
private val args: VehicleFragmentArgs by navArgs()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentVehicleBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initViewEvents()
initObservers()
vehicleViewModel.getVehicle(args.vehicleId)
}
private fun initViewEvents() {
binding.swltVehicle.setOnRefreshListener {
vehicleViewModel.getVehicle(args.vehicleId)
}
}
private fun initObservers() {
vehicleViewModel.vehicle.observe(this.viewLifecycleOwner, VehicleObserver())
}
private fun setVehicleContent(vehicle: Vehicle) {
binding.lytVehicle.tvName.text = vehicle.name
binding.lytVehicle.tvClass.text = vehicle.vehicleClass
binding.lytVehicle.tvLength.text = vehicle.length ?: getString(R.string.n_a)
binding.lytVehicle.ivThumbnail.load(vehicle.imageUrl) {
placeholder(R.drawable.shape_image_fallback)
fallback(R.drawable.shape_image_fallback)
error(R.drawable.shape_image_fallback)
crossfade(true)
transformations(RoundedCornersTransformation(4f))
}
binding.lytVehicle.tvDescription.text = vehicle.description
}
private inner class VehicleObserver : Observer<UIState<Vehicle>> {
override fun onChanged(vehicle: UIState<Vehicle>) {
when (vehicle) {
is UIState.Loading -> {
if (!binding.swltVehicle.isRefreshing) {
binding.swltVehicle.isRefreshing = true
}
}
is UIState.Success -> {
binding.swltVehicle.isRefreshing = false
setVehicleContent(vehicle.value)
}
is UIState.Failure -> {
binding.swltVehicle.isRefreshing = false
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
fcb906fcc0f834302e80d24ba646b5c9614644e4
| 3,189
|
ghiblibrary-android
|
MIT License
|
kotlin/src/src/main/java/com/techlabcamp/neuronet/presenterImpl/CouponPresenterImpl.kt
|
dimske-sys
| 610,048,630
| false
| null |
package com.techlabcamp.neuronet.presenterImpl
import com.techlabcamp.neuronet.manager.net.ApiService
import com.techlabcamp.neuronet.manager.net.CustomCallback
import com.techlabcamp.neuronet.manager.net.RetryListener
import com.techlabcamp.neuronet.model.Coupon
import com.techlabcamp.neuronet.model.CouponValidation
import com.techlabcamp.neuronet.model.Data
import com.techlabcamp.neuronet.presenter.Presenter
import com.techlabcamp.neuronet.ui.widget.CouponDialog
import retrofit2.Call
import retrofit2.Response
class CouponPresenterImpl(private val dialog: CouponDialog) : Presenter.CouponPresenter {
override fun validateCoupon(coupon: Coupon) {
ApiService.apiClient!!.validateCoupon(coupon)
.enqueue(object : CustomCallback<Data<CouponValidation>> {
override fun onStateChanged(): RetryListener? {
return RetryListener {
validateCoupon(coupon)
}
}
override fun onResponse(
call: Call<Data<CouponValidation>>,
response: Response<Data<CouponValidation>>
) {
if (response.body() != null) {
dialog.onCouponValidated(response.body()!!)
}
}
})
}
}
| 0
|
Kotlin
|
0
| 0
|
0f4cc0534a3c77a8edfb0fa043fb2ed7e2707250
| 1,345
|
neuronet
|
Apache License 2.0
|
src/maia/util/property/PropertyWithMemory.kt
|
waikato-maia
| 387,324,750
| false
|
{"Kotlin": 249102}
|
package maia.util.property
import maia.util.datastructure.WeakIdentityHashMap
import java.util.*
import kotlin.NoSuchElementException
import kotlin.properties.ReadOnlyProperty
import kotlin.properties.ReadWriteProperty
/**
* Class which provides memory for objects inside a property with memory.
*
* @param perObject
* Whether equal objects should not share memory.
* @param R
* The type of object which owns the memory.
* @param M
* The type of memory held for the objects.
*/
class PropertyMemory<in R : Any, M>(perObject : Boolean) {
/** A weakly-referenced map from object to the memory for the object. */
private val memory : MutableMap<R, M> = if (perObject) WeakIdentityHashMap() else WeakHashMap()
operator fun contains(accessor : R) : Boolean {
return accessor in memory
}
operator fun get(accessor : R) : M {
// Make sure the accessor has memory allocated
if (accessor !in memory) throw NoSuchElementException("$accessor has no allocated memory")
@Suppress("UNCHECKED_CAST")
return memory[accessor] as M
}
operator fun set(accessor : R, value : M) {
memory[accessor] = value
}
operator fun minusAssign(accessor : R) {
memory.remove(accessor)
}
}
/**
* Base class for read-only properties which require memory for their accessors.
*
* @param perObject
* Whether equal objects should not share memory.
* @param R
* The type of object which owns the delegated property.
* @param T
* The type of the property value.
* @param M
* The type of memory held for the objects.
*/
abstract class ReadOnlyPropertyWithMemory<in R : Any, out T, M>(
perObject : Boolean
) : ReadOnlyProperty<R, T> {
/** The memory for the accessors. */
protected val memory = PropertyMemory<R, M>(perObject)
}
/**
* Base class for read-write properties which require memory for their accessors.
*
* @param perObject
* Whether equal objects should not share memory.
* @param R
* The type of object which owns the delegated property.
* @param T
* The type of the property value.
* @param M
* The type of memory held for the objects.
*/
abstract class ReadWritePropertyWithMemory<in R : Any, T, M>(
perObject : Boolean
) : ReadWriteProperty<R, T> {
/** The memory for the accessors. */
protected val memory = PropertyMemory<R, M>(perObject)
}
| 0
|
Kotlin
|
0
| 0
|
b8ca03697de549dad17dbd7c3860d44247e2e973
| 2,490
|
maia-util
|
Apache License 2.0
|
app/src/main/java/com/example/archivevn/view/NavigationFragment.kt
|
JoDaC
| 594,124,810
| false
| null |
package com.example.archivevn.view
import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.example.archivevn.R
import com.example.archivevn.databinding.ActivityMainBinding
import com.example.archivevn.databinding.FragmentNavigationBinding
import com.example.archivevn.viewmodel.MainViewModel
class NavigationFragment() : Fragment() {
private lateinit var binding: FragmentNavigationBinding
private lateinit var activityMainBinding: ActivityMainBinding
private lateinit var mainViewModel: MainViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
mainViewModel = ViewModelProvider(requireActivity())[MainViewModel::class.java]
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_navigation, container, false)
binding.mainViewModel = mainViewModel
// Get the parent activity's URL EditText
activityMainBinding = DataBindingUtil.inflate(inflater, R.layout.activity_main, container, false)
val urlEditText = activityMainBinding.urlEditText
lineAnimationTheme()
binding.goButton.goButtonAnimation.setOnClickListener {
val url = urlEditText.text.toString()
mainViewModel.onGoButtonClicked(url)
}
binding.readerButton.setOnClickListener {
val url = urlEditText.text.toString()
mainViewModel.onReaderButtonClicked(url)
}
mainViewModel.isPasteButtonEnabled.observe(viewLifecycleOwner) { isEnabled ->
binding.pasteButton.isEnabled = isEnabled
}
return binding.root
}
private fun lineAnimationTheme() {
val nightLine = binding.horizontalLineViewNight
val currentNightMode = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK
if (currentNightMode == Configuration.UI_MODE_NIGHT_YES) {
nightLine.visibility = View.VISIBLE
} else {
nightLine.visibility = View.GONE
}
}
}
| 5
|
Kotlin
|
0
| 5
|
6836f0a843095c1f8b90a0ce9db235d3b76f46d2
| 2,316
|
Article-Companion
|
Apache License 2.0
|
app/src/main/java/com/criticalay/neer/ui/theme/Color.kt
|
criticalAY
| 757,950,703
| false
|
{"Kotlin": 293492}
|
/*
* Copyright (c) 2024 <NAME> <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.criticalay.neer.ui.theme
import androidx.compose.ui.graphics.Color
// custom color
val Light_blue = Color(0xFFA7C7E7)
val Progress_Blue = Color(0xFF00BFFF)
val BluePrimary = Color(0xFF00BFFF)
val BlueSecondary = Color(0xFF007399)
val BlueTertiary = Color(0xFF80DFFF)
val DarkBluePrimary= Color(0xFF0099CC)
val DarkBlueTertiary =Color(0xFF4695AF)
val DarkBlueSecondary = Color(0xFF4E6472)
| 7
|
Kotlin
|
3
| 26
|
aa46640b0660ea6bda41e64ac35408467181d26e
| 1,010
|
Neer
|
Apache License 2.0
|
PracticaRecyclerViewBindingKotlin/app/src/main/java/edu/unicauca/aplimovil/practicarecyclerviewapp/adapter/UserBindingAdapter.kt
|
cfigmart
| 491,656,397
| false
| null |
package edu.unicauca.aplimovil.practicarecyclerviewapp.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import edu.unicauca.aplimovil.practicarecyclerviewapp.R
import edu.unicauca.aplimovil.practicarecyclerviewapp.databinding.LayoutUserItemBinding
import edu.unicauca.aplimovil.practicarecyclerviewapp.model.User
class UserBindingAdapter(val userList: List<User>, val ctx: Context)
: RecyclerView.Adapter<UserBindingAdapter.UserViewHoder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHoder {
var bindingUsuario: LayoutUserItemBinding = DataBindingUtil.inflate(
LayoutInflater.from(parent.context), R.layout.layout_user_item, parent, false)
return UserViewHoder(bindingUsuario)
}
override fun onBindViewHolder(holder: UserViewHoder, position: Int) {
var user: User = userList[position]
holder.userItemBinding.user = user
//holder.userItemBinding.setUser(user)
}
override fun getItemCount(): Int = userList.size
class UserViewHoder(val userItemBinding: LayoutUserItemBinding)
: RecyclerView.ViewHolder(userItemBinding.root) {
}
}
| 0
|
Kotlin
|
0
| 0
|
6647b2dd12e0098a62f024e42b5adf900de218af
| 1,308
|
aplimovil2022
|
Apache License 2.0
|
app/src/test/java/me/hufman/androidautoidrive/calendar/UpcomingDestinationTest.kt
|
BimmerGestalt
| 164,273,785
| false
| null |
package me.hufman.androidautoidrive.calendar
import android.location.Address
import org.mockito.kotlin.*
import me.hufman.androidautoidrive.carapp.calendar.UpcomingDestination
import me.hufman.androidautoidrive.maps.LatLong
import me.hufman.androidautoidrive.carapp.navigation.AddressSearcher
import me.hufman.androidautoidrive.carapp.navigation.NavigationTrigger
import org.junit.Test
import java.util.*
class UpcomingDestinationTest {
var calendarEvents = listOf(
CalendarEvent("A", makeCalendar(2021, 11, 10, 9, 15), makeCalendar(2021, 11, 10, 16, 45), "Place1", "", 0),
CalendarEvent("B", makeCalendar(2021, 11, 11, 9, 15), makeCalendar(2021, 11, 11, 16, 45), "Place2", "", 0),
CalendarEvent("C", makeCalendar(2021, 11, 11, 18, 0), makeCalendar(2021, 11, 11, 20, 0), "Place3", "", 0),
CalendarEvent("Holiday", makeCalendar(2021, 11, 25, 0, 0), makeCalendar(2021, 11, 26, 0, 0), "Place4", "", 0),
CalendarEvent("Holiday", makeCalendar(2021, 12, 25, 0, 0), makeCalendar(2021, 12, 26, 0, 0), "Place5", "", 0),
CalendarEvent("Holiday", makeCalendar(2022, 1, 1, 0, 0), makeCalendar(2022, 1, 2, 0, 0), "Place6", "", 0),
)
val calendarProvider = mock<CalendarProvider> {
on {hasPermission()} doReturn true
on {getNow()} doAnswer { makeCalendar(2021, 11, 11, 9, 0) }
on {getEvents(any(), any(), isNull())} doAnswer { inv -> calendarEvents.filter { it.start[Calendar.YEAR] == inv.arguments[0] && it.start[Calendar.MONTH] + 1 == inv.arguments[1] } }
on {getEvents(any(), any(), isNotNull())} doAnswer { inv -> calendarEvents.filter { it.start[Calendar.YEAR] == inv.arguments[0] && it.start[Calendar.MONTH] + 1 == inv.arguments[1] && it.start[Calendar.DAY_OF_MONTH] == inv.arguments[2] } }
}
val addressSearcher = mock<AddressSearcher> {
on {search(any())} doReturn null
}
val navigationTrigger = mock<NavigationTrigger>()
val currentLatLong = LatLong(37.373022, -121.994893)
val closeLatLong = LatLong(37.373347, -121.994520) // too close to navigation to
val farLatLong = LatLong(37.353052, -121.976596)
val otherLatLong = LatLong(37.352048, -121.960684)
val closeAddress = mock<Address> {
on {latitude} doReturn closeLatLong.latitude
on {longitude} doReturn closeLatLong.longitude
}
val farAddress = mock<Address> {
on {latitude} doReturn farLatLong.latitude
on {longitude} doReturn farLatLong.longitude
}
val otherAddress = mock<Address> {
on {latitude} doReturn otherLatLong.latitude
on {longitude} doReturn otherLatLong.longitude
}
val upcomingDestination = UpcomingDestination(calendarProvider, addressSearcher, navigationTrigger)
private fun makeCalendar(year: Int, month: Int, day: Int, hour: Int = 0, minute: Int = 0): Calendar {
return Calendar.getInstance().also {
it[Calendar.YEAR] = year
it[Calendar.MONTH] = month - 1
it[Calendar.DAY_OF_MONTH] = day
it[Calendar.HOUR_OF_DAY] = hour
it[Calendar.MINUTE] = minute
it[Calendar.SECOND] = 0
it[Calendar.MILLISECOND] = 0
}
}
@Test
fun testEmptyNavigation() {
whenever(calendarProvider.getEvents(any(), any(), isNotNull())) doAnswer { emptyList() }
upcomingDestination.navigateUpcomingDestination(currentLatLong)
verify(calendarProvider).getEvents(2021, 11, 11)
verifyNoInteractions(addressSearcher)
verifyNoInteractions(navigationTrigger)
}
@Test
fun testStartNavigation() {
calendarEvents = listOf(
CalendarEvent("B", makeCalendar(2021, 11, 11, 9, 45), makeCalendar(2021, 11, 11, 16, 45), "Place3", "", 0),
CalendarEvent("B", makeCalendar(2021, 11, 11, 9, 15), makeCalendar(2021, 11, 11, 16, 45), "Place2", "", 0),
)
whenever(addressSearcher.search("Place2")) doReturn farAddress
whenever(addressSearcher.search("Place3")) doReturn otherAddress
upcomingDestination.navigateUpcomingDestination(currentLatLong)
verify(calendarProvider).getEvents(2021, 11, 11)
verify(addressSearcher).search("Place2")
verifyNoMoreInteractions(addressSearcher)
verify(navigationTrigger).triggerNavigation(farAddress)
}
@Test
fun testStartNavigationSkippingMissingAddress() {
calendarEvents = listOf(
CalendarEvent("B", makeCalendar(2021, 11, 11, 9, 45), makeCalendar(2021, 11, 11, 16, 45), "Place3", "", 0),
CalendarEvent("B", makeCalendar(2021, 11, 11, 9, 15), makeCalendar(2021, 11, 11, 16, 45), "Place2", "", 0),
)
whenever(addressSearcher.search("Place2")) doReturn null
whenever(addressSearcher.search("Place3")) doReturn farAddress
upcomingDestination.navigateUpcomingDestination(currentLatLong)
verify(calendarProvider).getEvents(2021, 11, 11)
verify(addressSearcher).search("Place2")
verify(addressSearcher).search("Place3")
verify(navigationTrigger).triggerNavigation(farAddress)
}
@Test
fun testSkipTooClose() {
calendarEvents = listOf(
CalendarEvent("B", makeCalendar(2021, 11, 11, 9, 15), makeCalendar(2021, 11, 11, 16, 45), "Place2", "", 0),
)
whenever(addressSearcher.search(any())) doReturn closeAddress
upcomingDestination.navigateUpcomingDestination(currentLatLong)
verify(calendarProvider).getEvents(2021, 11, 11)
verify(addressSearcher).search(calendarEvents[0].location)
verifyNoInteractions(navigationTrigger)
}
@Test
fun testSkipPrevious() {
calendarEvents = listOf(
CalendarEvent("B", makeCalendar(2021, 11, 11, 8, 15), makeCalendar(2021, 11, 11, 16, 45), "Place2", "", 0),
)
whenever(addressSearcher.search(any())) doReturn farAddress
upcomingDestination.navigateUpcomingDestination(currentLatLong)
verify(calendarProvider).getEvents(2021, 11, 11)
verifyNoInteractions(addressSearcher)
verifyNoInteractions(navigationTrigger)
}
@Test
fun testSkipTooLongAway() {
calendarEvents = listOf(
CalendarEvent("B", makeCalendar(2021, 11, 11, 10, 45), makeCalendar(2021, 11, 11, 16, 45), "Place2", "", 0),
)
whenever(addressSearcher.search(any())) doReturn farAddress
upcomingDestination.navigateUpcomingDestination(currentLatLong)
verify(calendarProvider).getEvents(2021, 11, 11)
verifyNoInteractions(addressSearcher)
verifyNoInteractions(navigationTrigger)
}
}
| 61
| null |
90
| 546
|
ea49ba17a18c353a8ba55f5040e8e4321bf14bd7
| 6,044
|
AAIdrive
|
MIT License
|
libNetwork/src/main/java/com/kanawish/socket/NetworkHelper.kt
|
kanawish
| 110,839,705
| false
| null |
package com.kanawish.socket
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import com.kanawish.robot.Command
import com.kanawish.robot.Telemetry
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.PublishSubject
import timber.log.Timber
import java.io.IOException
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.net.*
import javax.inject.Inject
import javax.inject.Singleton
const val HOST_PHONE_ADDRESS = "10.11.94.193" // [for RobotActivity] Pixel 2 Remote on ATR
//const val HOST_PHONE_ADDRESS = "192.168.43.1" // [for RobotActivity] Nexus 5 Remote on ATR
const val HOST_P2_ADDRESS = "192.168.43.60" // [for ARRemoteActivity] Pixel 2 on ATR
const val ROBOT_ADDRESS = "10.11.89.103" // Robot on ATR
const val PORT_CMD = 60123
const val PORT_TM = 60124
const val PORT_BM = 60125
fun ByteArray.toBitmap(): Bitmap {
return BitmapFactory.decodeByteArray(this, 0, this.size)
}
// NOTE: NetworkServer and NetworkClient currently don't really hold state.
// TODO: Consider only using top level functions instead of singleton.
@Singleton
class NetworkServer @Inject constructor() {
private val errorHandler = { t: Throwable -> Timber.e(t) }
fun receiveCommand(inetSocketAddress: InetSocketAddress = InetSocketAddress(PORT_CMD)): Observable<Command> {
// Server listens for clients, emits a socket object for each incoming connection.
val clientSockets = PublishSubject.create<Socket>()
val disposable = serverSocketAcceptor(inetSocketAddress).subscribe(clientSockets::onNext)
// We expect one ByteArray object, convert it to bitmap.
return clientSockets.clientSocketProcessor()
.map { (input, output) ->
val command = input.readObject() as Command
input.close()
output.close()
command
}
.doOnDispose { disposable.dispose() }
}
fun receiveTelemetry(inetSocketAddress: InetSocketAddress = InetSocketAddress(PORT_TM)): Observable<Telemetry> {
// Server listens for clients, emits a socket object for each incoming connection.
val clientSockets = PublishSubject.create<Socket>()
val disposable = serverSocketAcceptor(inetSocketAddress).subscribe(clientSockets::onNext)
// We expect one ByteArray object, convert it to bitmap.
return clientSockets.clientSocketProcessor()
.map { (input, output) ->
// Iffy, but then all this network code is iffy. ^_^
val telemetry = input.readObject() as Telemetry
Timber.d("Server received Telemetry:\nDistance:\t${telemetry.distance}\nBitmap:\t${telemetry.image.size} bytes")
input.close()
output.close()
telemetry
}
.doOnDispose { disposable.dispose() }
}
// Very quick and dirty.
fun receiveBitmaps(inetSocketAddress: InetSocketAddress = InetSocketAddress(PORT_BM)): Observable<Bitmap> {
// Server listens for clients, emits a socket object for each incoming connection.
val clientSockets = PublishSubject.create<Socket>()
val disposable = serverSocketAcceptor(inetSocketAddress).subscribe(clientSockets::onNext)
// We expect one ByteArray object, convert it to bitmap.
return clientSockets.clientSocketProcessor()
.map { (input, output) ->
val bytes = input.readObject() as ByteArray
input.close()
output.close()
BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
}
.doOnDispose { disposable.dispose() }
}
private fun serverSocketAcceptor(inetSocketAddress: InetSocketAddress): Observable<Socket> {
return Observable
.create<Socket> { e ->
var isStopped = false
try {
Timber.d("Starting server socket")
val serverSocket = ServerSocket()
serverSocket.reuseAddress = true
serverSocket.bind(inetSocketAddress)
e.setCancellable {
Timber.d("Trying to close on cancel/dispose.")
isStopped = true
try {
serverSocket.close()
} catch (e: IOException) {
Timber.e(e, "Error closing server.")
}
}
try {
while (!serverSocket.isClosed) e.onNext(serverSocket.accept())
} catch (e: Exception) {
if (isStopped) {
Timber.d("Server stopped")
} else {
Timber.e(e, "Socket accept exception caught. isStopped == $isStopped")
}
} finally {
serverSocket.close()
}
} catch (t: Exception) {
Timber.e(t, "Top level server exception caught.")
}
}
.subscribeOn(Schedulers.io())
}
private fun PublishSubject<Socket>.clientSocketProcessor(): Observable<Pair<ObjectInputStream, ObjectOutputStream>> {
return this
.observeOn(Schedulers.io())
// .doOnNext { s -> Timber.d("client socket ${s.inetAddress}") }
.map { s -> ObjectInputStream(s.getInputStream()) to ObjectOutputStream(s.getOutputStream()) }
}
}
@Singleton
class NetworkClient @Inject constructor() {
fun sendCommand(serverAddress: String, command: Command): Disposable {
Timber.i("$command -> $serverAddress")
return Completable
.create {
val socket = Socket(serverAddress, PORT_CMD)
val oos = ObjectOutputStream(socket.getOutputStream())
val ois = ObjectInputStream(socket.getInputStream())
oos.writeObject(command)
oos.flush()
socket.close()
}
.subscribeOn(Schedulers.io())
.subscribe({}, { t -> Timber.e(t, "Caught exception for this command upload.") })
}
fun sendTelemetry(serverAddress: String, telemetry: Telemetry): Disposable {
return Completable
.create {
val socket = Socket(serverAddress, PORT_TM)
val oos = ObjectOutputStream(socket.getOutputStream())
val ois = ObjectInputStream(socket.getInputStream())
oos.writeObject(telemetry)
oos.flush()
socket.close()
}
.subscribeOn(Schedulers.io())
.subscribe({}, { t -> Timber.e(t, "Caught exception for this telemetry upload.") })
}
fun sendImageData(serverAddress: String, byteArray: ByteArray): Disposable {
return Completable
.create {
val socket = Socket(serverAddress, PORT_BM)
val oos = ObjectOutputStream(socket.getOutputStream())
val ois = ObjectInputStream(socket.getInputStream())
oos.writeObject(byteArray)
oos.flush()
socket.close()
}
.subscribeOn(Schedulers.io())
.subscribe({}, { t -> Timber.e(t, "Caught exception for this image upload.") })
}
}
fun logIpAddresses() {
try {
val enumNetworkInterfaces = NetworkInterface.getNetworkInterfaces()
enumNetworkInterfaces.toList().forEach { networkInterface ->
networkInterface.inetAddresses.toList().forEach { address ->
if (address.isSiteLocalAddress) {
Timber.d("SiteLocalAddress: ${address.hostAddress}")
}
}
}
} catch (e: SocketException) {
Timber.d(e, "Caught a SocketException")
}
}
| 1
| null |
2
| 4
|
0404917454f2cbc04731c41d760edbff17444fb1
| 8,472
|
mixed-reality-toolbox
|
Apache License 2.0
|
app/src/main/java/com/app/upload_file/ui/upload_files/UploadListAdapter.kt
|
thanhit93
| 459,072,267
| false
| null |
package com.app.upload_file.ui.upload_files
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.app.upload_file.R
class UploadListAdapter(var fileNameList: List<String>, var fileDoneList: List<String>) :
RecyclerView.Adapter<UploadListAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view: View = LayoutInflater.from(parent.context).inflate(R.layout.single_list_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val fileName = fileNameList[position]
holder.fileName.text = fileName
val fileDone = fileDoneList[position]
if (fileDone == "Uploading") {
holder.fileDone.setImageResource(R.drawable.progress)
} else {
holder.fileDone.setImageResource(R.drawable.checked)
}
}
override fun getItemCount(): Int {
return fileNameList.size
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var fileName: TextView
var fileDone: ImageView
init {
fileName = itemView.findViewById(R.id.txtFilename)
fileDone = itemView.findViewById(R.id.imgLoading)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
8775ab01083bb8ea5fb4204438908767a177ba6a
| 1,448
|
multiple_upload_firebase
|
MIT License
|
media/audio-ui/src/test/kotlin/com/google/android/horologist/audio/ui/components/actions/SetVolumeButtonTest.kt
|
google
| 451,563,714
| false
|
{"Kotlin": 3151160, "Shell": 5169, "Java": 708, "Starlark": 361}
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.audio.ui.components.actions
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.google.android.horologist.audio.ui.VolumeUiState
import com.google.android.horologist.screenshots.rng.WearLegacyComponentTest
import org.junit.Test
class SetVolumeButtonTest : WearLegacyComponentTest() {
@Test
fun givenCurrentVolumeIsNotMaxAndNotMin_thenIconIsVolumeDown() {
val currentVolume = 5
runComponentTest {
SetVolumeButton(
onVolumeClick = {},
volumeUiState = VolumeUiState(current = currentVolume, max = 10),
)
}
}
@Test
fun givenCurrentVolumeIsMinimum_thenIconIsVolumeMute() {
val currentVolume = 0
runComponentTest {
SetVolumeButton(
onVolumeClick = {},
volumeUiState = VolumeUiState(current = currentVolume),
)
}
}
@Test
fun givenCurrentVolumeIsMaximum_thenIconIsVolumeUp() {
val currentVolume = 1
runComponentTest {
SetVolumeButton(
onVolumeClick = {},
volumeUiState = VolumeUiState(current = currentVolume),
)
}
}
@Test
fun givenNoVolumeUiState_thenIconIsVolumeUp() {
runComponentTest {
SetVolumeButton(onVolumeClick = {})
}
}
@Composable
override fun ComponentScaffold(content: @Composable () -> Unit) {
Box(
modifier = Modifier
.wrapContentSize()
.background(Color.Black.copy(alpha = 0.5f))
.border(1.dp, Color.White),
) {
content()
}
}
}
| 16
|
Kotlin
|
93
| 565
|
bde87db14f63338904550fc1827d0141ebe24d9a
| 2,633
|
horologist
|
Apache License 2.0
|
trixnity-core/src/commonMain/kotlin/net/folivo/trixnity/core/model/Mention.kt
|
benkuly
| 330,904,570
| false
|
{"Kotlin": 4181910, "JavaScript": 5352, "TypeScript": 2906, "CSS": 1454, "Dockerfile": 1275}
|
package net.folivo.trixnity.core.model
sealed interface Mention {
data class User(val userId: UserId) : Mention
data class Room(val roomId: RoomId) : Mention
data class RoomEvent(val roomId: RoomId, val eventId: EventId) : Mention
data class RoomAlias(val roomAliasId: RoomAliasId) : Mention
data class RoomAliasEvent(val roomAliasId: RoomAliasId, val eventId: EventId) : Mention
data class Event(val eventId: EventId) : Mention
}
| 0
|
Kotlin
|
3
| 29
|
8a92f29c64822248ba00fc6d8ad55466f93ab081
| 455
|
trixnity
|
Apache License 2.0
|
mtproto/src/main/kotlin/com/github/badoualy/telegram/mtproto/tl/MTProtoContext.kt
|
y9san9
| 285,876,206
| true
|
{"Gradle": 7, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "YAML": 1, "Markdown": 1, "JAR Manifest": 1, "Kotlin": 94, "INI": 1, "Java": 894, "Gradle Kotlin DSL": 1, "JSON": 776}
|
package com.github.badoualy.telegram.mtproto.tl
import com.github.badoualy.telegram.tl.TLContext
object MTProtoContext : TLContext(15) {
override fun init() {
registerClass(MTMessagesContainer.CONSTRUCTOR_ID, MTMessagesContainer::class.java)
registerClass(MTMsgsAck.CONSTRUCTOR_ID, MTMsgsAck::class.java)
registerClass(MTNewSessionCreated.CONSTRUCTOR_ID, MTNewSessionCreated::class.java)
registerClass(MTRpcError.CONSTRUCTOR_ID, MTRpcError::class.java)
registerClass(MTRpcResult.CONSTRUCTOR_ID, MTRpcResult::class.java)
registerClass(MTBadMessageNotification.CONSTRUCTOR_ID, MTBadMessageNotification::class.java)
registerClass(MTBadServerSalt.CONSTRUCTOR_ID, MTBadServerSalt::class.java)
registerClass(MTNeedResendMessage.CONSTRUCTOR_ID, MTNeedResendMessage::class.java)
registerClass(MTNewMessageDetailedInfo.CONSTRUCTOR_ID, MTNewMessageDetailedInfo::class.java)
registerClass(MTMessageDetailedInfo.CONSTRUCTOR_ID, MTMessageDetailedInfo::class.java)
registerClass(MTGetFutureSalts.CONSTRUCTOR_ID, MTGetFutureSalts::class.java)
registerClass(MTFutureSalts.CONSTRUCTOR_ID, MTFutureSalts::class.java)
registerClass(MTFutureSalt.CONSTRUCTOR_ID, MTFutureSalt::class.java)
// For test
//registerClass(MTPing.CONSTRUCTOR_ID, MTPing.class);
//registerClass(MTPingDelayDisconnect.CONSTRUCTOR_ID, MTPingDelayDisconnect.class);
//registerClass(MTPong.CONSTRUCTOR_ID, MTPong.class);
}
}
| 1
|
Java
|
2
| 5
|
34f98671bd0aa15c67b0ead1ed0292755bf8c7eb
| 1,527
|
kotlogram
|
MIT License
|
crp-util-desktop/src/main/kotlin/com/x256n/desktop/crputil/MainState.kt
|
liosha2007
| 471,299,880
| false
| null |
package com.x256n.desktop.crputil
data class MainState(
val mode: ScreenMode = ScreenMode.MAIN,
val source: String = "",
val result: List<DisplayResultItem> = emptyList(),
val activePanel: ActivePanel = ActivePanel.SOURCE,
val progress: Float = 0f,
val logs: MutableList<LogMessage> = mutableListOf(),
val timeout: Int = 3000,
val status: String = "Введіть вхідні дані та почніть перевірку",
val customTemplate: String = "tcp://#IP:#PORT ",
val customValue: String = "",
)
enum class ActivePanel {
SOURCE, RESULT
}
enum class ScreenMode {
MAIN, PROGRESS, CUSTOM_YELLOW, CUSTOM_GREEN, CUSTOM_ALL
}
| 0
|
Kotlin
|
0
| 0
|
23ec8032fbe3719a6e9a6b5d80cfb88fa2a31a90
| 648
|
crp-util
|
MIT License
|
velocity/src/main/kotlin/kingmc/platform/velocity/entity/player/VelocityPlayer.kt
|
Kingsthere
| 599,960,106
| false
|
{"Kotlin": 1080096}
|
package kingmc.platform.velocity.entity.player
import kingmc.common.application.Application
import kingmc.platform.proxy.entity.player.ProxiedPlayer
import kingmc.platform.server
import kingmc.platform.velocity.VelocityProxyServer
import kingmc.platform.velocity._VelocityPlayer
import kingmc.platform.velocity.command.VelocityCommandSender
/**
* Extended `Player` exposed an interface to convert this into a `com.velocitypowered.api.proxy.Player`
*
* @author kingsthere
* @since 0.0.9
*/
interface VelocityPlayer : ProxiedPlayer, VelocityCommandSender {
/**
* Convert this velocity player to a [com.velocitypowered.api.proxy.Player]
*/
fun toVelocityPlayer(): _VelocityPlayer
}
/**
* Convert this [com.velocitypowered.api.proxy.Player] to kingmc `Player`
*
* @receiver velocity player to convert to
* @return `Player` instance converted
*/
fun _VelocityPlayer.asKingMC(application: Application) =
(application.server as VelocityProxyServer).getPlayerForVelocity(this)
| 0
|
Kotlin
|
0
| 1
|
6c325cbe550bcebc70f3071564e63459c2592f6b
| 1,003
|
kingmc-platform
|
MIT License
|
web/src/main/kotlin/showdown.web/ui/game/Toolbar.kt
|
Foso
| 335,062,450
| false
| null |
package showdown.web.ui.game
import Application
import kotlinx.html.DIV
import kotlinx.html.id
import kotlinx.html.js.onClickFunction
import materialui.components.appbar.appBar
import materialui.components.appbar.enums.AppBarColor
import materialui.components.appbar.enums.AppBarPosition
import materialui.components.button.button
import materialui.components.button.enums.ButtonColor
import materialui.components.button.enums.ButtonVariant
import materialui.components.checkbox.checkbox
import materialui.components.menu.menu
import materialui.components.menuitem.menuItem
import org.w3c.dom.events.EventTarget
import react.*
import react.dom.RDOMBuilder
import react.dom.div
import react.dom.label
import showdown.web.game.GameDataSource
import showdown.web.wrapper.material.ShareIcon
import showdown.web.wrapper.material.VisibilityIcon
import showdown.web.wrapper.material.icons.AccountCircleIcon
import showdown.web.wrapper.material.icons.AddCircleIcon
import kotlin.browser.window
import kotlin.math.floor
interface ToolbarState : RState {
var onNewGameClicked: () -> Unit
var onShowVotesClicked: () -> Unit
var onGameModeClicked: () -> Unit
var diffSecs: Double
var openMenu: Boolean
var anchor: EventTarget?
var startTimer: Boolean
var showShareDialog: Boolean
var gameConfig: Boolean
}
interface ToolbarProps : RProps {
var onNewGameClicked: () -> Unit
var onShowVotesClicked: () -> Unit
var startTimer: Boolean
var diffSecs: Double
var onGameModeClicked: () -> Unit
var autoReveal: Boolean
}
class Toolbar(props: ToolbarProps) : RComponent<ToolbarProps, ToolbarState>(props) {
private val gameDataSource: GameDataSource = Application.gameDataSource
override fun ToolbarState.init(props: ToolbarProps) {
this.onNewGameClicked = props.onNewGameClicked
this.onShowVotesClicked = props.onShowVotesClicked
this.startTimer = props.startTimer
this.showShareDialog = false
this.diffSecs = props.diffSecs
this.onGameModeClicked = props.onGameModeClicked
}
override fun componentWillReceiveProps(nextProps: ToolbarProps) {
setState {
this.diffSecs = props.diffSecs
this.startTimer = props.startTimer
this.gameConfig = props.autoReveal
}
}
override fun RBuilder.render() {
shareDialog(state.showShareDialog) {
setState {
this.showShareDialog = false
}
}
appBar {
attrs {
position = AppBarPosition.static
color = AppBarColor.primary
}
div {
newGameButton()
showVotesButton()
shareButton()
settingsPopupMenu(state)
+"Estimation time: ${getTimerText()} seconds."
}
}
}
private fun RDOMBuilder<DIV>.newGameButton() {
button {
attrs {
variant = ButtonVariant.contained
color = ButtonColor.primary
text("New Game")
onClickFunction = {
state.onNewGameClicked()
}
startIcon {
AddCircleIcon {}
}
}
}
}
private fun RDOMBuilder<DIV>.showVotesButton() {
button {
attrs {
variant = ButtonVariant.contained
color = ButtonColor.primary
text("Show Votes")
onClickFunction = {
state.onShowVotesClicked()
}
startIcon {
VisibilityIcon {}
}
}
}
}
private fun RDOMBuilder<DIV>.shareButton() {
button {
attrs {
variant = ButtonVariant.contained
color = ButtonColor.primary
text("Share")
onClickFunction = {
setState {
this.showShareDialog = true
}
}
startIcon {
ShareIcon {}
}
}
}
}
private fun getTimerText(): String {
return if (state.startTimer) {
floor(state.diffSecs).toString()
} else {
"0"
}
}
private fun RBuilder.settingsPopupMenu(
state: ToolbarState
) {
button {
+"Settings"
attrs {
variant = ButtonVariant.contained
color = ButtonColor.primary
asDynamic()["aria-controls"] = "simple-menu"
asDynamic()["aria-haspopup"] = true
startIcon {
AccountCircleIcon {}
}
onClickFunction = { event ->
val currentTarget = event.currentTarget
setState {
anchor = currentTarget
openMenu = !state.openMenu
}
}
}
}
menu {
attrs {
id = "simple-menu"
open = state.openMenu
onClose = { event, s ->
setState {
openMenu = false
}
}
anchorEl(state.anchor)
}
menuItem {
attrs {
onClickFunction = {
setState {
openMenu = false
}
}
}
label {
+"Playername: ${gameDataSource.getPlayerName()}"
}
}
menuItem {
attrs {
onClickFunction = {
setState {
openMenu = false
}
}
}
checkbox {
attrs {
checked = state.gameConfig
onClickFunction = {
gameDataSource.setAutoReveal(!state.gameConfig)
}
}
}
label {
+"AutoReveal Votes"
}
}
menuItem {
attrs {
onClickFunction = {
setState {
openMenu = false
}
state.onGameModeClicked()
}
}
label {
+" Change GameConfig"
}
}
menuItem {
attrs {
onClickFunction = {
window.location.href = "https://github.com/Foso/Showdown/issues";
}
}
label {
+"Issues/Feature Requests"
}
}
menuItem {
attrs {
onClickFunction = {
window.location.href = "https://github.com/Foso/Showdown";
}
}
label {
+"Showdown v1.1 on Github"
}
}
}
}
}
fun RBuilder.myToolbar(
startTimer: Boolean,
onNewGameClicked: () -> Unit,
onShowVotesClicked: () -> Unit,
diffSecs: Double,
onGameModeClicked: () -> Unit,
gameConfig: Boolean
): ReactElement {
return child(Toolbar::class) {
attrs {
this.onNewGameClicked = onNewGameClicked
this.onShowVotesClicked = onShowVotesClicked
this.startTimer = startTimer
this.diffSecs = diffSecs
this.onGameModeClicked = onGameModeClicked
this.autoReveal = gameConfig
}
}
}
| 0
|
Kotlin
|
0
| 0
|
b68c5f3964163fa2d263b298b96c30c1c469bcf3
| 8,058
|
QuizPrototype
|
Apache License 2.0
|
app/src/main/java/com/fourteenrows/p2pcs/activities/quest/QuestRecyclerAdapter.kt
|
FourteenRows
| 185,977,617
| false
| null |
package com.fourteenrows.p2pcs.activities.quest
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatTextView
import androidx.recyclerview.widget.RecyclerView
import com.fourteenrows.p2pcs.R
import com.fourteenrows.p2pcs.objects.quests.ActiveQuest
import kotlinx.android.synthetic.main.recycler_quest_item.view.*
class QuestRecyclerAdapter(
private val items: ArrayList<ActiveQuest>,
private val listener: IQuestListener
) :
RecyclerView.Adapter<QuestRecyclerAdapter.BaseViewHolder<*>>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<*> {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.recycler_quest_item, parent, false)
return QuestViewHolder(view, listener)
}
override fun onBindViewHolder(holder: BaseViewHolder<*>, position: Int) {
val element = items[position]
(holder as QuestViewHolder).bind(element)
}
override fun getItemCount(): Int = items.size
abstract class BaseViewHolder<T>(itemView: View) : RecyclerView.ViewHolder(itemView) {
abstract fun bind(item: T)
}
class QuestViewHolder(val view: View, val listener: IQuestListener) :
BaseViewHolder<ActiveQuest>(view),
View.OnClickListener {
private val name = view.name
private val qid = view.qid
private val exp = view.exp as AppCompatTextView
private val gaiaCoin = view.gaiacoin as AppCompatTextView
private val imgPremio = view.imgPremio
private val objective = view.fine as AppCompatTextView
private val progressBar = view.progressbar
override fun bind(item: ActiveQuest) {
name.text = view.resources.getString(R.string.quest_objective, item.name)
qid.text = item.qid
exp.text = item.exp.toString()
gaiaCoin.text = item.gaia_coins.toString()
objective.text =
view.resources.getString(R.string.quest_status, item.progress.toString(), item.target.toString())
progressBar.min = 0
progressBar.max = item.target.toInt()
progressBar.progress = item.progress.toInt()
if (item.box.isNotEmpty()) {
imgPremio.visibility = View.VISIBLE
}
view.changeQuest.setOnClickListener {
listener.changeQuestRequest(qid.text.toString())
}
}
override fun onClick(view: View) {}
}
}
| 0
|
Kotlin
|
0
| 0
|
b88364cb6775aa24ef005845943d1086a7f76bbe
| 2,556
|
P2PCS
|
MIT License
|
compiler/testData/codegen/box/inlineClasses/propertyDelegation/kt42933.kt
|
JetBrains
| 3,432,266
| false
| null |
// WITH_RUNTIME
class Delegate {
operator fun getValue(t: Any?, p: Any): String = "OK"
}
@Suppress("OPTIONAL_DECLARATION_USAGE_IN_NON_COMMON_SOURCE")
@kotlin.jvm.JvmInline
value class Kla1(val default: Int) {
fun getValue(): String {
val prop by Delegate()
return prop
}
}
fun box() = Kla1(1).getValue()
| 125
| null |
4813
| 39,375
|
83d2d2cfcfc3d9903c902ca348f331f89bed1076
| 334
|
kotlin
|
Apache License 2.0
|
compiler/testData/codegen/classes/privateOuterFunctions.kt
|
chirino
| 3,596,099
| false
| null |
class C {
private fun String.ext() : String = ""
private fun f() {}
public fun foo() : String {
{
"".ext()
f()
}.invoke()
object : Runnable {
public override fun run() {
"".ext()
f()
}
}.run()
Inner().innerFun()
return "OK"
}
private class Inner() {
fun innerFun() {
"".ext()
f()
}
}
}
fun box() = C().foo()
| 0
| null |
28
| 71
|
ac434d48525a0e5b57c66b9f61b388ccf3d898b5
| 505
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/com/hiberus/anaya/redmineeditor/dialogs/ColorEntrySettings.kt
|
anayaHiberus
| 645,313,511
| false
|
{"Kotlin": 214371, "Java": 692, "Batchfile": 504, "Shell": 240, "CSS": 43}
|
package com.hiberus.anaya.redmineeditor.dialogs
import com.hiberus.anaya.redmineeditor.model.Colors
import com.hiberus.anaya.redmineeditor.utils.enabled
import javafx.scene.control.Button
import javafx.scene.control.ColorPicker
import javafx.scene.control.Label
import javafx.scene.control.Tooltip
/** For settings. */
class ColorEntrySettings {
lateinit var defaultBtn: Button
lateinit var restoreBtn: Button
lateinit var colorPicker: ColorPicker
lateinit var label: Label
lateinit var color: Colors
fun initialize(color: Colors) {
this.color = color
// init properties
label.text = color.description
label.tooltip = Tooltip(color.name)
colorPicker.value = color.value
// init buttons
colorPicker.valueProperty().addListener { _, _, value ->
restoreBtn.enabled = value != color.value
defaultBtn.enabled = value != color.defaultValue
}
restoreBtn.enabled = false
defaultBtn.enabled = color.value != color.defaultValue
}
/** True iff the user changed the color. */
val hasChanges get() = colorPicker.value != color.value
/** Restores the currently saved color. */
fun restoreCurrent() {
colorPicker.value = color.value
}
/** Applies the chosen color, returns true iff it was changed. */
fun modify() = (colorPicker.value != color.value).also { color.value = colorPicker.value }
/** Loads the default color. */
fun loadDefault() {
colorPicker.value = color.defaultValue
}
/** Run listener when color changes. */
fun onChange(listener: () -> Unit) {
colorPicker.valueProperty().addListener { _, _, _ -> listener() }
}
}
| 0
|
Kotlin
|
0
| 3
|
b0bac42c74907f2b29b832a2e6bd1d57f3831e5f
| 1,737
|
redmineeditor
|
Creative Commons Attribution 4.0 International
|
app/src/main/java/com/benrostudios/enchante/data/models/response/home/PasseX.kt
|
EnchanteHQ
| 380,800,255
| false
| null |
package com.benrostudios.enchante.data.models.response.events
data class PasseX(
val _id: String? = "",
val availableNumber: Int? = 0,
val description: String? = "",
val passName: String? = "",
val price: Int? = 0
)
| 0
|
Kotlin
|
0
| 0
|
67cf14e4929105fcc7b2d1c8ad35136ea2c5f154
| 236
|
enchante
|
MIT License
|
zzsong-device-edge/src/main/kotlin/com/zzsong/device/edge/configure/DeviceEdgeInitializing.kt
|
Songzhizong
| 465,969,434
| false
| null |
package com.zzsong.device.edge.configure
import com.zzsong.device.edge.infrastructure.center.CenterClient
import kotlinx.coroutines.runBlocking
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.SmartInitializingSingleton
import org.springframework.stereotype.Component
/**
* @author 宋志宗 on 2022/4/8
*/
@Component
class DeviceEdgeInitializing(
private val centerClient: CenterClient,
private val edgeProperties: DeviceEdgeProperties
) : SmartInitializingSingleton {
companion object {
private val log: Logger = LoggerFactory.getLogger(DeviceEdgeInitializing::class.java)
}
override fun afterSingletonsInstantiated() {
val edgeId = edgeProperties.edgeId
if (edgeId != null) {
val edge = runBlocking { centerClient.getEdgeInfo(edgeId) }
val name = edge.name
log.info("=============================================================================")
log.info("")
log.info(" 当前边缘节点: {}", name)
log.info("")
log.info("=============================================================================")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
06f8f2664499e92576b0bc329083ec15bebfdad9
| 1,138
|
zzsong-device
|
MIT License
|
src/test/kotlin/uk/gov/justice/digital/hmpps/prisonerfromnomismigration/prisonperson/physicalattributes/PhysicalAttributesNomisApiMockServer.kt
|
ministryofjustice
| 452,734,022
| false
|
{"Kotlin": 2137951, "Mustache": 1803, "Dockerfile": 1377}
|
package uk.gov.justice.digital.hmpps.prisonerfromnomismigration.prisonperson
import com.fasterxml.jackson.databind.ObjectMapper
import com.github.tomakehurst.wiremock.client.WireMock.aResponse
import com.github.tomakehurst.wiremock.client.WireMock.get
import com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo
import com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching
import com.github.tomakehurst.wiremock.matching.RequestPatternBuilder
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Component
import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomismappings.model.ErrorResponse
import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.BookingPhysicalAttributesResponse
import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.PhysicalAttributesResponse
import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.PrisonerPhysicalAttributesResponse
import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.wiremock.NomisApiExtension.Companion.nomisApi
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
@Component
class PrisonPersonNomisApiMockServer(private val objectMapper: ObjectMapper) {
fun stubGetPhysicalAttributes(
offenderNo: String = "A1234AA",
response: PrisonerPhysicalAttributesResponse = PrisonerPhysicalAttributesResponse(
offenderNo = offenderNo,
bookings = listOf(
BookingPhysicalAttributesResponse(
bookingId = 1,
startDateTime = "2024-02-03T12:34:56",
endDateTime = "2024-10-21T12:34:56",
latestBooking = true,
physicalAttributes = listOf(
PhysicalAttributesResponse(
attributeSequence = 1,
heightCentimetres = 180,
weightKilograms = 80,
createdBy = "A_USER",
createDateTime = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
modifiedBy = "ANOTHER_USER",
modifiedDateTime = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
auditModuleName = "MODULE",
),
),
),
),
),
) = nomisApi.stubFor(
get(urlEqualTo("/prisoners/$offenderNo/physical-attributes")).willReturn(
aResponse()
.withHeader("Content-Type", "application/json")
.withStatus(HttpStatus.OK.value())
.withBody(objectMapper.writeValueAsString(response)),
),
)
fun stubGetPhysicalAttributes(status: HttpStatus, error: ErrorResponse = ErrorResponse(status = status.value())) {
nomisApi.stubFor(
get(urlPathMatching("/prisoners/\\w+/physical-attributes")).willReturn(
aResponse()
.withHeader("Content-Type", "application/json")
.withStatus(status.value())
.withBody(objectMapper.writeValueAsString(error)),
),
)
}
fun verify(pattern: RequestPatternBuilder) = nomisApi.verify(pattern)
fun verify(count: Int, pattern: RequestPatternBuilder) = nomisApi.verify(count, pattern)
}
| 3
|
Kotlin
|
1
| 2
|
d312542469362ff77dab8300a3aadaadc3143395
| 3,099
|
hmpps-prisoner-from-nomis-migration
|
MIT License
|
build-tools/agp-gradle-core/src/main/java/com/android/build/gradle/internal/ManagedDeviceUtils.kt
|
RivanParmar
| 526,653,590
| false
| null |
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.build.gradle.internal
import com.android.build.api.dsl.Device
import com.android.build.api.dsl.DeviceGroup
import com.android.build.gradle.internal.component.InstrumentedTestCreationConfig
import com.android.build.gradle.internal.dsl.ManagedVirtualDevice
import com.android.build.gradle.options.ProjectOptions
import com.android.build.gradle.options.StringOption
import com.android.prefs.AndroidLocationsProvider
import com.android.testing.utils.computeVendorString
import com.android.utils.CpuArchitecture
import com.android.utils.osArchitecture
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.ProviderFactory
private const val GRADLE_AVD_DIRECTORY_PATH = "gradle/avd"
/**
* Gets the provider of the avd folder for managed devices across all projects.
*/
fun getManagedDeviceAvdFolder(
objectFactory: ObjectFactory,
providerFactory: ProviderFactory,
androidLocationsProvider: AndroidLocationsProvider
): DirectoryProperty =
objectFactory.directoryProperty().fileProvider(providerFactory.provider {
androidLocationsProvider.gradleAvdLocation.toFile()
})
fun computeAvdName(device: ManagedVirtualDevice): String =
computeAvdName(
device.apiLevel,
device.systemImageSource,
computeAbiFromArchitecture(device),
device.device)
fun computeAvdName(
apiLevel: Int,
imageSource: String,
abi: String,
hardwareProfile: String
): String {
val sanitizedProfile = sanitizeProfileName(hardwareProfile)
val vendor = computeVendorString(imageSource)
return "dev${apiLevel}_${vendor}_${abi}_$sanitizedProfile"
}
fun sanitizeProfileName(hardwareProfile: String) =
hardwareProfile.replace(Regex("[() ]"), "_")
fun setupTaskName(device: Device): String = "${device.name}Setup"
fun managedDeviceAllVariantsTaskName(device: Device): String = "${device.name}Check"
fun managedDeviceGroupAllVariantsTaskName(deviceGroup: DeviceGroup): String =
"${deviceGroup.name}GroupCheck"
fun managedDeviceGroupSingleVariantTaskName(
creationConfig: InstrumentedTestCreationConfig, deviceGroup: DeviceGroup): String =
creationConfig.computeTaskName("${deviceGroup.name}Group")
fun computeAbiFromArchitecture(device: ManagedVirtualDevice): String =
computeAbiFromArchitecture(
device.require64Bit,
device.apiLevel,
device.systemImageSource
)
fun computeAbiFromArchitecture(
require64Bit: Boolean,
apiLevel: Int,
vendor: String,
cpuArch: CpuArchitecture = osArchitecture
): String = when {
cpuArch == CpuArchitecture.ARM
|| cpuArch == CpuArchitecture.X86_ON_ARM-> "arm64-v8a"
require64Bit -> "x86_64"
// Neither system-images;android-30;default;x86 nor system-images;android-26;default;x86
// exist, but the google images do.
vendor == "aosp" && apiLevel in listOf(26, 30) -> "x86_64"
apiLevel <= 30 -> "x86"
else -> "x86_64"
}
fun computeManagedDeviceEmulatorMode(projectOptions: ProjectOptions) =
projectOptions[StringOption.GRADLE_MANAGED_DEVICE_EMULATOR_GPU_MODE] ?: "auto-no-window"
| 0
| null |
2
| 17
|
a497291d77bba1aa34271808088fe1e8aab5efe2
| 3,775
|
androlabs
|
Apache License 2.0
|
app/src/main/java/net/osdn/ja/gokigen/wearos/timerapp/presentation/ui/ViewRoot.kt
|
MRSa
| 753,626,791
| false
|
{"Kotlin": 57411}
|
package net.osdn.ja.gokigen.wearos.timerapp.presentation.ui
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.AbstractComposeView
import androidx.wear.compose.navigation.rememberSwipeDismissableNavController
import net.osdn.ja.gokigen.wearos.timerapp.counter.CounterModel
import net.osdn.ja.gokigen.wearos.timerapp.presentation.theme.TimerAppTheme
class ViewRoot @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : AbstractComposeView(context, attrs, defStyleAttr)
{
private val appContext: Context
init
{
this.appContext = context
}
@Composable
override fun Content()
{
val navController = rememberSwipeDismissableNavController()
val counterModel = remember { CounterModel(appContext) }
TimerAppTheme {
NavigationMain(appContext, navController, counterModel)
}
Log.v(TAG, " ... ViewRoot ...")
}
companion object
{
private val TAG = ViewRoot::class.java.simpleName
}
}
| 0
|
Kotlin
|
0
| 0
|
3f4fac2d77da8ee9ff39a9b931c57fa77a87f8b9
| 1,193
|
TimerApp
|
Apache License 2.0
|
deprecated/RxJavaTemplate/app/src/main/java/co/nimblehq/rxjava/ui/common/ItemClickable.kt
|
nimblehq
| 101,353,301
| false
| null |
package co.nimblehq.rxjava.ui.common
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
interface ItemClickable<T : Any> {
val itemClick: Observable<T>
fun notifyItemClick(data: T)
}
class ItemClickableImpl<T : Any> : ItemClickable<T> {
private val _itemClick = PublishSubject.create<T>()
override val itemClick: Observable<T>
get() = _itemClick
override fun notifyItemClick(data: T) = _itemClick.onNext(data)
}
| 31
| null |
23
| 94
|
f07941499a70b6144f4280c233edba542ab3e516
| 471
|
android-templates
|
MIT License
|
app/src/main/java/com/xwq/companyvxwhelper/bean/Enum/InputSettingEnum.kt
|
aidenpierce2
| 421,354,234
| false
| null |
package com.xwq.companyvxwhelper.bean.Enum
enum class InputSettingEnum(var inputSettingStr : String) {
PHONENUM("phonenum"), WXACCOUNT("wxaccount")
}
| 0
|
Kotlin
|
0
| 0
|
f3dea6373b9a48e9fbbd69dba8a27da10d6569b3
| 156
|
companyvxwhelper
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.