repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
F43nd1r/acra-backend | acrarium/src/main/kotlin/com/faendir/acra/setup/UserSetup.kt | 1 | 2922 | package com.faendir.acra.setup
import com.faendir.acra.model.User
import com.faendir.acra.service.UserService
import com.faendir.acra.util.zip
import mu.KotlinLogging
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.stereotype.Component
private val logger = KotlinLogging.logger {}
private const val CREATE_USER_OPTION = "create-user"
private const val PASSWORD_OPTION = "password"
private const val ROLES_OPTION = "roles"
@Component
class UserSetup(private val userService: UserService) : ApplicationRunner {
override fun run(args: ApplicationArguments) {
if (args.containsOption(CREATE_USER_OPTION)) {
val names = args.getOptionValues(CREATE_USER_OPTION)
if (names.isEmpty()) {
logger.error { "No username provided. No users created." }
return
}
if (!args.containsOption(PASSWORD_OPTION)) {
logger.error { "No password provided. No users created." }
return
}
val passwords = args.getOptionValues(PASSWORD_OPTION)
if (names.size != passwords.size) {
logger.error { "User and password count do not match. No users created." }
return
}
val rolesList = (args.getOptionValues(ROLES_OPTION)?.map { rolesString ->
rolesString.split(",").map {
try {
User.Role.valueOf(it.uppercase())
} catch (e: Exception) {
logger.error { "Unknown role $it. No users created." }
return
}
}
} ?: emptyList()).let { it + MutableList(names.size - it.size) { listOf(User.Role.ADMIN, User.Role.USER, User.Role.API) } }
names.zip(passwords, rolesList).forEach { (name, password, roles) ->
if (name.isBlank()) {
logger.error { "Username may not be blank." }
return@forEach
}
if (userService.getUser(name) != null) {
logger.warn { "User $name already exists." }
return@forEach
}
if (password.isBlank()) {
logger.error { "Password my not be blank." }
return@forEach
}
if (roles.contains(User.Role.REPORTER)) {
logger.error { "Reporter users may not be created manually." }
return@forEach
}
val user = User(name, "", roles.toMutableSet().apply { if (contains(User.Role.ADMIN)) add(User.Role.USER) }, password, null)
userService.store(user)
logger.info { "Created user $name with roles $roles." }
}
}
}
} | apache-2.0 | 38860af026e4a026dd4ae12433eadde2 | 41.362319 | 140 | 0.55065 | 4.735818 | false | false | false | false |
JetBrains/teamcity-dnx-plugin | plugin-dotnet-agent/src/test/kotlin/jetbrains/buildServer/dotnet/test/dotnet/VSTestLoggerArgumentsProviderTest.kt | 1 | 2525 | package jetbrains.buildServer.dotnet.test.dotnet
import io.mockk.*
import io.mockk.impl.annotations.MockK
import jetbrains.buildServer.agent.Path
import jetbrains.buildServer.agent.ToolPath
import jetbrains.buildServer.agent.VirtualContext
import jetbrains.buildServer.dotnet.*
import org.testng.Assert
import org.testng.annotations.BeforeMethod
import org.testng.annotations.DataProvider
import org.testng.annotations.Test
import java.io.File
class VSTestLoggerArgumentsProviderTest {
@MockK private lateinit var _loggerParameters: LoggerParameters
@MockK private lateinit var _virtualContext: VirtualContext
@BeforeMethod
fun setUp() {
MockKAnnotations.init(this)
clearAllMocks()
every { _virtualContext.resolvePath(any()) } answers { "v_" + arg<String>(0)}
}
@DataProvider
fun testLoggerArgumentsData(): Array<Array<Any?>> {
return arrayOf(
// Success scenario
arrayOf(
File("loggerPath", "vstestlogger.dll") as File?,
Verbosity.Normal,
listOf(
"/logger:logger://teamcity",
"/TestAdapterPath:v_${File("loggerPath").canonicalPath}",
"/logger:console;verbosity=normal")),
arrayOf(
File("loggerPath", "vstestlogger.dll") as File?,
Verbosity.Detailed,
listOf(
"/logger:logger://teamcity",
"/TestAdapterPath:v_${File("loggerPath").canonicalPath}",
"/logger:console;verbosity=detailed"))
)
}
@Test(dataProvider = "testLoggerArgumentsData")
fun shouldGetArguments(
loggerFile: File,
verbosity: Verbosity,
expectedArguments: List<String>) {
// Given
val context = DotnetBuildContext(ToolPath(Path("wd")), mockk<DotnetCommand>())
val argumentsProvider = VSTestLoggerArgumentsProvider(LoggerResolverStub(File("msbuildlogger"), loggerFile), _loggerParameters, _virtualContext)
every { _loggerParameters.vsTestVerbosity } returns verbosity
// When
val actualArguments = argumentsProvider.getArguments(context).map { it.value }.toList()
// Then
verify { _virtualContext.resolvePath(any()) }
Assert.assertEquals(actualArguments, expectedArguments)
}
} | apache-2.0 | 01cd11ad3917b755d80b52685026a7d8 | 37.272727 | 152 | 0.613069 | 5.304622 | false | true | false | false |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/fragment/PrepareSharingFragment.kt | 1 | 6064 | /*
* Copyright (C) 2021 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.fragment
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.navigation.fragment.findNavController
import com.genonbeta.android.framework.io.OpenableContent
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.monora.uprotocol.client.android.R
import org.monora.uprotocol.client.android.database.model.UTransferItem
import org.monora.uprotocol.client.android.databinding.LayoutPrepareSharingBinding
import org.monora.uprotocol.core.protocol.Direction
import java.lang.ref.WeakReference
import java.text.Collator
import java.util.*
import javax.inject.Inject
import kotlin.random.Random
@AndroidEntryPoint
class PrepareSharingFragment : Fragment(R.layout.layout_prepare_sharing) {
private val preparationViewModel: PreparationViewModel by activityViewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val activity = activity
val intent = activity?.intent
if (activity != null && intent != null) {
if (Intent.ACTION_SEND == intent.action && intent.hasExtra(Intent.EXTRA_TEXT)) {
findNavController().navigate(
PrepareSharingFragmentDirections.actionPrepareSharingFragmentToNavTextEditor(
text = intent.getStringExtra(Intent.EXTRA_TEXT)
)
)
} else {
val list: List<Uri>? = try {
when (intent.action) {
Intent.ACTION_SEND -> (intent.getParcelableExtra(Intent.EXTRA_STREAM) as Uri?)?.let {
Collections.singletonList(it)
}
Intent.ACTION_SEND_MULTIPLE -> intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM)
else -> null
}
} catch (e: Throwable) {
null
}
if (list.isNullOrEmpty()) {
activity.finish()
return
}
preparationViewModel.consume(list)
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = LayoutPrepareSharingBinding.bind(view)
binding.button.setOnClickListener {
if (!findNavController().navigateUp()) activity?.finish()
}
preparationViewModel.shared.observe(viewLifecycleOwner) {
when (it) {
is PreparationState.Progress -> {
binding.progressBar.max = it.total
if (Build.VERSION.SDK_INT >= 24) {
binding.progressBar.setProgress(it.index, true)
} else {
binding.progressBar.progress = it.index
}
}
is PreparationState.Ready -> {
findNavController().navigate(
PrepareSharingFragmentDirections.actionPrepareSharingFragmentToSharingFragment(
it.list.toTypedArray(), it.id
)
)
}
}
}
}
}
@HiltViewModel
class PreparationViewModel @Inject internal constructor(
@ApplicationContext context: Context,
) : ViewModel() {
private var consumer: Job? = null
private val context = WeakReference(context)
val shared = MutableLiveData<PreparationState>()
@Synchronized
fun consume(contents: List<Uri>) {
if (consumer != null) return
consumer = viewModelScope.launch(Dispatchers.IO) {
val groupId = Random.nextLong()
val list = mutableListOf<UTransferItem>()
val direction = Direction.Outgoing
contents.forEachIndexed { index, uri ->
val context = context.get() ?: return@launch
val id = index.toLong()
OpenableContent.from(context, uri).runCatching {
shared.postValue(PreparationState.Progress(index, contents.size, name))
list.add(UTransferItem(id, groupId, name, mimeType, size, null, uri.toString(), direction))
}
}
val collator = Collator.getInstance()
list.sortWith { o1, o2 -> collator.compare(o1.name, o2.name) }
shared.postValue(PreparationState.Ready(groupId, list))
consumer = null
}
}
}
sealed class PreparationState {
class Progress(val index: Int, val total: Int, val title: String) : PreparationState()
class Ready(val id: Long, val list: List<UTransferItem>) : PreparationState()
}
| gpl-2.0 | f535d5ead6fe8e13563f79045550e518 | 35.745455 | 111 | 0.637803 | 5.048293 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-tests/src/test/kotlin/test/setup/SampleAnnoApi.kt | 1 | 3636 | package test.setup
import slatekit.apis.*
import slatekit.apis.AuthModes
import slatekit.common.*
import slatekit.common.auth.Roles
import slatekit.common.crypto.EncDouble
import slatekit.common.crypto.EncInt
import slatekit.common.crypto.EncLong
import slatekit.common.crypto.EncString
import slatekit.requests.Request
import slatekit.utils.smartvalues.Email
import slatekit.utils.smartvalues.PhoneUS
import slatekit.connectors.entities.AppEntContext
import slatekit.results.Notice
import slatekit.results.Success
@Api(area = "app", name = "tests", desc = "sample to test features of Slate Kit APIs", auth = AuthModes.TOKEN, roles= ["admin"])
class SampleAnnoApi(val context: AppEntContext) {
@Action(desc = "accepts supplied basic data types from send")
fun inputBasicTypes(string1: String, bool1: Boolean, numShort: Short, numInt: Int, numLong: Long, numFloat: Float, numDouble: Double, date: DateTime): String {
return "$string1, $bool1, $numShort $numInt, $numLong, $numFloat, $numDouble, $date"
}
@Action(desc = "access the send model directly instead of auto-conversion", roles= [Roles.ALL])
fun inputRequest(req: Request): Notice<String> {
return Success("ok", msg = "raw send id: " + req.data!!.getInt("id"))
}
@Action(desc = "auto-convert json to objects", roles= [Roles.ALL])
fun inputObject(movie: Movie): Movie {
return movie
}
@Action(desc = "auto-convert json to objects", roles= [Roles.ALL])
fun inputObjectlist(movies:List<Movie>): List<Movie> {
return movies
}
@Action(desc = "accepts a list of strings from send", roles= [Roles.ALL])
fun inputListString(items:List<String>): Notice<String> {
return Success("ok", msg = items.fold("", { acc, curr -> acc + "," + curr } ))
}
@Action(desc = "accepts a list of integers from send", roles= [Roles.ALL])
fun inputListInt(items:List<Int>): Notice<String> {
return Success("ok", msg = items.fold("", { acc, curr -> acc + "," + curr.toString() } ))
}
@Action(desc = "accepts a map of string/ints from send", roles= [Roles.ALL])
fun inputMapInt(items:Map<String,Int>): Notice<String> {
val sortedPairs = items.keys.toList().sortedBy{ k:String -> k }.map{ key -> Pair(key, items[key]) }
val delimited = sortedPairs.fold("", { acc, curr -> acc + "," + curr.first + "=" + curr.second } )
return Success("ok", msg = delimited)
}
@Action(desc = "accepts an encrypted int that will be decrypted", roles= [Roles.ALL])
fun inputDecInt(id: EncInt): Notice<String> {
return Success("ok", msg ="decrypted int : " + id.value)
}
@Action(desc = "accepts an encrypted long that will be decrypted", roles= [Roles.ALL])
fun inputDecLong(id: EncLong): Notice<String> {
return Success("ok", msg ="decrypted long : " + id.value)
}
@Action(desc = "accepts an encrypted double that will be decrypted", roles= [Roles.ALL])
fun inputDecDouble(id: EncDouble): Notice<String>
{
return Success("ok", msg = "decrypted double : " + id.value)
}
@Action(desc = "accepts an encrypted string that will be decrypted", roles= [Roles.ALL])
fun inputDecString(id: EncString): Notice<String>
{
return Success("ok", msg = "decrypted string : " + id.value)
}
@Action(desc = "accepts a smart string of phone", roles= [Roles.GUEST])
fun smartStringPhone(text: PhoneUS): String = "${text.value}"
@Action(desc = "accepts a smart string of email", roles= [Roles.GUEST])
fun smartStringEmail(text: Email): String = "${text.value}"
}
| apache-2.0 | 7ca6656b86336b8edd0bbcb4ee984c1b | 35.36 | 163 | 0.665292 | 3.73306 | false | false | false | false |
moko256/twicalico | app/src/main/java/com/github/moko256/twitlatte/widget/ImageKeyboardEditText.kt | 1 | 2757 | /*
* Copyright 2015-2019 The twitlatte authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.github.moko256.twitlatte.widget
import android.content.Context
import android.net.Uri
import android.os.Build
import android.util.AttributeSet
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import androidx.appcompat.widget.AppCompatEditText
import androidx.core.view.inputmethod.EditorInfoCompat
import androidx.core.view.inputmethod.InputConnectionCompat
import androidx.core.view.inputmethod.InputContentInfoCompat
/**
* Created by moko256 on 2017/12/20.
*
* @author moko256
*/
class ImageKeyboardEditText : AppCompatEditText {
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context) : super(context)
var imageAddedListener: OnImageAddedListener? = null
private var permitInputContentInfo: InputContentInfoCompat? = null
override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection {
val ic = super.onCreateInputConnection(outAttrs)
EditorInfoCompat.setContentMimeTypes(outAttrs, arrayOf("image/*", "video/*"))
return InputConnectionCompat.createWrapper(ic, outAttrs) { inputContentInfo, flags, _ ->
if (Build.VERSION.SDK_INT >= 25 && flags and InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION != 0) {
try {
inputContentInfo.requestPermission()
permitInputContentInfo = inputContentInfo
} catch (e: Exception) {
return@createWrapper false
}
}
val result = imageAddedListener?.onAdded(inputContentInfo.contentUri)
if (inputContentInfo.linkUri != null && result == true) {
text?.append(" " + inputContentInfo.linkUri?.toString())
}
true
}
}
fun close() {
permitInputContentInfo?.releasePermission()
imageAddedListener = null
}
interface OnImageAddedListener {
fun onAdded(imageUri: Uri): Boolean
}
} | apache-2.0 | f31f7da449090cb022098c0a399a79a8 | 34.818182 | 126 | 0.702575 | 4.89698 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/codegen/controlflow/for_loops_nested.kt | 1 | 1112 | package codegen.controlflow.for_loops_nested
import kotlin.test.*
@Test fun runTest() {
// Simple
for (i in 0..2) {
for (j in 0..2) {
print("$i$j ")
}
}
println()
// Break
l1@for (i in 0..2) {
l2@for (j in 0..2) {
print("$i$j ")
if (j == 1) break
}
}
println()
l1@for (i in 0..2) {
l2@for (j in 0..2) {
print("$i$j ")
if (j == 1) break@l2
}
}
println()
l1@for (i in 0..2) {
l2@for (j in 0..2) {
print("$i$j ")
if (j == 1) break@l1
}
}
println()
// Continue
l1@for (i in 0..2) {
l2@for (j in 0..2) {
if (j == 1) continue
print("$i$j ")
}
}
println()
l1@for (i in 0..2) {
l2@for (j in 0..2) {
if (j == 1) continue@l2
print("$i$j ")
}
}
println()
l1@for (i in 0..2) {
l2@for (j in 0..2) {
if (j == 1) continue@l1
print("$i$j ")
}
}
println()
} | apache-2.0 | f7b46b0fe2d9b0bf4896edc857372e27 | 16.666667 | 44 | 0.353417 | 2.997305 | false | false | false | false |
FanDevs/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/modules/awards/item/ItemAwardsPresenter.kt | 2 | 4108 | package ru.fantlab.android.ui.modules.awards.item
import android.view.View
import io.reactivex.Single
import io.reactivex.functions.Consumer
import ru.fantlab.android.data.dao.model.Awards
import ru.fantlab.android.data.dao.model.Nomination
import ru.fantlab.android.data.dao.model.Translator
import ru.fantlab.android.data.dao.response.AuthorResponse
import ru.fantlab.android.data.dao.response.PersonAwardsResponse
import ru.fantlab.android.data.dao.response.TranslatorResponse
import ru.fantlab.android.data.dao.response.WorkResponse
import ru.fantlab.android.provider.rest.*
import ru.fantlab.android.provider.storage.DbProvider
import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter
class ItemAwardsPresenter : BasePresenter<ItemAwardsMvp.View>(),
ItemAwardsMvp.Presenter {
override fun getWorkAwards(workId: Int) {
makeRestCall(
getWorkAwardsInternal(workId).toObservable(),
Consumer { nominations ->
sendToView { it.onInitViews(nominations) }
}
)
}
private fun getWorkAwardsInternal(workId: Int) =
getWorkAwardsFromServer(workId)
.onErrorResumeNext {
getWorkAwardsFromDb(workId)
}
.onErrorResumeNext { ext -> Single.error(ext) }
.doOnError { err -> sendToView { it.showErrorMessage(err.message) } }
private fun getWorkAwardsFromServer(workId: Int):
Single<Awards> =
DataManager.getWork(workId, showAwards = true)
.map { getAwardsFromWork(it) }
private fun getWorkAwardsFromDb(workId: Int):
Single<Awards> =
DbProvider.mainDatabase
.responseDao()
.get(getWorkPath(workId, showAwards = true))
.map { it.response }
.map { WorkResponse.Deserializer().deserialize(it) }
.map { getAwardsFromWork(it) }
private fun getAwardsFromWork(response: WorkResponse): Awards? = response.awards
override fun getAuthorAwards(authorId: Int) {
makeRestCall(
getAuthorAwardsInternal(authorId).toObservable(),
Consumer { nominations ->
sendToView { it.onInitViews(nominations) }
}
)
}
private fun getAuthorAwardsInternal(authorId: Int) =
getAuthorAwardsFromServer(authorId)
.onErrorResumeNext {
getAuthorAwardsFromDb(authorId)
}
.onErrorResumeNext { ext -> Single.error(ext) }
.doOnError { err -> sendToView { it.showErrorMessage(err.message) } }
private fun getAuthorAwardsFromServer(authorId: Int):
Single<Awards> =
DataManager.getPersonAwards(authorId, "autor")
.map { getAwardsFromPerson(it) }
private fun getAuthorAwardsFromDb(authorId: Int):
Single<Awards> =
DbProvider.mainDatabase
.responseDao()
.get(getPersonAwardsPath(authorId, "autor"))
.map { it.response }
.map { PersonAwardsResponse.Deserializer().deserialize(it) }
.map { getAwardsFromPerson(it) }
override fun getTranslatorAwards(translatorId: Int) {
makeRestCall(
getTranslatorAwardsInternal(translatorId).toObservable(),
Consumer { nominations ->
sendToView { it.onInitViews(nominations) }
}
)
}
private fun getTranslatorAwardsInternal(translatorId: Int) =
getTranslatorAwardsFromServer(translatorId)
.onErrorResumeNext {
getTranslatorAwardsFromDb(translatorId)
}
.onErrorResumeNext { ext -> Single.error(ext) }
.doOnError { err -> sendToView { it.showErrorMessage(err.message) } }
private fun getTranslatorAwardsFromServer(translatorId: Int):
Single<Awards> =
DataManager.getPersonAwards(translatorId, "translator")
.map { getAwardsFromPerson(it) }
private fun getTranslatorAwardsFromDb(translatorId: Int):
Single<Awards> =
DbProvider.mainDatabase
.responseDao()
.get(getPersonAwardsPath(translatorId, "translator"))
.map { it.response }
.map { PersonAwardsResponse.Deserializer().deserialize(it) }
.map { getAwardsFromPerson(it) }
private fun getAwardsFromPerson(response: PersonAwardsResponse): Awards? {
var res = Awards(arrayListOf(), arrayListOf())
response.awards.forEach { nomination ->
if (nomination.isWinner == 1) {
res.wins.add(nomination)
} else {
res.nominations.add(nomination)
}
}
return res
}
} | mit | ce9f652d8a40b8ce4eae5b3e4ee4dd03 | 31.611111 | 81 | 0.734664 | 4.01564 | false | false | false | false |
AndroidX/androidx | room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/ksp/KspAnnotated.kt | 3 | 9317 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.compiler.processing.ksp
import androidx.room.compiler.processing.InternalXAnnotated
import androidx.room.compiler.processing.XAnnotation
import androidx.room.compiler.processing.XAnnotationBox
import androidx.room.compiler.processing.unwrapRepeatedAnnotationsFromContainer
import com.google.devtools.ksp.symbol.AnnotationUseSiteTarget
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSAnnotation
import com.google.devtools.ksp.symbol.KSTypeAlias
import java.lang.annotation.ElementType
import kotlin.reflect.KClass
internal sealed class KspAnnotated(
val env: KspProcessingEnv
) : InternalXAnnotated {
abstract fun annotations(): Sequence<KSAnnotation>
private fun <T : Annotation> findAnnotations(annotation: KClass<T>): Sequence<KSAnnotation> {
return annotations().filter { it.isSameAnnotationClass(annotation) }
}
override fun getAllAnnotations(): List<XAnnotation> {
return annotations().map { ksAnnotated ->
KspAnnotation(env, ksAnnotated)
}.flatMap { annotation ->
annotation.unwrapRepeatedAnnotationsFromContainer() ?: listOf(annotation)
}.toList()
}
override fun <T : Annotation> getAnnotations(
annotation: KClass<T>,
containerAnnotation: KClass<out Annotation>?
): List<XAnnotationBox<T>> {
// we'll try both because it can be the container or the annotation itself.
// try container first
if (containerAnnotation != null) {
// if container also repeats, this won't work but we don't have that use case
findAnnotations(containerAnnotation).firstOrNull()?.let {
return KspAnnotationBox(
env = env,
annotation = it,
annotationClass = containerAnnotation.java,
).getAsAnnotationBoxArray<T>("value").toList()
}
}
// didn't find anything with the container, try the annotation class
return findAnnotations(annotation).map {
KspAnnotationBox(
env = env,
annotationClass = annotation.java,
annotation = it
)
}.toList()
}
override fun hasAnnotationWithPackage(pkg: String): Boolean {
return annotations().any {
it.annotationType.resolve().declaration.qualifiedName?.getQualifier() == pkg
}
}
override fun hasAnnotation(
annotation: KClass<out Annotation>,
containerAnnotation: KClass<out Annotation>?
): Boolean {
return annotations().any {
it.isSameAnnotationClass(annotation) ||
(containerAnnotation != null && it.isSameAnnotationClass(containerAnnotation))
}
}
private class KSAnnotatedDelegate(
env: KspProcessingEnv,
private val delegate: KSAnnotated,
private val useSiteFilter: UseSiteFilter
) : KspAnnotated(env) {
override fun annotations(): Sequence<KSAnnotation> {
return delegate.annotations.filter {
useSiteFilter.accept(env, it)
}
}
}
private class NotAnnotated(env: KspProcessingEnv) : KspAnnotated(env) {
override fun annotations(): Sequence<KSAnnotation> {
return emptySequence()
}
}
/**
* Annotation use site filter
*
* https://kotlinlang.org/docs/annotations.html#annotation-use-site-targets
*/
interface UseSiteFilter {
fun accept(env: KspProcessingEnv, annotation: KSAnnotation): Boolean
private class Impl(
val acceptedSiteTarget: AnnotationUseSiteTarget,
val acceptedTarget: AnnotationTarget,
private val acceptNoTarget: Boolean = true,
) : UseSiteFilter {
override fun accept(env: KspProcessingEnv, annotation: KSAnnotation): Boolean {
val useSiteTarget = annotation.useSiteTarget
val annotationTargets = annotation.getDeclaredTargets(env)
return if (useSiteTarget != null) {
acceptedSiteTarget == useSiteTarget
} else if (annotationTargets.isNotEmpty()) {
annotationTargets.contains(acceptedTarget)
} else {
acceptNoTarget
}
}
}
companion object {
val NO_USE_SITE = object : UseSiteFilter {
override fun accept(env: KspProcessingEnv, annotation: KSAnnotation): Boolean {
return annotation.useSiteTarget == null
}
}
val NO_USE_SITE_OR_FIELD: UseSiteFilter = Impl(
acceptedSiteTarget = AnnotationUseSiteTarget.FIELD,
acceptedTarget = AnnotationTarget.FIELD
)
val NO_USE_SITE_OR_METHOD_PARAMETER: UseSiteFilter = Impl(
acceptedSiteTarget = AnnotationUseSiteTarget.PARAM,
acceptedTarget = AnnotationTarget.VALUE_PARAMETER
)
val NO_USE_SITE_OR_GETTER: UseSiteFilter = Impl(
acceptedSiteTarget = AnnotationUseSiteTarget.GET,
acceptedTarget = AnnotationTarget.PROPERTY_GETTER
)
val NO_USE_SITE_OR_SETTER: UseSiteFilter = Impl(
acceptedSiteTarget = AnnotationUseSiteTarget.SET,
acceptedTarget = AnnotationTarget.PROPERTY_SETTER
)
val NO_USE_SITE_OR_SET_PARAM: UseSiteFilter = Impl(
acceptedSiteTarget = AnnotationUseSiteTarget.SETPARAM,
acceptedTarget = AnnotationTarget.PROPERTY_SETTER
)
val FILE: UseSiteFilter = Impl(
acceptedSiteTarget = AnnotationUseSiteTarget.FILE,
acceptedTarget = AnnotationTarget.FILE,
acceptNoTarget = false
)
private fun KSAnnotation.getDeclaredTargets(
env: KspProcessingEnv
): Set<AnnotationTarget> {
val annotationDeclaration = this.annotationType.resolve().declaration
val kotlinTargets = annotationDeclaration.annotations.firstOrNull {
it.isSameAnnotationClass(kotlin.annotation.Target::class)
}?.let { targetAnnotation ->
KspAnnotation(env, targetAnnotation)
.asAnnotationBox(kotlin.annotation.Target::class.java)
.value.allowedTargets
}?.toSet() ?: emptySet()
val javaTargets = annotationDeclaration.annotations.firstOrNull {
it.isSameAnnotationClass(java.lang.annotation.Target::class)
}?.let { targetAnnotation ->
KspAnnotation(env, targetAnnotation)
.asAnnotationBox(java.lang.annotation.Target::class.java)
.value.value.toList()
}?.mapNotNull { it.toAnnotationTarget() }?.toSet() ?: emptySet()
return kotlinTargets + javaTargets
}
private fun ElementType.toAnnotationTarget() = when (this) {
ElementType.TYPE -> AnnotationTarget.CLASS
ElementType.FIELD -> AnnotationTarget.FIELD
ElementType.METHOD -> AnnotationTarget.FUNCTION
ElementType.PARAMETER -> AnnotationTarget.VALUE_PARAMETER
ElementType.CONSTRUCTOR -> AnnotationTarget.CONSTRUCTOR
ElementType.LOCAL_VARIABLE -> AnnotationTarget.LOCAL_VARIABLE
ElementType.ANNOTATION_TYPE -> AnnotationTarget.ANNOTATION_CLASS
ElementType.TYPE_PARAMETER -> AnnotationTarget.TYPE_PARAMETER
ElementType.TYPE_USE -> AnnotationTarget.TYPE
else -> null
}
}
}
companion object {
fun create(
env: KspProcessingEnv,
delegate: KSAnnotated?,
filter: UseSiteFilter
): KspAnnotated {
return delegate?.let {
KSAnnotatedDelegate(env, it, filter)
} ?: NotAnnotated(env)
}
internal fun KSAnnotation.isSameAnnotationClass(
annotationClass: KClass<out Annotation>
): Boolean {
var declaration = annotationType.resolve().declaration
while (declaration is KSTypeAlias) {
declaration = declaration.type.resolve().declaration
}
val qualifiedName = declaration.qualifiedName?.asString() ?: return false
return qualifiedName == annotationClass.qualifiedName
}
}
} | apache-2.0 | 42b4d54978118857a32f5cd2a831ce22 | 40.784753 | 97 | 0.621337 | 5.776193 | false | false | false | false |
smmribeiro/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/extensions/common/BaseStylesExtension.kt | 2 | 1973 | // Copyright 2000-2020 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 org.intellij.plugins.markdown.extensions.common
import com.intellij.openapi.project.Project
import org.intellij.plugins.markdown.extensions.MarkdownBrowserPreviewExtension
import org.intellij.plugins.markdown.settings.MarkdownSettings
import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanel
import org.intellij.plugins.markdown.ui.preview.PreviewLAFThemeStyles
import org.intellij.plugins.markdown.ui.preview.ResourceProvider
import java.io.File
internal class BaseStylesExtension(private val project: Project?) : MarkdownBrowserPreviewExtension, ResourceProvider {
override val priority = MarkdownBrowserPreviewExtension.Priority.BEFORE_ALL
override val styles: List<String> = listOf("baseStyles/default.css", COLORS_CSS_FILENAME)
override val resourceProvider: ResourceProvider = this
override fun loadResource(resourceName: String): ResourceProvider.Resource? {
if (resourceName == COLORS_CSS_FILENAME) {
return ResourceProvider.Resource(PreviewLAFThemeStyles.createStylesheet().toByteArray())
}
val settings = project?.let(MarkdownSettings::getInstance)
val path = settings?.customStylesheetPath.takeIf { settings?.useCustomStylesheetPath == true }
return when (path) {
null -> ResourceProvider.loadInternalResource(BaseStylesExtension::class, resourceName)
else -> ResourceProvider.loadExternalResource(File(path))
}
}
override fun canProvide(resourceName: String): Boolean = resourceName in styles
override fun dispose() = Unit
class Provider: MarkdownBrowserPreviewExtension.Provider {
override fun createBrowserExtension(panel: MarkdownHtmlPanel): MarkdownBrowserPreviewExtension {
return BaseStylesExtension(panel.project)
}
}
companion object {
private const val COLORS_CSS_FILENAME = "baseStyles/colors.css"
}
}
| apache-2.0 | 6c272938e564034dc7e62af14dc7896b | 43.840909 | 140 | 0.795236 | 4.944862 | false | false | false | false |
googlearchive/android-RuntimePermissions | kotlinApp/app/src/main/java/com/example/android/system/runtimepermissions/extensions/AppCompatActivityExts.kt | 3 | 1459 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.system.runtimepermissions.extensions
import android.content.pm.PackageManager
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AppCompatActivity
fun AppCompatActivity.isPermissionGranted(permission: String) =
ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
fun AppCompatActivity.shouldShowPermissionRationale(permission: String) =
ActivityCompat.shouldShowRequestPermissionRationale(this, permission)
fun AppCompatActivity.requestPermission(permission: String, requestId: Int) =
ActivityCompat.requestPermissions(this, arrayOf(permission), requestId)
fun AppCompatActivity.batchRequestPermissions(permissions: Array<String>, requestId: Int) =
ActivityCompat.requestPermissions(this, permissions, requestId) | apache-2.0 | fd0299ee1e72b0029ad417a678e34df2 | 44.625 | 97 | 0.790953 | 4.815182 | false | false | false | false |
smmribeiro/intellij-community | platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/test/JavaTestProjectModelBuilder.kt | 9 | 1648 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.externalSystem.test
import com.intellij.platform.externalSystem.testFramework.*
import com.intellij.externalSystem.JavaProjectData
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.pom.java.LanguageLevel
class JavaProject : AbstractNode<JavaProjectData>("javaProject") {
var compileOutputPath: String
get() = props["compileOutputPath"]!!
set(value) {
props["compileOutputPath"] = value
}
var languageLevel: LanguageLevel?
get() = props["languageLevel"]?.run { LanguageLevel.valueOf(this) }
set(value) {
if (value == null) props.remove("languageLevel")
else props["languageLevel"] = value.name
}
var targetBytecodeVersion: String?
get() = props["targetBytecodeVersion"]
set(value) {
if (value == null) props.remove("targetBytecodeVersion")
else props["targetBytecodeVersion"] = value
}
override fun createDataNode(parentData: Any?): DataNode<JavaProjectData> {
val javaProjectData = JavaProjectData(systemId, compileOutputPath, languageLevel, targetBytecodeVersion)
return DataNode(JavaProjectData.KEY, javaProjectData, null)
}
}
fun Project.javaProject(compileOutputPath: String,
languageLevel: LanguageLevel? = null,
targetBytecodeVersion: String? = null) =
initChild(JavaProject()) {
this.compileOutputPath = compileOutputPath
this.languageLevel = languageLevel
this.targetBytecodeVersion = targetBytecodeVersion
}
| apache-2.0 | eaa355f45d738858ba3ea8993914b311 | 38.238095 | 120 | 0.728762 | 4.804665 | false | false | false | false |
junerver/CloudNote | app/src/main/java/com/junerver/cloudnote/ui/fragment/NoteFragment.kt | 1 | 10540 | package com.junerver.cloudnote.ui.fragment
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.drakeet.multitype.MultiTypeAdapter
import com.junerver.cloudnote.net.BmobMethods
import com.edusoa.ideallecturer.createJsonRequestBody
import com.edusoa.ideallecturer.fetchNetwork
import com.edusoa.ideallecturer.toBean
import com.edusoa.ideallecturer.toJson
import com.elvishew.xlog.XLog
import com.idealworkshops.idealschool.utils.SpUtils
import com.junerver.cloudnote.Constants
import com.junerver.cloudnote.R
import com.junerver.cloudnote.adapter.NoteViewBinder
import com.junerver.cloudnote.bean.*
import com.junerver.cloudnote.databinding.FragmentNoteBinding
import com.junerver.cloudnote.db.NoteUtils
import com.junerver.cloudnote.ui.activity.EditNoteActivity
import com.junerver.cloudnote.utils.NetUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import java.util.*
/**
* A simple [Fragment] subclass.
*/
class NoteFragment : BaseFragment() {
private var _binding: FragmentNoteBinding? = null
private val binding get() = _binding!!
private lateinit var mLayoutManager: LinearLayoutManager
private val adapter = MultiTypeAdapter()
private val items = ArrayList<Any>()
private lateinit var mContext: Context
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentNoteBinding.inflate(inflater, container, false)
mContext = requireContext()
init()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
XLog.d("自动同步一次")
syncToDb()
}
private fun init() {
val binder = NoteViewBinder()
binder.setLongClickListener { item ->
val builder: AlertDialog.Builder = AlertDialog.Builder(mContext)
builder.setTitle("确认要删除这个笔记么?")
builder.setPositiveButton(
"确认"
) { _, _ ->
if (NetUtils.isConnected(mContext)) {
lifecycleScope.launch {
//云端删除
fetchNetwork {
doNetwork {
BmobMethods.INSTANCE.delNoteById(item.objId)
}
onSuccess {
val delResp = it.toBean<DelResp>()
//本地删除
item.delete()
listAllFromDb()
}
onHttpError { errorBody, errorMsg, code ->
errorBody?.let {
val bean = it.toBean<ErrorResp>()
if (code == 101) {
//云端没有该对象
item.delete()
} else {
item.isLocalDel = true
item.saveOrUpdate("objId = ?", item.objId)
}
listAllFromDb()
}
}
}
}
} else {
item.isLocalDel = true
item.saveOrUpdate("objId = ?", item.objId)
listAllFromDb()
}
}
builder.setNegativeButton("取消", null)
builder.show()
}
adapter.register(binder)
binding.rvList.adapter = adapter
//设置固定大小
binding.rvList.setHasFixedSize(true)
//创建线性布局
mLayoutManager = LinearLayoutManager(activity)
//垂直方向
mLayoutManager.orientation = RecyclerView.VERTICAL
//给RecyclerView设置布局管理器
binding.rvList.layoutManager = mLayoutManager
adapter.items = items
//同步按钮点击事件
binding.ivSync.setOnClickListener {
binding.ivSync.startAnimation(
//动画效果
AnimationUtils.loadAnimation(
activity,
R.anim.anim_sync
)
)
syncToDb()
}
binding.fabAddNote.setOnClickListener {
startActivity(Intent(activity, EditNoteActivity::class.java))
}
listAllFromDb()
}
private fun syncToDb() {
lifecycleScope.launch {
//sync to db
flow {
val map = mapOf("userObjId" to SpUtils.decodeString(Constants.SP_USER_ID))
val resp = BmobMethods.INSTANCE.getAllNoteByUserId(map.toJson())
emit(resp)
}.catch { e ->
XLog.e(e)
}.flatMapConcat {
val allNote = it.toBean<GetAllNoteResp>()
allNote.results.asFlow()
}.onEach { note ->
//云端的每一条笔记
val objId = note.objectId
//根据bmob的objid查表
val dbBean = NoteUtils.queryNoteById(objId)
if (dbBean == null) {
//本地没有次数据 新建本地数据并保存数据库
val entity = note.toEntity()
entity.save()
XLog.d("本地没有该数据 新建\n$entity")
}
//存在本地对象 对比是否跟新 or 删除
dbBean?.let {
if (it.isLocalDel) {
//本地删除
val resp = BmobMethods.INSTANCE.delNoteById(it.objId)
if (resp.contains("ok")) {
//远端删除成功 本地删除
it.delete()
XLog.d("远端删除成功 本地删除\n$resp")
}
return@let
}
//未本地删除对比数据相互更新
when {
note.updatedTime > it.updatedTime -> {
//云端内容更新更新本地数据
it.update(note)
XLog.d("使用云端数据更新本地数据库\n$it\n$note")
}
note.updatedTime < it.updatedTime -> {
//云端数据小于本地 更新云端
note.update(it)
val resp = BmobMethods.INSTANCE.putNoteById(
objId,
note.toJson(excludeFields = Constants.DEFAULT_EXCLUDE_FIELDS)
.createJsonRequestBody()
)
val putResp = resp.toBean<PutResp>()
XLog.d("使用本地数据更新云端数据 \n$it\n$note")
}
else -> {
//数据相同 do nothing
XLog.d("本地数据与云端数据相同\n$it\n$note")
return@let
}
}
it.isSync = true
it.save()
}
}.flowOn(Dispatchers.IO).onCompletion {
//完成时调用与末端流操作符处于同一个协程上下文范围
XLog.d("Bmob☁️同步执行完毕,开始同步本地数据到云端")
syncToBmob()
}.collect {
}
}
}
//同步本地其他数据到云端
private suspend fun syncToBmob() {
//未同步的即本地有而云端无
NoteUtils.listNotSync().asFlow()
.onEach {
XLog.d(it)
if (it.objId.isEmpty()) {
//本地有云端无 本地无objId 直接上传
val note = it.toBmob()
val resp = BmobMethods.INSTANCE.postNote(
note.toJson(excludeFields = Constants.DEFAULT_EXCLUDE_FIELDS)
.createJsonRequestBody()
)
val postResp = resp.toBean<PostResp>()
//保存objectId
it.objId = postResp.objectId
XLog.d("本地有云端无 新建数据")
} else {
//云端同步后 本地不可能出现本地有记录,且存在云端objid,但是没有和云端同步
// 这种情况只可能是云端手动删除了记录,但是本地没有同步,
// 即一个账号登录了两个客户端,但是在一个客户端中对该记录进行了删除,在另一个客户端中还存在本地记录
//此情况可以加入特殊标记 isCloudDel
it.isCloudDel = true
XLog.d("不太可能出现的一种情况\n$it")
}
it.isSync = true
it.save()
}.flowOn(Dispatchers.IO).onCompletion {
//完成时调用与末端流操作符处于同一个协程上下文范围
listAllFromDb()
}.collect {
XLog.d(it)
}
}
//列出本地数据
private fun listAllFromDb() {
lifecycleScope.launch {
val dbwork = async(Dispatchers.IO) {
NoteUtils.listAll()
}
val list = dbwork.await()
items.clear()
items.addAll(list)
adapter.notifyDataSetChanged()
}
}
override fun onResume() {
super.onResume()
listAllFromDb()
}
} | apache-2.0 | 8f8824da2a1ea6ed6f0e82992500cab5 | 34.883895 | 93 | 0.487265 | 5.095745 | false | false | false | false |
mglukhikh/intellij-community | platform/configuration-store-impl/src/ExportSettingsAction.kt | 1 | 11841 | /*
* Copyright 2000-2015 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 com.intellij.configurationStore
import com.intellij.AbstractBundle
import com.intellij.CommonBundle
import com.intellij.ide.IdeBundle
import com.intellij.ide.actions.ImportSettingsFilenameFilter
import com.intellij.ide.actions.ShowFilePathAction
import com.intellij.ide.plugins.IdeaPluginDescriptor
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.components.*
import com.intellij.openapi.components.impl.ServiceManagerImpl
import com.intellij.openapi.components.impl.stores.StoreUtil
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.options.OptionsBundle
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.util.PlatformUtils
import com.intellij.util.ReflectionUtil
import com.intellij.util.containers.putValue
import com.intellij.util.io.*
import gnu.trove.THashMap
import gnu.trove.THashSet
import java.io.IOException
import java.io.OutputStream
import java.io.OutputStreamWriter
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
private class ExportSettingsAction : AnAction(), DumbAware {
override fun actionPerformed(e: AnActionEvent?) {
ApplicationManager.getApplication().saveSettings()
val dialog = ChooseComponentsToExportDialog(getExportableComponentsMap(true, true), true,
IdeBundle.message("title.select.components.to.export"),
IdeBundle.message(
"prompt.please.check.all.components.to.export"))
if (!dialog.showAndGet()) {
return
}
val markedComponents = dialog.exportableComponents
if (markedComponents.isEmpty()) {
return
}
val exportFiles = markedComponents.mapTo(THashSet()) { it.file }
val saveFile = dialog.exportFile
try {
if (saveFile.exists() && Messages.showOkCancelDialog(
IdeBundle.message("prompt.overwrite.settings.file", saveFile.toString()),
IdeBundle.message("title.file.already.exists"), Messages.getWarningIcon()) != Messages.OK) {
return
}
exportSettings(exportFiles, saveFile.outputStream(), FileUtilRt.toSystemIndependentName(PathManager.getConfigPath()))
ShowFilePathAction.showDialog(getEventProject(e), IdeBundle.message("message.settings.exported.successfully"),
IdeBundle.message("title.export.successful"), saveFile.toFile(), null)
}
catch (e1: IOException) {
Messages.showErrorDialog(IdeBundle.message("error.writing.settings", e1.toString()), IdeBundle.message("title.error.writing.file"))
}
}
}
// not internal only to test
fun exportSettings(exportFiles: Set<Path>, out: OutputStream, configPath: String) {
val zipOut = MyZipOutputStream(out)
try {
val writtenItemRelativePaths = THashSet<String>()
for (file in exportFiles) {
if (file.exists()) {
val relativePath = FileUtilRt.getRelativePath(configPath, file.toAbsolutePath().systemIndependentPath, '/')!!
ZipUtil.addFileOrDirRecursively(zipOut, null, file.toFile(), relativePath, null, writtenItemRelativePaths)
}
}
exportInstalledPlugins(zipOut)
val zipEntry = ZipEntry(ImportSettingsFilenameFilter.SETTINGS_JAR_MARKER)
zipOut.putNextEntry(zipEntry)
zipOut.closeEntry()
}
finally {
zipOut.doClose()
}
}
private class MyZipOutputStream(out: OutputStream) : ZipOutputStream(out) {
override fun close() {
}
fun doClose() {
super.close()
}
}
data class ExportableItem(val file: Path, val presentableName: String, val roamingType: RoamingType = RoamingType.DEFAULT)
private fun exportInstalledPlugins(zipOut: MyZipOutputStream) {
val plugins = ArrayList<String>()
for (descriptor in PluginManagerCore.getPlugins()) {
if (!descriptor.isBundled && descriptor.isEnabled) {
plugins.add(descriptor.pluginId.idString)
}
}
if (plugins.isEmpty()) {
return
}
val e = ZipEntry(PluginManager.INSTALLED_TXT)
zipOut.putNextEntry(e)
try {
PluginManagerCore.writePluginsList(plugins, OutputStreamWriter(zipOut, CharsetToolkit.UTF8_CHARSET))
}
finally {
zipOut.closeEntry()
}
}
// onlyPaths - include only specified paths (relative to config dir, ends with "/" if directory)
fun getExportableComponentsMap(onlyExisting: Boolean,
computePresentableNames: Boolean,
storageManager: StateStorageManager = ApplicationManager.getApplication().stateStore.stateStorageManager,
onlyPaths: Set<String>? = null): Map<Path, List<ExportableItem>> {
val result = LinkedHashMap<Path, MutableList<ExportableItem>>()
@Suppress("DEPRECATION")
val processor = { component: ExportableComponent ->
for (file in component.exportFiles) {
val item = ExportableItem(file.toPath(), component.presentableName, RoamingType.DEFAULT)
result.putValue(item.file, item)
}
}
@Suppress("DEPRECATION")
ApplicationManager.getApplication().getComponents(ExportableApplicationComponent::class.java).forEach(processor)
@Suppress("DEPRECATION")
ServiceBean.loadServicesFromBeans(ExportableComponent.EXTENSION_POINT, ExportableComponent::class.java).forEach(processor)
val configPath = storageManager.expandMacros(ROOT_CONFIG)
fun isSkipFile(file: Path): Boolean {
if (onlyPaths != null) {
var relativePath = FileUtilRt.getRelativePath(configPath, file.systemIndependentPath, '/')!!
if (!file.fileName.toString().contains('.') && !file.isFile()) {
relativePath += '/'
}
if (!onlyPaths.contains(relativePath)) {
return true
}
}
return onlyExisting && !file.exists()
}
if (onlyExisting || onlyPaths != null) {
result.keys.removeAll(::isSkipFile)
}
val fileToContent = THashMap<Path, String>()
ServiceManagerImpl.processAllImplementationClasses(ApplicationManager.getApplication() as ApplicationImpl, { aClass, pluginDescriptor ->
val stateAnnotation = StoreUtil.getStateSpec(aClass)
@Suppress("DEPRECATION")
if (stateAnnotation == null || stateAnnotation.name.isEmpty() || ExportableComponent::class.java.isAssignableFrom(aClass)) {
return@processAllImplementationClasses true
}
val storage = stateAnnotation.storages.sortByDeprecated().firstOrNull() ?: return@processAllImplementationClasses true
if (!(storage.roamingType != RoamingType.DISABLED && storage.storageClass == StateStorage::class && !storage.path.isEmpty())) {
return@processAllImplementationClasses true
}
var additionalExportFile: Path? = null
val additionalExportPath = stateAnnotation.additionalExportFile
if (additionalExportPath.isNotEmpty()) {
// backward compatibility - path can contain macro
if (additionalExportPath[0] == '$') {
additionalExportFile = Paths.get(storageManager.expandMacros(additionalExportPath))
}
else {
additionalExportFile = Paths.get(storageManager.expandMacros(ROOT_CONFIG), additionalExportPath)
}
if (isSkipFile(additionalExportFile)) {
additionalExportFile = null
}
}
val file = Paths.get(storageManager.expandMacros(storage.path))
val isFileIncluded = !isSkipFile(file)
if (isFileIncluded || additionalExportFile != null) {
if (computePresentableNames && onlyExisting && additionalExportFile == null && file.fileName.toString().endsWith(".xml")) {
val content = fileToContent.getOrPut(file) { file.readText() }
if (!content.contains("""<component name="${stateAnnotation.name}">""")) {
return@processAllImplementationClasses true
}
}
val presentableName = if (computePresentableNames) getComponentPresentableName(stateAnnotation, aClass, pluginDescriptor) else ""
if (isFileIncluded) {
result.putValue(file, ExportableItem(file, presentableName, storage.roamingType))
}
if (additionalExportFile != null) {
result.putValue(additionalExportFile, ExportableItem(additionalExportFile, "$presentableName (schemes)", RoamingType.DEFAULT))
}
}
true
})
// must be in the end - because most of SchemeManager clients specify additionalExportFile in the State spec
(SchemeManagerFactory.getInstance() as SchemeManagerFactoryBase).process {
if (it.roamingType != RoamingType.DISABLED && it.fileSpec.getOrNull(0) != '$') {
val file = Paths.get(storageManager.expandMacros(ROOT_CONFIG), it.fileSpec)
if (!result.containsKey(file) && !isSkipFile(file)) {
result.putValue(file, ExportableItem(file, it.presentableName ?: "", it.roamingType))
}
}
}
return result
}
private fun getComponentPresentableName(state: State, aClass: Class<*>, pluginDescriptor: PluginDescriptor?): String {
val presentableName = state.presentableName.java
if (presentableName != State.NameGetter::class.java) {
try {
return ReflectionUtil.newInstance(presentableName).get()
}
catch (e: Exception) {
LOG.error(e)
}
}
val defaultName = state.name
fun trimDefaultName(): String {
// Vcs.Log.App.Settings
return defaultName
.removeSuffix(".Settings")
.removeSuffix(".Settings")
}
var resourceBundleName: String?
if (pluginDescriptor is IdeaPluginDescriptor && "com.intellij" != pluginDescriptor.pluginId.idString) {
resourceBundleName = pluginDescriptor.resourceBundleBaseName
if (resourceBundleName == null) {
if (pluginDescriptor.vendor == "JetBrains") {
resourceBundleName = OptionsBundle.PATH_TO_BUNDLE
}
else {
return trimDefaultName()
}
}
}
else {
resourceBundleName = OptionsBundle.PATH_TO_BUNDLE
}
val classLoader = pluginDescriptor?.pluginClassLoader ?: aClass.classLoader
if (classLoader != null) {
val message = messageOrDefault(classLoader, resourceBundleName, defaultName)
if (message !== defaultName) {
return message
}
if (PlatformUtils.isRubyMine()) {
// ruby plugin in RubyMine has id "com.intellij", so, we cannot set "resource-bundle" in plugin.xml
return messageOrDefault(classLoader, "org.jetbrains.plugins.ruby.RBundle", defaultName)
}
}
return trimDefaultName()
}
private fun messageOrDefault(classLoader: ClassLoader, bundleName: String, defaultName: String): String {
val bundle = AbstractBundle.getResourceBundle(bundleName, classLoader) ?: return defaultName
return CommonBundle.messageOrDefault(bundle, "exportable.$defaultName.presentable.name", defaultName)
}
| apache-2.0 | c9d8f7051a29e2e6aa1ca4e72d1f11af | 37.950658 | 138 | 0.720632 | 4.954393 | false | false | false | false |
gbaldeck/vue.kt | src/kotlin/io/gbaldeck/vuekt/wrapper/Vue.kt | 1 | 4242 | package io.gbaldeck.vuekt.wrapper
interface VueCommon
fun VueCommon._name() = this::class.simpleName!!.camelToDashCase().toLowerCase()
object Vue{
infix fun component(vueComponent: VueComponent){
val component = vueComponent.asDynamic()
val ownNames = js("Object").getOwnPropertyNames(component) as Array<String>
val protoNames = js("Object").getOwnPropertyNames(component.constructor.prototype) as Array<String>
println(ownNames)
println(protoNames)
val definition = createJsObject<dynamic>()
val data = createJsObject<dynamic>()
definition.methods = createJsObject<dynamic>()
definition.computed = createJsObject<dynamic>()
definition.watches = createJsObject<dynamic>()
definition.props = arrayOf<String>().asDynamic()
val lifeCycleHooks = arrayOf("beforeCreate","created","beforeMount",
"mounted","beforeUpdate","updated","activated","deactivated","beforeDestroy","destroyed","errorCaptured")
val protoNamesList = protoNames.toMutableList()
protoNamesList.removeAll(arrayOf("constructor", "template", "elementName"))
protoNamesList.removeAll(lifeCycleHooks)
ownNames.forEach {
if(component[it] !is VueKtDelegate) {
val dataKey = stripGeneratedPostfix(it)
if(dataKey != "template" && dataKey != "elementName")
data[dataKey] = component[it]
} else {
val delegatePropertyKey = stripGeneratedPostfix(it)
when(component[it]) {
is VueComponent.Computed<*> -> {
val (propertyName, methodName) = component[delegatePropertyKey] as Pair<String, String>
definition.computed[propertyName] = component[methodName]
protoNamesList.remove(methodName)
}
is VueComponent.Watch<*> -> {
val (propertyName, propertyValue, methodName) = component[delegatePropertyKey] as Triple<String, dynamic, String>
data[propertyName] = propertyValue
definition.watches[propertyName] = component[methodName]
protoNamesList.remove(methodName)
}
is VueComponent.Ref<*> -> {
val (propertyName, refComputedFun) = component[delegatePropertyKey] as Pair<String, dynamic>
definition.computed[propertyName] = refComputedFun
}
is VueComponent.Prop<*> -> {
val propName = component[delegatePropertyKey]
definition.props.push(propName)
}
}
protoNamesList.remove(delegatePropertyKey)
}
}
protoNamesList.forEach {
definition.methods[it] = component[it]
}
definition.data = {
js("Object").assign(createJsObject(), data)
}
lifeCycleHooks.forEach {
definition[it] = component[it]
}
definition.render = component.template.render
definition.staticRenderFns = component.template.staticRenderFns
Communicator.setComponentDefinition(vueComponent.elementName, definition)
}
infix fun directive(vueDirective: VueDirective){
val directive = vueDirective.asDynamic()
val protoNames = js("Object").getOwnPropertyNames(directive.constructor.prototype) as Array<String>
val lifeCycleHooks = arrayOf("bind", "inserted", "update", "componentUpdated", "unbind")
val definition = createJsObject<dynamic>()
lifeCycleHooks.forEach {
definition[it] = directive[it]
}
Communicator.setDirectiveDefinition(vueDirective.name, definition)
}
infix fun filter(vueFilter: VueFilter){
val filter = vueFilter.asDynamic()
val filterFun = filter[vueFilter.filter.name]
Communicator.setFilterFunction(vueFilter.name, filterFun)
}
}
fun stripGeneratedPostfix(name: String): String{
if(name.matches("^[.\\S]+$postfixRegex\$")){
val subIt = name.substringBeforeLast("$")
return subIt.substringBeforeLast("_")
}
return name
}
private val postfixRegex = "_[.\\S]+[\$](?:_\\d)?"
//
//fun findSpecificNamesWithPostfix(searchArr: Array<String>, names: Array<String>): Array<String>{
// val arr = mutableListOf<String>()
//
// names.forEach {
// name ->
// val item = searchArr.find { it.matches("^$name(?:$postfixRegex)?\$") }
//
// item?.let{ arr.add(it) }
// }
//
// return arr.toTypedArray()
//}
//
| mit | 50ec2e83afe95907bfe601970e5f1cec | 31.883721 | 125 | 0.676332 | 4.50797 | false | false | false | false |
mseroczynski/CityBikes | app/src/main/kotlin/pl/ches/citybikes/presentation/screen/main/stations/StationDiffCallback.kt | 1 | 962 | package pl.ches.citybikes.presentation.screen.main.stations
import android.support.v7.util.DiffUtil
import pl.ches.citybikes.data.disk.entity.Station
/**
* @author Michał Seroczyński <[email protected]>
*/
class StationDiffCallback(private val old: List<Pair<Station, Float>>,
private val new: List<Pair<Station, Float>>) : DiffUtil.Callback() {
override fun getOldListSize(): Int = old.size
override fun getNewListSize(): Int = new.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return old[oldItemPosition].first.id == new[newItemPosition].first.id
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
// val distanceDiff = Math.abs(old[oldItemPosition].second - new[newItemPosition].second)
// return && distanceDiff < 10
return old[oldItemPosition].second.toInt() == new[newItemPosition].second.toInt()
}
} | gpl-3.0 | f27d160400fd226f87fec4ddd321e34b | 35.961538 | 94 | 0.732292 | 4.285714 | false | false | false | false |
kivensolo/UiUsingListView | module-Common/src/main/java/com/kingz/module/wanandroid/bean/CollectListBean.kt | 1 | 2418 | package com.kingz.module.wanandroid.bean
/**
* WanAndroid 用户收藏文章列表
*/
class CollectListBean {
/**
* curPage : 1
* datas : [{"apkLink": "",
"author": "MannaYang",
"chapterId": 97,
"chapterName": "音视频",
"collectInside": false,
"courseId": 13,
"desc": "",
"envelopePic": "",
"fresh": true,
"id": 8824,
"link": "https://juejin.im/post/5d42d4946fb9a06ae439d46b",
"niceDate": "22分钟前",
"origin": "",
"prefix": "",
"projectLink": "",
"publishTime": 1564713410000,
"superChapterId": 97,
"superChapterName": "多媒体技术",
"tags": [],
"title": "Android 基于MediaCodec+MediaMuxer实现音视频录制合成",
"type": 0,
"userId": -1,
"visible": 1,
"zan": 0
}, {
"apkLink": "",
"author": " coder-pig",
"chapterId": 74,
"chapterName": "反编译",
"collectInside": false,
"courseId": 13,
"desc": "",
"envelopePic": "",
"fresh": true,
"id": 8823,
"link": "https://juejin.im/post/5d42f440e51d4561e53538b6",
"niceDate": "33分钟前",
"origin": "",
"prefix": "",
"projectLink": "",
"publishTime": 1564712761000,
"superChapterId": 74,
"superChapterName": "热门专题",
"tags": [],
"title": "忘了他吧!我偷别人APP的代码养你",
"type": 0,
"userId": -1,
"visible": 1,
"zan": 0
},
.........
]
* offset : 0
* over : false
* pageCount : 342
* size : 20
* total : 6840
*/
var curPage = 0
var offset = 0
var over = false
var pageCount = 0
var size = 0
var total = 0
var datas: List<Article>? = null
override fun toString(): String {
return "CollectListBean(curPage=$curPage, collectList=$datas)"
}
} | gpl-2.0 | 6a6f1ba09261119e0ec3e46fb169d55d | 28.628205 | 74 | 0.390909 | 4.154676 | false | false | false | false |
idea4bsd/idea4bsd | platform/diff-impl/tests/com/intellij/diff/DiffTestCase.kt | 8 | 6850 | /*
* Copyright 2000-2016 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 com.intellij.diff
import com.intellij.diff.comparison.ComparisonManagerImpl
import com.intellij.diff.comparison.iterables.DiffIterableUtil
import com.intellij.diff.util.ThreeSide
import com.intellij.openapi.editor.Document
import com.intellij.openapi.progress.DumbProgressIndicator
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.util.Couple
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.testFramework.UsefulTestCase
import com.intellij.util.containers.HashMap
import com.intellij.util.text.CharSequenceSubSequence
import junit.framework.ComparisonFailure
import java.util.*
import java.util.concurrent.atomic.AtomicLong
abstract class DiffTestCase : UsefulTestCase() {
companion object {
private val DEFAULT_CHAR_COUNT = 12
private val DEFAULT_CHAR_TABLE: Map<Int, Char> = {
val map = HashMap<Int, Char>()
listOf('\n', '\n', '\t', ' ', ' ', '.', '<', '!').forEachIndexed { i, c -> map.put(i, c) }
map
}()
}
val RNG: Random = Random()
private var gotSeedException = false
val INDICATOR: ProgressIndicator = DumbProgressIndicator.INSTANCE
val MANAGER: ComparisonManagerImpl = ComparisonManagerImpl()
override fun setUp() {
super.setUp()
DiffIterableUtil.setVerifyEnabled(true)
}
override fun tearDown() {
DiffIterableUtil.setVerifyEnabled(Registry.`is`("diff.verify.iterable"))
super.tearDown()
}
//
// Assertions
//
fun assertTrue(actual: Boolean, message: String = "") {
assertTrue(message, actual)
}
fun assertEquals(expected: Any?, actual: Any?, message: String = "") {
assertEquals(message, expected, actual)
}
fun assertEquals(expected: CharSequence?, actual: CharSequence?, message: String = "") {
if (!StringUtil.equals(expected, actual)) throw ComparisonFailure(message, expected?.toString(), actual?.toString())
}
fun assertEqualsCharSequences(chunk1: CharSequence, chunk2: CharSequence, ignoreSpaces: Boolean, skipLastNewline: Boolean) {
if (ignoreSpaces) {
assertTrue(StringUtil.equalsIgnoreWhitespaces(chunk1, chunk2))
} else {
if (skipLastNewline) {
if (StringUtil.equals(chunk1, chunk2)) return
if (StringUtil.equals(stripNewline(chunk1), chunk2)) return
if (StringUtil.equals(chunk1, stripNewline(chunk2))) return
assertTrue(false)
} else {
assertTrue(StringUtil.equals(chunk1, chunk2))
}
}
}
//
// Parsing
//
fun textToReadableFormat(text: CharSequence?): String {
if (text == null) return "null"
return "'" + text.toString().replace('\n', '*').replace('\t', '+') + "'"
}
fun parseSource(string: CharSequence): String = string.toString().replace('_', '\n')
fun parseMatching(matching: String): BitSet {
val set = BitSet()
matching.filterNot { it == '.' }.forEachIndexed { i, c -> if (c != ' ') set.set(i) }
return set
}
//
// Misc
//
fun getLineCount(document: Document): Int {
return Math.max(1, document.lineCount)
}
infix fun Int.until(a: Int): IntRange = this..a - 1
//
// AutoTests
//
fun doAutoTest(seed: Long, runs: Int, test: (DebugData) -> Unit) {
RNG.setSeed(seed)
var lastSeed: Long = -1
val debugData = DebugData()
for (i in 1..runs) {
if (i % 1000 == 0) println(i)
try {
lastSeed = getCurrentSeed()
test(debugData)
debugData.reset()
} catch (e: Throwable) {
println("Seed: " + seed)
println("Runs: " + runs)
println("I: " + i)
println("Current seed: " + lastSeed)
debugData.dump()
throw e
}
}
}
fun generateText(maxLength: Int, charCount: Int, predefinedChars: Map<Int, Char>): String {
val length = RNG.nextInt(maxLength + 1)
val builder = StringBuilder(length)
for (i in 1..length) {
val rnd = RNG.nextInt(charCount)
val char = predefinedChars[rnd] ?: (rnd + 97).toChar()
builder.append(char)
}
return builder.toString()
}
fun generateText(maxLength: Int): String {
return generateText(maxLength, DEFAULT_CHAR_COUNT, DEFAULT_CHAR_TABLE)
}
fun getCurrentSeed(): Long {
if (gotSeedException) return -1
try {
val seedField = RNG.javaClass.getDeclaredField("seed")
seedField.isAccessible = true
val seedFieldValue = seedField.get(RNG) as AtomicLong
return seedFieldValue.get() xor 0x5DEECE66DL
} catch (e: Exception) {
gotSeedException = true
System.err.println("Can't get random seed: " + e.message)
return -1
}
}
private fun stripNewline(text: CharSequence): CharSequence? {
return when (StringUtil.endsWithChar(text, '\n') ) {
true -> CharSequenceSubSequence(text, 0, text.length - 1)
false -> null
}
}
class DebugData() {
private val data: MutableList<Pair<String, Any>> = ArrayList()
fun put(key: String, value: Any) {
data.add(Pair(key, value))
}
fun reset() {
data.clear()
}
fun dump() {
data.forEach { println(it.first + ": " + it.second) }
}
}
//
// Helpers
//
open class Trio<T : Any>(val data1: T, val data2: T, val data3: T) {
companion object {
fun <V : Any> from(f: (ThreeSide) -> V): Trio<V> = Trio(f(ThreeSide.LEFT), f(ThreeSide.BASE), f(ThreeSide.RIGHT))
}
fun <V : Any> map(f: (T) -> V): Trio<V> = Trio(f(data1), f(data2), f(data3))
fun <V : Any> map(f: (T, ThreeSide) -> V): Trio<V> = Trio(f(data1, ThreeSide.LEFT), f(data2, ThreeSide.BASE), f(data3, ThreeSide.RIGHT))
fun forEach(f: (T, ThreeSide) -> Unit): Unit {
f(data1, ThreeSide.LEFT)
f(data2, ThreeSide.BASE)
f(data3, ThreeSide.RIGHT)
}
operator fun invoke(side: ThreeSide): T = side.select(data1, data2, data3) as T
override fun toString(): String {
return "($data1, $data2, $data3)"
}
override fun equals(other: Any?): Boolean {
return other is Trio<*> && other.data1 == data1 && other.data2 == data2 && other.data3 == data3
}
override fun hashCode(): Int {
return data1.hashCode() * 37 * 37 + data2.hashCode() * 37 + data3.hashCode()
}
}
} | apache-2.0 | bd9fbc38a003e5c9563e07eb04b5358b | 28.277778 | 140 | 0.652117 | 3.900911 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/project/LibraryModificationTracker.kt | 1 | 4294 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.caches.project
import com.intellij.ide.highlighter.ArchiveFileType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.fileTypes.FileTypeEvent
import com.intellij.openapi.fileTypes.FileTypeListener
import com.intellij.openapi.fileTypes.FileTypeManager
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.SimpleModificationTracker
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileCopyEvent
import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.openapi.vfs.newvfs.events.VFileMoveEvent
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.util.application.getServiceSafe
class LibraryModificationTracker(project: Project) : SimpleModificationTracker() {
companion object {
@JvmStatic
fun getInstance(project: Project): LibraryModificationTracker = project.getServiceSafe()
}
init {
val disposable = KotlinPluginDisposable.getInstance(project)
val connection = project.messageBus.connect(disposable)
connection.subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
override fun after(events: List<VFileEvent>) {
events.filter(::isRelevantEvent).let { createEvents ->
if (createEvents.isNotEmpty()) {
ApplicationManager.getApplication().invokeLater {
if (!Disposer.isDisposed(disposable)) {
processBulk(createEvents) {
projectFileIndex.isInLibraryClasses(it) || isLibraryArchiveRoot(it)
}
}
}
}
}
}
override fun before(events: List<VFileEvent>) {
processBulk(events) {
projectFileIndex.isInLibraryClasses(it)
}
}
})
connection.subscribe(DumbService.DUMB_MODE, object : DumbService.DumbModeListener {
override fun enteredDumbMode() {
incModificationCount()
}
override fun exitDumbMode() {
incModificationCount()
}
})
connection.subscribe(FileTypeManager.TOPIC, object : FileTypeListener {
override fun beforeFileTypesChanged(event: FileTypeEvent) {
incModificationCount()
}
override fun fileTypesChanged(event: FileTypeEvent) {
incModificationCount()
}
})
}
private val projectFileIndex = ProjectFileIndex.SERVICE.getInstance(project)
private inline fun processBulk(events: List<VFileEvent>, check: (VirtualFile) -> Boolean) {
events.forEach { event ->
if (event.isValid) {
val file = event.file
if (file != null && check(file)) {
incModificationCount()
return
}
}
}
}
// if library points to a jar, the jar does not pass isInLibraryClasses check, so we have to perform additional check for this case
private fun isLibraryArchiveRoot(virtualFile: VirtualFile): Boolean {
if (virtualFile.fileType != ArchiveFileType.INSTANCE) return false
val archiveRoot = JarFileSystem.getInstance().getRootByLocal(virtualFile) ?: return false
return projectFileIndex.isInLibraryClasses(archiveRoot)
}
}
private fun isRelevantEvent(vFileEvent: VFileEvent) =
vFileEvent is VFileCreateEvent || vFileEvent is VFileMoveEvent || vFileEvent is VFileCopyEvent
| apache-2.0 | 72b2f45042353cb37c947bd35244e0bf | 41.098039 | 158 | 0.665347 | 5.456163 | false | false | false | false |
K0zka/kerub | src/test/kotlin/com/github/kerubistan/kerub/services/DbDumpServiceImplTest.kt | 2 | 1488 | package com.github.kerubistan.kerub.services
import com.nhaarman.mockito_kotlin.eq
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import org.infinispan.AdvancedCache
import org.infinispan.Cache
import org.infinispan.CacheSet
import org.infinispan.commons.util.CloseableIterator
import org.infinispan.manager.EmbeddedCacheManager
import org.junit.Test
import java.io.ByteArrayOutputStream
import javax.ws.rs.core.StreamingOutput
class DbDumpServiceImplTest {
@Test
fun dump() {
val cacheManager = mock<EmbeddedCacheManager>()
whenever(cacheManager.cacheNames).thenReturn(
mutableSetOf("testCache")
)
val cache = mock<Cache<Any, Any>>()
val advancedCache = mock<AdvancedCache<Any, Any>>()
whenever(cacheManager.getCache<Any, Any>(eq("testCache"))).thenReturn(cache)
whenever(cache.advancedCache).thenReturn(advancedCache)
val keys = mock<CacheSet<Any>>()
whenever(keys.iterator()).then { val keyIterator = mock<CloseableIterator<Any>>()
whenever(keyIterator.hasNext()).thenReturn(true, true, true, false)
whenever(keyIterator.next()).thenReturn("A", "B", "C")
keyIterator
}
whenever(advancedCache[eq("A")]).thenReturn("A-VALUE")
whenever(advancedCache[eq("B")]).thenReturn("B-VALUE")
whenever(advancedCache[eq("C")]).thenReturn("C-VALUE")
whenever(advancedCache.keys).thenReturn(keys)
val tar = ByteArrayOutputStream()
(DbDumpServiceImpl(cacheManager).dump().entity as StreamingOutput).write(tar)
}
} | apache-2.0 | 5c2a973c47aee8882aeb0802a46f7541 | 34.452381 | 83 | 0.770161 | 3.795918 | false | true | false | false |
jwren/intellij-community | plugins/kotlin/compiler-plugins/allopen/gradle/src/org/jetbrains/kotlin/idea/compilerPlugin/allopen/gradleJava/AllOpenGradleProjectImportHandler.kt | 1 | 1483 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.compilerPlugin.allopen.gradleJava
import org.jetbrains.kotlin.allopen.AllOpenCommandLineProcessor
import org.jetbrains.kotlin.idea.gradleTooling.model.allopen.AllOpenModel
import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.idea.gradleJava.compilerPlugin.AbstractAnnotationBasedCompilerPluginGradleImportHandler
import org.jetbrains.kotlin.idea.compilerPlugin.toJpsVersionAgnosticKotlinBundledPath
class AllOpenGradleProjectImportHandler : AbstractAnnotationBasedCompilerPluginGradleImportHandler<AllOpenModel>() {
override val compilerPluginId = AllOpenCommandLineProcessor.PLUGIN_ID
override val pluginName = "allopen"
override val annotationOptionName = AllOpenCommandLineProcessor.ANNOTATION_OPTION.optionName
override val pluginJarFileFromIdea = KotlinArtifacts.instance.allopenCompilerPlugin.toJpsVersionAgnosticKotlinBundledPath()
override val modelKey = AllOpenProjectResolverExtension.KEY
override fun getAnnotationsForPreset(presetName: String): List<String> {
for ((name, annotations) in AllOpenCommandLineProcessor.SUPPORTED_PRESETS.entries) {
if (presetName == name) {
return annotations
}
}
return super.getAnnotationsForPreset(presetName)
}
}
| apache-2.0 | b8e8df064b19e7c1eb1c08818d07f9d5 | 53.925926 | 158 | 0.807822 | 5.660305 | false | false | false | false |
jwren/intellij-community | platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/ProblemsViewProjectErrorsPanelProvider.kt | 1 | 2003 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.analysis.problemsView.toolWindow
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.ui.SimpleTextAttributes
import java.awt.event.ActionEvent
class ProblemsViewProjectErrorsPanelProvider(private val project: Project) : ProblemsViewPanelProvider {
companion object {
const val ID = "ProjectErrors"
}
private val ACTION_IDS = listOf("CompileDirty", "InspectCode")
override fun create(): ProblemsViewTab? {
val state = ProblemsViewState.getInstance(project)
val panel = ProblemsViewPanel(project, ID, state, ProblemsViewBundle.messagePointer("problems.view.project"))
panel.treeModel.root = CollectorBasedRoot(panel)
val status = panel.tree.emptyText
status.text = ProblemsViewBundle.message("problems.view.project.empty")
if (Registry.`is`("ide.problems.view.empty.status.actions")) {
val or = ProblemsViewBundle.message("problems.view.project.empty.or")
var index = 0
for (id in ACTION_IDS) {
val action = ActionUtil.getAction(id) ?: continue
val text = action.templateText
if (text.isNullOrBlank()) continue
if (index == 0) {
status.appendText(".")
status.appendLine("")
}
else {
status.appendText(" ").appendText(or).appendText(" ")
}
status.appendText(text, SimpleTextAttributes.LINK_PLAIN_ATTRIBUTES
) { event: ActionEvent? ->
ActionUtil.invokeAction(action, panel, "ProblemsView", null, null)
}
val shortcut = KeymapUtil.getFirstKeyboardShortcutText(action)
if (!shortcut.isBlank()) status.appendText(" (").appendText(shortcut).appendText(")")
index++
}
}
return panel
}
} | apache-2.0 | ea33ac694538999a862e192afd733a23 | 38.294118 | 120 | 0.702446 | 4.521445 | false | false | false | false |
androidx/androidx | fragment/fragment/src/androidTest/java/androidx/fragment/app/FragmentViewLifecycleOwnerTest.kt | 3 | 7037 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.fragment.app
import androidx.fragment.app.test.FragmentTestActivity
import androidx.fragment.app.test.TestViewModel
import androidx.fragment.app.test.ViewModelActivity
import androidx.fragment.test.R
import androidx.lifecycle.HasDefaultViewModelProviderFactory
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import androidx.testutils.withActivity
import androidx.testutils.withUse
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@SmallTest
class FragmentViewLifecycleOwnerTest {
/**
* Test representing a Non-Hilt case, in which the default factory is not overwritten at the
* Fragment level.
*/
@Test
fun defaultFactoryNotOverwritten() {
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fm = withActivity {
setContentView(R.layout.simple_container)
supportFragmentManager
}
val fragment = StrictViewFragment()
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit()
executePendingTransactions()
val defaultFactory1 = (
fragment.viewLifecycleOwner as HasDefaultViewModelProviderFactory
).defaultViewModelProviderFactory
val defaultFactory2 = (
fragment.viewLifecycleOwner as HasDefaultViewModelProviderFactory
).defaultViewModelProviderFactory
// Assure that multiple call return the same default factory
assertThat(defaultFactory1).isSameInstanceAs(defaultFactory2)
assertThat(defaultFactory1).isNotSameInstanceAs(
fragment.defaultViewModelProviderFactory
)
}
}
/**
* Test representing a Hilt case, in which the default factory is overwritten at the
* Fragment level.
*/
@Test
fun defaultFactoryOverwritten() {
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fm = withActivity {
setContentView(R.layout.simple_container)
supportFragmentManager
}
val fragment = FragmentWithFactoryOverride()
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit()
executePendingTransactions()
val defaultFactory = (
fragment.viewLifecycleOwner as HasDefaultViewModelProviderFactory
).defaultViewModelProviderFactory
assertThat(defaultFactory).isInstanceOf(FakeViewModelProviderFactory::class.java)
}
}
@Test
fun testCreateViewModelViaExtras() {
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fm = withActivity {
setContentView(R.layout.simple_container)
supportFragmentManager
}
val fragment = StrictViewFragment()
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment, "fragment")
.commit()
executePendingTransactions()
val viewLifecycleOwner = (fragment.viewLifecycleOwner as FragmentViewLifecycleOwner)
val creationViewModel = ViewModelProvider(
viewLifecycleOwner.viewModelStore,
viewLifecycleOwner.defaultViewModelProviderFactory,
viewLifecycleOwner.defaultViewModelCreationExtras
)["test", TestViewModel::class.java]
recreate()
val recreatedViewLifecycleOwner = withActivity {
supportFragmentManager.findFragmentByTag("fragment")?.viewLifecycleOwner
as FragmentViewLifecycleOwner
}
assertThat(
ViewModelProvider(recreatedViewLifecycleOwner)["test", TestViewModel::class.java]
).isSameInstanceAs(creationViewModel)
}
}
@Test
fun testCreateViewModelViaExtrasSavedState() {
withUse(ActivityScenario.launch(FragmentTestActivity::class.java)) {
val fm = withActivity {
setContentView(R.layout.simple_container)
supportFragmentManager
}
val fragment = StrictViewFragment()
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment, "fragment")
.commit()
executePendingTransactions()
val viewLifecycleOwner = (fragment.viewLifecycleOwner as FragmentViewLifecycleOwner)
val creationViewModel = ViewModelProvider(
viewLifecycleOwner.viewModelStore,
viewLifecycleOwner.defaultViewModelProviderFactory,
viewLifecycleOwner.defaultViewModelCreationExtras
)["test", ViewModelActivity.TestSavedStateViewModel::class.java]
creationViewModel.savedStateHandle["key"] = "value"
recreate()
val recreatedViewLifecycleOwner = withActivity {
supportFragmentManager.findFragmentByTag("fragment")?.viewLifecycleOwner
as FragmentViewLifecycleOwner
}
val recreateViewModel = ViewModelProvider(recreatedViewLifecycleOwner)[
"test", ViewModelActivity.TestSavedStateViewModel::class.java
]
assertThat(recreateViewModel).isSameInstanceAs(creationViewModel)
val value: String? = recreateViewModel.savedStateHandle["key"]
assertThat(value).isEqualTo("value")
}
}
class FakeViewModelProviderFactory : ViewModelProvider.Factory {
private var createCalled: Boolean = false
override fun <T : ViewModel> create(modelClass: Class<T>): T {
require(modelClass == TestViewModel::class.java)
createCalled = true
@Suppress("UNCHECKED_CAST")
return TestViewModel() as T
}
}
public class FragmentWithFactoryOverride : StrictViewFragment() {
public override fun getDefaultViewModelProviderFactory(): ViewModelProvider.Factory =
FakeViewModelProviderFactory()
}
} | apache-2.0 | 2412b29878125151f6c97ad0aedc4915 | 36.238095 | 97 | 0.663351 | 6.161996 | false | true | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/contacts/sync/CdsPermanentErrorBottomSheet.kt | 1 | 2160 | package org.thoughtcrime.securesms.contacts.sync
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.view.ContextThemeWrapper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.FragmentManager
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.FixedRoundedCornerBottomSheetDialogFragment
import org.thoughtcrime.securesms.databinding.CdsPermanentErrorBottomSheetBinding
import org.thoughtcrime.securesms.util.BottomSheetUtil
import org.thoughtcrime.securesms.util.CommunicationActions
/**
* Bottom sheet shown when CDS is in a permanent error state, preventing us from doing a sync.
*/
class CdsPermanentErrorBottomSheet : FixedRoundedCornerBottomSheetDialogFragment() {
private lateinit var binding: CdsPermanentErrorBottomSheetBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = CdsPermanentErrorBottomSheetBinding.inflate(inflater.cloneInContext(ContextThemeWrapper(inflater.context, themeResId)), container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding.learnMoreButton.setOnClickListener {
CommunicationActions.openBrowserLink(requireContext(), "https://support.signal.org/hc/articles/360007319011#android_contacts_error")
}
binding.settingsButton.setOnClickListener {
val intent = Intent().apply {
action = Intent.ACTION_VIEW
data = android.provider.ContactsContract.Contacts.CONTENT_URI
}
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(context, R.string.CdsPermanentErrorBottomSheet_no_contacts_toast, Toast.LENGTH_SHORT).show()
}
}
}
companion object {
@JvmStatic
fun show(fragmentManager: FragmentManager) {
val fragment = CdsPermanentErrorBottomSheet()
fragment.show(fragmentManager, BottomSheetUtil.STANDARD_BOTTOM_SHEET_FRAGMENT_TAG)
}
}
}
| gpl-3.0 | 7d551adf397ac428b07e32634ab92471 | 38.272727 | 151 | 0.791204 | 5.023256 | false | false | false | false |
androidx/androidx | graphics/graphics-core/src/main/java/androidx/graphics/opengl/GLThread.kt | 3 | 13745 | /*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.graphics.opengl
import android.opengl.EGL14
import android.opengl.EGLConfig
import android.opengl.EGLSurface
import android.os.Handler
import android.os.HandlerThread
import android.os.SystemClock
import android.util.Log
import android.view.Surface
import androidx.annotation.AnyThread
import androidx.annotation.WorkerThread
import androidx.graphics.opengl.GLRenderer.EGLContextCallback
import androidx.graphics.opengl.GLRenderer.RenderCallback
import androidx.graphics.opengl.egl.EGLManager
import androidx.graphics.opengl.egl.EGLSpec
import java.util.concurrent.atomic.AtomicBoolean
/**
* Thread responsible for management of EGL dependencies, setup and teardown
* of EGLSurface instances as well as delivering callbacks to draw a frame
*/
internal class GLThread(
name: String = "GLThread",
private val mEglSpecFactory: () -> EGLSpec,
private val mEglConfigFactory: EGLManager.() -> EGLConfig,
) : HandlerThread(name) {
// Accessed on internal HandlerThread
private val mIsTearingDown = AtomicBoolean(false)
private var mEglManager: EGLManager? = null
private val mSurfaceSessions = HashMap<Int, SurfaceSession>()
private var mHandler: Handler? = null
private val mEglContextCallback = HashSet<EGLContextCallback>()
override fun start() {
super.start()
mHandler = Handler(looper)
}
/**
* Adds the given [android.view.Surface] to be managed by the GLThread.
* A corresponding [EGLSurface] is created on the GLThread as well as a callback
* for rendering into the surface through [RenderCallback].
* @param surface intended to be be rendered into on the GLThread
* @param width Desired width of the [surface]
* @param height Desired height of the [surface]
* @param renderer callbacks used to create a corresponding [EGLSurface] from the
* given surface as well as render content into the created [EGLSurface]
* @return Identifier used for subsequent requests to communicate
* with the provided Surface (ex. [requestRender] or [detachSurface]
*/
@AnyThread
fun attachSurface(
token: Int,
surface: Surface?,
width: Int,
height: Int,
renderer: RenderCallback
) {
withHandler {
post(token) {
attachSurfaceSessionInternal(
SurfaceSession(token, surface, renderer).apply {
this.width = width
this.height = height
}
)
}
}
}
@AnyThread
fun resizeSurface(token: Int, width: Int, height: Int, callback: Runnable? = null) {
withHandler {
post(token) {
resizeSurfaceSessionInternal(token, width, height)
requestRenderInternal(token)
callback?.run()
}
}
}
@AnyThread
fun addEGLCallbacks(callbacks: ArrayList<EGLContextCallback>) {
withHandler {
post {
mEglContextCallback.addAll(callbacks)
mEglManager?.let {
for (callback in callbacks) {
callback.onEGLContextCreated(it)
}
}
}
}
}
@AnyThread
fun addEGLCallback(callbacks: EGLContextCallback) {
withHandler {
post {
mEglContextCallback.add(callbacks)
// If EGL dependencies are already initialized, immediately invoke
// the added callback
mEglManager?.let {
callbacks.onEGLContextCreated(it)
}
}
}
}
@AnyThread
fun removeEGLCallback(callbacks: EGLContextCallback) {
withHandler {
post {
mEglContextCallback.remove(callbacks)
}
}
}
/**
* Removes the corresponding [android.view.Surface] from management of the GLThread.
* This destroys the EGLSurface associated with this surface and subsequent requests
* to render into the surface with the provided token are ignored. Any queued request
* to render to the corresponding [SurfaceSession] that has not started yet is cancelled.
* However, if this is invoked in the middle of the frame being rendered, it will continue to
* process the current frame.
*/
@AnyThread
fun detachSurface(
token: Int,
cancelPending: Boolean,
callback: Runnable?
) {
log("dispatching request to detach surface w/ token: $token")
withHandler {
if (cancelPending) {
removeCallbacksAndMessages(token)
}
post(token) {
detachSurfaceSessionInternal(token, callback)
}
}
}
/**
* Cancel all pending requests to all currently managed [SurfaceSession] instances,
* destroy all EGLSurfaces, teardown EGLManager and quit this thread
*/
@AnyThread
fun tearDown(cancelPending: Boolean, callback: Runnable?) {
withHandler {
if (cancelPending) {
removeCallbacksAndMessages(null)
}
post {
releaseResourcesInternalAndQuit(callback)
}
mIsTearingDown.set(true)
}
}
/**
* Mark the corresponding surface session with the given token as dirty
* to schedule a call to [RenderCallback#onDrawFrame].
* If there is already a queued request to render into the provided surface with
* the specified token, this request is ignored.
*/
@AnyThread
fun requestRender(token: Int, callback: Runnable? = null) {
log("dispatching request to render for token: $token")
withHandler {
post(token) {
requestRenderInternal(token)
callback?.run()
}
}
}
/**
* Lazily creates an [EGLManager] instance from the given [mEglSpecFactory]
* used to determine the configuration. This result is cached across calls
* unless [tearDown] has been called.
*/
@WorkerThread
fun obtainEGLManager(): EGLManager =
mEglManager ?: EGLManager(mEglSpecFactory.invoke()).also {
it.initialize()
val config = mEglConfigFactory.invoke(it)
it.createContext(config)
for (callback in mEglContextCallback) {
callback.onEGLContextCreated(it)
}
mEglManager = it
}
@WorkerThread
private fun disposeSurfaceSession(session: SurfaceSession) {
val eglSurface = session.eglSurface
if (eglSurface != null && eglSurface != EGL14.EGL_NO_SURFACE) {
obtainEGLManager().eglSpec.eglDestroySurface(eglSurface)
session.eglSurface = null
}
}
/**
* Helper method to obtain the cached EGLSurface for the given [SurfaceSession],
* creating one if it does not previously exist
*/
@WorkerThread
private fun obtainEGLSurfaceForSession(session: SurfaceSession): EGLSurface? {
return if (session.eglSurface != null) {
session.eglSurface
} else {
createEGLSurfaceForSession(
session.surface,
session.width,
session.height,
session.surfaceRenderer
).also {
session.eglSurface = it
}
}
}
/**
* Helper method to create the corresponding EGLSurface from the [SurfaceSession] instance
* Consumers are expected to teardown the previously existing EGLSurface instance if it exists
*/
@WorkerThread
private fun createEGLSurfaceForSession(
surface: Surface?,
width: Int,
height: Int,
surfaceRenderer: RenderCallback
): EGLSurface? {
with(obtainEGLManager()) {
return if (surface != null) {
surfaceRenderer.onSurfaceCreated(
eglSpec,
// Successful creation of EGLManager ensures non null EGLConfig
eglConfig!!,
surface,
width,
height
)
} else {
null
}
}
}
@WorkerThread
private fun releaseResourcesInternalAndQuit(callback: Runnable?) {
val eglManager = obtainEGLManager()
for (session in mSurfaceSessions) {
disposeSurfaceSession(session.value)
}
callback?.run()
mSurfaceSessions.clear()
for (eglCallback in mEglContextCallback) {
eglCallback.onEGLContextDestroyed(eglManager)
}
mEglContextCallback.clear()
eglManager.release()
mEglManager = null
quit()
}
@WorkerThread
private fun requestRenderInternal(token: Int) {
log("requesting render for token: $token")
mSurfaceSessions[token]?.let { surfaceSession ->
val eglManager = obtainEGLManager()
val eglSurface = obtainEGLSurfaceForSession(surfaceSession)
if (eglSurface != null) {
eglManager.makeCurrent(eglSurface)
} else {
eglManager.makeCurrent(eglManager.defaultSurface)
}
val width = surfaceSession.width
val height = surfaceSession.height
if (width > 0 && height > 0) {
surfaceSession.surfaceRenderer.onDrawFrame(eglManager)
}
if (eglSurface != null) {
eglManager.swapAndFlushBuffers()
}
}
}
@WorkerThread
private fun attachSurfaceSessionInternal(surfaceSession: SurfaceSession) {
mSurfaceSessions[surfaceSession.surfaceToken] = surfaceSession
}
@WorkerThread
private fun resizeSurfaceSessionInternal(
token: Int,
width: Int,
height: Int
) {
mSurfaceSessions[token]?.let { surfaceSession ->
surfaceSession.apply {
this.width = width
this.height = height
}
disposeSurfaceSession(surfaceSession)
obtainEGLSurfaceForSession(surfaceSession)
}
}
@WorkerThread
private fun detachSurfaceSessionInternal(token: Int, callback: Runnable?) {
val session = mSurfaceSessions.remove(token)
if (session != null) {
disposeSurfaceSession(session)
}
callback?.run()
}
/**
* Helper method that issues a callback on the handler instance for this thread
* ensuring proper nullability checks are handled.
* This assumes that that [GLRenderer.start] has been called before attempts
* to interact with the corresponding Handler are made with this method
*/
private inline fun withHandler(block: Handler.() -> Unit) {
val handler = mHandler
?: throw IllegalStateException("Did you forget to call GLThread.start()?")
if (!mIsTearingDown.get()) {
block(handler)
}
}
companion object {
private const val DEBUG = true
private const val TAG = "GLThread"
internal fun log(msg: String) {
if (DEBUG) {
Log.v(TAG, msg)
}
}
}
private class SurfaceSession(
/**
* Identifier used to lookup the mapping of this surface session.
* Consumers are expected to provide this identifier to operate on the corresponding
* surface to either request a frame be rendered or to remove this Surface
*/
val surfaceToken: Int,
/**
* Target surface to render into. Can be null for situations where GL is used to render
* into a frame buffer object provided from an AHardwareBuffer instance.
* In these cases the actual surface is never used.
*/
val surface: Surface?,
/**
* Callback used to create an EGLSurface from the provided surface as well as
* render content to the surface
*/
val surfaceRenderer: RenderCallback
) {
/**
* Lazily created + cached [EGLSurface] after [RenderCallback.onSurfaceCreated]
* is invoked. This is only modified on the backing thread
*/
var eglSurface: EGLSurface? = null
/**
* Target width of the [surface]. This is only modified on the backing thread
*/
var width: Int = 0
/**
* Target height of the [surface]. This is only modified on the backing thread
*/
var height: Int = 0
}
/**
* Handler does not expose a post method that takes a token and a runnable.
* We need the token to be able to cancel pending requests so just call
* postAtTime with the default of SystemClock.uptimeMillis
*/
private fun Handler.post(token: Any?, runnable: Runnable) {
postAtTime(runnable, token, SystemClock.uptimeMillis())
}
} | apache-2.0 | 72bd5770a1b88be237ddd2a5caa84346 | 32.445255 | 98 | 0.610113 | 5.337864 | false | false | false | false |
GunoH/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/ProjectSettingsTracker.kt | 2 | 14133 | // Copyright 2000-2021 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 com.intellij.openapi.externalSystem.autoimport
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.externalSystem.autoimport.AutoImportProjectTracker.Companion.isAsyncChangesProcessing
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemModificationType.EXTERNAL
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemSettingsFilesModificationContext.Event.*
import com.intellij.openapi.externalSystem.autoimport.ExternalSystemSettingsFilesModificationContext.ReloadStatus
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ProjectEvent.*
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ProjectEvent.Companion.externalInvalidate
import com.intellij.openapi.externalSystem.autoimport.ProjectStatus.ProjectEvent.Companion.externalModify
import com.intellij.openapi.externalSystem.autoimport.changes.AsyncFilesChangesListener.Companion.subscribeOnDocumentsAndVirtualFilesChanges
import com.intellij.openapi.externalSystem.autoimport.changes.FilesChangesListener
import com.intellij.openapi.externalSystem.autoimport.changes.NewFilesListener.Companion.whenNewFilesCreated
import com.intellij.openapi.externalSystem.autoimport.settings.*
import com.intellij.openapi.externalSystem.util.calculateCrc
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.observable.operation.core.AtomicOperationTrace
import com.intellij.openapi.observable.operation.core.isOperationInProgress
import com.intellij.openapi.observable.operation.core.whenOperationFinished
import com.intellij.openapi.observable.operation.core.whenOperationStarted
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.LocalTimeCounter.currentTime
import org.jetbrains.annotations.ApiStatus
import java.nio.file.Path
import java.util.concurrent.Executor
import java.util.concurrent.atomic.AtomicReference
@ApiStatus.Internal
class ProjectSettingsTracker(
private val project: Project,
private val projectTracker: AutoImportProjectTracker,
private val backgroundExecutor: Executor,
private val projectAware: ExternalSystemProjectAware,
private val parentDisposable: Disposable
) {
private val projectStatus = ProjectStatus(debugName = "Settings ${projectAware.projectId.debugName}")
private val settingsFilesStatus = AtomicReference(SettingsFilesStatus())
private val applyChangesOperation = AtomicOperationTrace(name = "Apply changes operation")
private val settingsAsyncSupplier = SettingsFilesAsyncSupplier()
private fun calculateSettingsFilesCRC(settingsFiles: Set<String>): Map<String, Long> {
val localFileSystem = LocalFileSystem.getInstance()
return settingsFiles
.mapNotNull { localFileSystem.findFileByPath(it) }
.associate { it.path to calculateCrc(it) }
}
private fun calculateCrc(file: VirtualFile): Long {
val fileDocumentManager = FileDocumentManager.getInstance()
val document = fileDocumentManager.getCachedDocument(file)
if (document != null) return document.calculateCrc(project, projectAware.projectId.systemId, file)
return file.calculateCrc(project, projectAware.projectId.systemId)
}
fun isUpToDate() = projectStatus.isUpToDate()
fun getModificationType() = projectStatus.getModificationType()
fun getSettingsContext(): ExternalSystemSettingsFilesReloadContext {
val status = settingsFilesStatus.get()
return SettingsFilesReloadContext(status.updated, status.created, status.deleted)
}
/**
* Updates settings files status using new CRCs.
* @param isReloadJustFinished see [adjustCrc] for details
*/
private fun updateSettingsFilesStatus(
operationName: String,
newCRC: Map<String, Long>,
isReloadJustFinished: Boolean = false,
): SettingsFilesStatus {
return settingsFilesStatus.updateAndGet {
SettingsFilesStatus(it.oldCRC, newCRC)
.adjustCrc(operationName, isReloadJustFinished)
}
}
/**
* Adjusts settings files status. It allows ignoring files modifications by rules from
* external system. For example some build systems needed to ignore files updates during reload.
*
* @see ExternalSystemProjectAware.isIgnoredSettingsFileEvent
*/
private fun SettingsFilesStatus.adjustCrc(operationName: String, isReloadJustFinished: Boolean): SettingsFilesStatus {
val modificationType = getModificationType()
val isReloadInProgress = applyChangesOperation.isOperationInProgress()
val reloadStatus = when {
isReloadJustFinished -> ReloadStatus.JUST_FINISHED
isReloadInProgress -> ReloadStatus.IN_PROGRESS
else -> ReloadStatus.IDLE
}
val oldCRC = oldCRC.toMutableMap()
for (path in updated) {
val context = SettingsFilesModificationContext(UPDATE, modificationType, reloadStatus)
if (projectAware.isIgnoredSettingsFileEvent(path, context)) {
oldCRC[path] = newCRC[path]!!
}
}
for (path in created) {
val context = SettingsFilesModificationContext(CREATE, modificationType, reloadStatus)
if (projectAware.isIgnoredSettingsFileEvent(path, context)) {
oldCRC[path] = newCRC[path]!!
}
}
for (path in deleted) {
val context = SettingsFilesModificationContext(DELETE, modificationType, reloadStatus)
if (projectAware.isIgnoredSettingsFileEvent(path, context)) {
oldCRC.remove(path)
}
}
val status = SettingsFilesStatus(oldCRC, newCRC)
LOG.debug(
"[$operationName] " +
"ReloadStatus=$reloadStatus, " +
"ModificationType=$modificationType, " +
"Updated=${status.updated}, " +
"Created=${status.created}, " +
"Deleted=${status.deleted}"
)
return status
}
fun getState() = State(projectStatus.isDirty(), settingsFilesStatus.get().oldCRC.toMap())
fun loadState(state: State) {
val operationStamp = currentTime()
settingsFilesStatus.set(SettingsFilesStatus(state.settingsFiles.toMap()))
when (state.isDirty) {
true -> projectStatus.markDirty(operationStamp, EXTERNAL)
else -> projectStatus.markSynchronized(operationStamp)
}
}
fun refreshChanges() {
submitSettingsFilesStatusUpdate(
operationName = "refreshChanges",
isRefreshVfs = true,
syncEvent = ::Revert,
changeEvent = ::externalInvalidate
) {
projectTracker.scheduleChangeProcessing()
}
}
private fun submitSettingsFilesCollection(isInvalidateCache: Boolean = false, callback: (Set<String>) -> Unit) {
if (isInvalidateCache) {
settingsAsyncSupplier.invalidate()
}
settingsAsyncSupplier.supply(parentDisposable, callback)
}
private fun submitSettingsFilesRefresh(callback: (Set<String>) -> Unit) {
EdtAsyncSupplier.invokeOnEdt(::isAsyncChangesProcessing, parentDisposable) {
val fileDocumentManager = FileDocumentManager.getInstance()
fileDocumentManager.saveAllDocuments()
submitSettingsFilesCollection(isInvalidateCache = true) { settingsPaths ->
val localFileSystem = LocalFileSystem.getInstance()
val settingsFiles = settingsPaths.map { Path.of(it) }
localFileSystem.refreshNioFiles(settingsFiles, isAsyncChangesProcessing, false) {
callback(settingsPaths)
}
}
}
}
private fun submitSettingsFilesCRCCalculation(
operationName: String,
settingsPaths: Set<String>,
isMergeSameCalls: Boolean = false,
callback: (Map<String, Long>) -> Unit
) {
val builder = ReadAsyncSupplier.Builder { calculateSettingsFilesCRC(settingsPaths) }
.shouldKeepTasksAsynchronous(::isAsyncChangesProcessing)
if (isMergeSameCalls) {
builder.coalesceBy(this, operationName)
}
builder.build(backgroundExecutor)
.supply(parentDisposable, callback)
}
private fun submitSettingsFilesCollection(
isRefreshVfs: Boolean = false,
isInvalidateCache: Boolean = false,
callback: (Set<String>) -> Unit
) {
if (isRefreshVfs) {
submitSettingsFilesRefresh(callback)
}
else {
submitSettingsFilesCollection(isInvalidateCache, callback)
}
}
private fun submitSettingsFilesStatusUpdate(
operationName: String,
isMergeSameCalls: Boolean = false,
isReloadJustFinished: Boolean = false,
isInvalidateCache: Boolean = false,
isRefreshVfs: Boolean = false,
syncEvent: (Long) -> ProjectStatus.ProjectEvent,
changeEvent: ((Long) -> ProjectStatus.ProjectEvent)?,
callback: () -> Unit
) {
submitSettingsFilesCollection(isRefreshVfs, isInvalidateCache) { settingsPaths ->
val operationStamp = currentTime()
submitSettingsFilesCRCCalculation(operationName, settingsPaths, isMergeSameCalls) { newSettingsFilesCRC ->
val settingsFilesStatus = updateSettingsFilesStatus(operationName, newSettingsFilesCRC, isReloadJustFinished)
val event = if (settingsFilesStatus.hasChanges()) changeEvent else syncEvent
if (event != null) {
projectStatus.update(event(operationStamp))
}
callback()
}
}
}
fun beforeApplyChanges(
parentDisposable: Disposable,
listener: () -> Unit
) = applyChangesOperation.whenOperationStarted(parentDisposable, listener)
fun afterApplyChanges(
parentDisposable: Disposable,
listener: () -> Unit
) = applyChangesOperation.whenOperationFinished(parentDisposable, listener)
init {
projectAware.subscribe(ProjectListener(), parentDisposable)
whenNewFilesCreated(settingsAsyncSupplier::invalidate, parentDisposable)
subscribeOnDocumentsAndVirtualFilesChanges(settingsAsyncSupplier, ProjectSettingsListener(), parentDisposable)
}
data class State(var isDirty: Boolean = true, var settingsFiles: Map<String, Long> = emptyMap())
private class SettingsFilesStatus(
val oldCRC: Map<String, Long>,
val newCRC: Map<String, Long>,
) {
constructor(CRC: Map<String, Long> = emptyMap()) : this(CRC, CRC)
val updated: Set<String> by lazy {
oldCRC.keys.intersect(newCRC.keys)
.filterTo(HashSet()) { oldCRC[it] != newCRC[it] }
}
val created: Set<String> by lazy {
newCRC.keys.minus(oldCRC.keys)
}
val deleted: Set<String> by lazy {
oldCRC.keys.minus(newCRC.keys)
}
fun hasChanges() = updated.isNotEmpty() || created.isNotEmpty() || deleted.isNotEmpty()
}
private class SettingsFilesReloadContext(
override val updated: Set<String>,
override val created: Set<String>,
override val deleted: Set<String>
) : ExternalSystemSettingsFilesReloadContext
private class SettingsFilesModificationContext(
override val event: ExternalSystemSettingsFilesModificationContext.Event,
override val modificationType: ExternalSystemModificationType,
override val reloadStatus: ReloadStatus,
) : ExternalSystemSettingsFilesModificationContext
private inner class ProjectListener : ExternalSystemProjectListener {
override fun onProjectReloadStart() {
applyChangesOperation.traceStart()
settingsFilesStatus.updateAndGet {
SettingsFilesStatus(it.newCRC, it.newCRC)
}
projectStatus.markSynchronized(currentTime())
}
override fun onProjectReloadFinish(status: ExternalSystemRefreshStatus) {
submitSettingsFilesStatusUpdate(
operationName = "onProjectReloadFinish",
isRefreshVfs = true,
isReloadJustFinished = true,
syncEvent = ::Synchronize,
changeEvent = ::externalInvalidate
) {
applyChangesOperation.traceFinish()
}
}
override fun onSettingsFilesListChange() {
submitSettingsFilesStatusUpdate(
operationName = "onSettingsFilesListChange",
isInvalidateCache = true,
syncEvent = ::Revert,
changeEvent = ::externalModify,
) {
projectTracker.scheduleChangeProcessing()
}
}
}
private inner class ProjectSettingsListener : FilesChangesListener {
override fun onFileChange(path: String, modificationStamp: Long, modificationType: ExternalSystemModificationType) {
val operationStamp = currentTime()
logModificationAsDebug(path, modificationStamp, modificationType)
projectStatus.markModified(operationStamp, modificationType)
}
override fun apply() {
submitSettingsFilesStatusUpdate(
operationName = "ProjectSettingsListener.apply",
isMergeSameCalls = true,
syncEvent = ::Revert,
changeEvent = null
) {
projectTracker.scheduleChangeProcessing()
}
}
private fun logModificationAsDebug(path: String, modificationStamp: Long, type: ExternalSystemModificationType) {
if (LOG.isDebugEnabled) {
val projectPath = projectAware.projectId.externalProjectPath
val relativePath = FileUtil.getRelativePath(projectPath, path, '/') ?: path
LOG.debug("File $relativePath is modified at ${modificationStamp} as $type")
}
}
}
private inner class SettingsFilesAsyncSupplier : AsyncSupplier<Set<String>> {
private val cachingAsyncSupplier = CachingAsyncSupplier(
BackgroundAsyncSupplier.Builder(projectAware::settingsFiles)
.shouldKeepTasksAsynchronous(::isAsyncChangesProcessing)
.build(backgroundExecutor))
private val supplier = BackgroundAsyncSupplier.Builder(cachingAsyncSupplier)
.shouldKeepTasksAsynchronous(::isAsyncChangesProcessing)
.build(backgroundExecutor)
override fun supply(parentDisposable: Disposable, consumer: (Set<String>) -> Unit) {
supplier.supply(parentDisposable) {
consumer(it + settingsFilesStatus.get().oldCRC.keys)
}
}
fun invalidate() {
cachingAsyncSupplier.invalidate()
}
}
companion object {
private val LOG = Logger.getInstance("#com.intellij.openapi.externalSystem.autoimport")
}
} | apache-2.0 | eccdd1391cca88e30709d98d4eb8fb1b | 37.512262 | 140 | 0.74839 | 5.590585 | false | false | false | false |
siosio/intellij-community | plugins/markdown/src/org/intellij/plugins/markdown/lang/psi/impl/MarkdownImageImpl.kt | 1 | 2873 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.intellij.plugins.markdown.lang.psi.impl
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.tree.IElementType
import com.intellij.psi.util.elementType
import com.intellij.psi.util.siblings
import org.intellij.plugins.markdown.lang.MarkdownElementTypes
import org.intellij.plugins.markdown.lang.MarkdownTokenTypes
import org.intellij.plugins.markdown.lang.psi.MarkdownPsiElement
import org.intellij.plugins.markdown.util.hasType
class MarkdownImageImpl(node: ASTNode): ASTWrapperPsiElement(node), MarkdownPsiElement {
val exclamationMark: PsiElement?
get() = firstChild
val wholeLink: PsiElement?
get() = findChildByType(MarkdownElementTypes.INLINE_LINK)
val wholeLinkText: PsiElement?
get() = wholeLink?.children?.find { it.hasType(MarkdownElementTypes.LINK_TEXT) }
val wholeLinkTitle: PsiElement?
get() = wholeLink?.children?.find { it.hasType(MarkdownElementTypes.LINK_TITLE) }
val linkDestination: MarkdownLinkDestinationImpl?
get() = wholeLink?.children?.find { it.hasType(MarkdownElementTypes.LINK_DESTINATION) } as? MarkdownLinkDestinationImpl
fun collectLinkDescriptionText(): String? {
return wholeLinkText?.let {
collectTextFromWrappedBlock(it, MarkdownTokenTypes.LBRACKET, MarkdownTokenTypes.RBRACKET)
}
}
fun collectLinkTitleText(): String? {
return wholeLinkTitle?.let {
collectTextFromWrappedBlock(it, MarkdownTokenTypes.DOUBLE_QUOTE, MarkdownTokenTypes.DOUBLE_QUOTE)
}
}
private fun collectTextFromWrappedBlock(element: PsiElement, prefix: IElementType? = null, suffix: IElementType? = null): String? {
val children = element.firstChild?.siblings(withSelf = true)?.toList() ?: return null
val left = when (children.first().elementType) {
prefix -> 1
else -> 0
}
val right = when (children.last().elementType) {
suffix -> children.size - 1
else -> children.size
}
val elements = children.subList(left, right)
val content = elements.joinToString(separator = "") { it.text }
return content.takeIf { it.isNotEmpty() }
}
companion object {
/**
* Useful for determining if some element is an actual image by it's leaf child.
*/
fun getByLeadingExclamationMark(exclamationMark: PsiElement): MarkdownImageImpl? {
if (!exclamationMark.hasType(MarkdownTokenTypes.EXCLAMATION_MARK)) {
return null
}
val image = exclamationMark.parent ?: return null
if (!image.hasType(MarkdownElementTypes.IMAGE) || image.firstChild != exclamationMark) {
return null
}
return image as? MarkdownImageImpl
}
}
}
| apache-2.0 | 880c937d1b65b3100c0567b3344fc038 | 38.356164 | 158 | 0.739645 | 4.604167 | false | false | false | false |
siosio/intellij-community | plugins/git4idea/src/git4idea/log/GitCommitSignatureTrackerService.kt | 1 | 4894 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.log
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.AppUIExecutor.onUiThread
import com.intellij.openapi.application.impl.coroutineDispatchingContext
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.VcsException
import com.intellij.vcs.log.CommitId
import com.intellij.vcs.log.impl.VcsLogUiProperties
import com.intellij.vcs.log.ui.table.GraphTableModel
import com.intellij.vcs.log.ui.table.VcsLogGraphTable
import com.intellij.vcs.log.ui.table.column.VcsLogColumn
import com.intellij.vcs.log.ui.table.column.isVisible
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.swing.event.TableModelEvent
import javax.swing.event.TableModelListener
import kotlin.math.min
@Service(Service.Level.PROJECT)
internal class GitCommitSignatureTrackerService {
private val trackers = mutableMapOf<GraphTableModel, GitCommitSignatureTracker>()
fun getCommitSignature(model: GraphTableModel, row: Int): GitCommitSignature? =
trackers[model]?.getCommitSignature(row)
fun ensureTracking(table: VcsLogGraphTable, column: GitCommitSignatureLogColumn) {
if (table.model in trackers) return
val tracker = GitCommitSignatureTracker(table, column)
trackers[table.model] = tracker
Disposer.register(tracker) { trackers -= table.model }
Disposer.register(table, tracker)
tracker.track()
}
companion object {
fun getInstance(project: Project): GitCommitSignatureTrackerService = project.service()
}
}
private val LOG = logger<GitCommitSignatureTracker>()
private const val TRACK_SIZE = 50
private class GitCommitSignatureTracker(
private val table: VcsLogGraphTable,
private val column: GitCommitSignatureLogColumn
) : Disposable {
private val project: Project get() = table.logData.project
private val model: GraphTableModel get() = table.model
private val scope = CoroutineScope(onUiThread().coroutineDispatchingContext())
.also { Disposer.register(this) { it.cancel() } }
private val commitSignatures = mutableMapOf<CommitId, GitCommitSignature>()
fun getCommitSignature(row: Int): GitCommitSignature? {
val commitId = model.getCommitId(row) ?: return null
return commitSignatures[commitId]
}
override fun dispose() = Unit
fun track() {
scope.launch(CoroutineName("Git Commit Signature Tracker - ${table.id}")) {
val trackedEvents =
combine(table.modelChangedFlow(), table.columnVisibilityFlow(column)) { _, isColumnVisible -> isColumnVisible }
trackedEvents.collectLatest { isColumnVisible ->
if (!isColumnVisible) return@collectLatest
update()
}
}
}
private suspend fun update() =
try {
doUpdate()
}
catch (e: VcsException) {
LOG.warn("Failed to load commit signatures", e)
}
@Throws(VcsException::class)
private suspend fun doUpdate() {
val size = min(TRACK_SIZE, table.rowCount)
val rows = IntArray(size) { it }
val rootCommits = model.getCommitIds(rows).groupBy { it.root }
for ((root, commits) in rootCommits) {
val signatures = loadCommitSignatures(project, root, commits.map { it.hash })
commitSignatures.keys.removeIf { it.root == root }
commitSignatures += signatures.mapKeys { (hash, _) -> CommitId(hash, root) }
fireColumnDataChanged()
}
}
private fun fireColumnDataChanged() = table.repaint()
}
@Suppress("EXPERIMENTAL_API_USAGE")
private fun VcsLogGraphTable.modelChangedFlow(): Flow<Unit> =
callbackFlow {
val emit = { offer(Unit) }
val listener = TableModelListener {
if (it.column == TableModelEvent.ALL_COLUMNS) emit()
}
emit() // initial value
model.addTableModelListener(listener)
awaitClose { model.removeTableModelListener(listener) }
}
@Suppress("EXPERIMENTAL_API_USAGE")
private fun VcsLogGraphTable.columnVisibilityFlow(column: VcsLogColumn<*>): Flow<Boolean> {
val flow = callbackFlow {
val emit = { offer(column.isVisible(properties)) }
val listener = object : VcsLogUiProperties.PropertiesChangeListener {
override fun <T> onPropertyChanged(property: VcsLogUiProperties.VcsLogUiProperty<T>) {
emit()
}
}
emit() // initial value
properties.addChangeListener(listener)
awaitClose { properties.removeChangeListener(listener) }
}
return flow.distinctUntilChanged()
} | apache-2.0 | 75014fa8426b4cb5d5a99954d0add301 | 32.527397 | 158 | 0.750102 | 4.469406 | false | false | false | false |
GunoH/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/auth/ui/login/TokenLoginDialog.kt | 2 | 2474 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.collaboration.auth.ui.login
import com.intellij.collaboration.async.DisposingMainScope
import com.intellij.collaboration.messages.CollaborationToolsBundle
import com.intellij.collaboration.ui.ExceptionUtil
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.asContextElement
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.wm.IdeFocusManager
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlinx.coroutines.plus
import java.awt.Component
import javax.swing.JComponent
class TokenLoginDialog(
project: Project?, parent: Component?,
private val model: LoginModel,
@NlsContexts.DialogTitle title: String = CollaborationToolsBundle.message("login.dialog.title"),
private val centerPanelSupplier: () -> DialogPanel
) : DialogWrapper(project, parent, false, IdeModalityType.PROJECT) {
private val uiScope = DisposingMainScope(disposable) + ModalityState.stateForComponent(rootPane).asContextElement()
init {
setOKButtonText(CollaborationToolsBundle.message("login.button"))
setTitle(title)
init()
uiScope.launch {
model.loginState.collectLatest { state ->
isOKActionEnabled = state !is LoginModel.LoginState.Connecting
if (state is LoginModel.LoginState.Failed) startTrackingValidation()
if (state is LoginModel.LoginState.Connected) close(OK_EXIT_CODE)
}
}
}
override fun createCenterPanel(): JComponent = centerPanelSupplier()
override fun doOKAction() {
applyFields()
if (!isOKActionEnabled) return
uiScope.launch {
model.login()
}
}
override fun doValidate(): ValidationInfo? {
val loginState = model.loginState.value
if (loginState is LoginModel.LoginState.Failed) {
val errorMessage = ExceptionUtil.getPresentableMessage(loginState.error)
return ValidationInfo(errorMessage).withOKEnabled()
}
return null
}
override fun getPreferredFocusedComponent(): JComponent? {
val focusManager = IdeFocusManager.findInstanceByComponent(contentPanel)
return focusManager.getFocusTargetFor(contentPanel)
}
} | apache-2.0 | a980ee8781d4e3143033d2cf5ecd83ed | 34.357143 | 120 | 0.781326 | 4.85098 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/LambdaToAnonymousFunctionIntention.kt | 1 | 8514 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.builtins.isSuspendFunctionType
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.core.moveInsideParentheses
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.BranchedFoldingUtils
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.quoteIfNeeded
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunctionDescriptor
import org.jetbrains.kotlin.resolve.calls.callUtil.getParameterForArgument
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.ErrorType
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeConstructor
import org.jetbrains.kotlin.types.isFlexible
import org.jetbrains.kotlin.types.typeUtil.isTypeParameter
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
class LambdaToAnonymousFunctionIntention : SelfTargetingIntention<KtLambdaExpression>(
KtLambdaExpression::class.java,
KotlinBundle.lazyMessage("convert.to.anonymous.function"),
KotlinBundle.lazyMessage("convert.lambda.expression.to.anonymous.function")
), LowPriorityAction {
override fun isApplicableTo(element: KtLambdaExpression, caretOffset: Int): Boolean {
val argument = element.getStrictParentOfType<KtValueArgument>()
val call = argument?.getStrictParentOfType<KtCallElement>()
if (call?.getStrictParentOfType<KtFunction>()?.hasModifier(KtTokens.INLINE_KEYWORD) == true) return false
val context = element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
if (call?.getResolvedCall(context)?.getParameterForArgument(argument)?.type?.isSuspendFunctionType == true) return false
val descriptor = context[
BindingContext.DECLARATION_TO_DESCRIPTOR,
element.functionLiteral,
] as? AnonymousFunctionDescriptor ?: return false
if (descriptor.valueParameters.any { it.isDestructuring() || it.type is ErrorType }) return false
val lastElement = element.functionLiteral.arrow ?: element.functionLiteral.lBrace
return caretOffset <= lastElement.endOffset
}
override fun applyTo(element: KtLambdaExpression, editor: Editor?) {
val functionDescriptor = element.functionLiteral.descriptor as? AnonymousFunctionDescriptor ?: return
val resultingFunction = convertLambdaToFunction(element, functionDescriptor) ?: return
val argument = when (val parent = resultingFunction.parent) {
is KtLambdaArgument -> parent
is KtLabeledExpression -> parent.replace(resultingFunction).parent as? KtLambdaArgument
else -> null
} ?: return
argument.moveInsideParentheses(argument.analyze(BodyResolveMode.PARTIAL))
}
private fun ValueParameterDescriptor.isDestructuring() = this is ValueParameterDescriptorImpl.WithDestructuringDeclaration
companion object {
fun convertLambdaToFunction(
lambda: KtLambdaExpression,
functionDescriptor: FunctionDescriptor,
functionName: String = "",
functionParameterName: (ValueParameterDescriptor, Int) -> String = { parameter, _ ->
val parameterName = parameter.name
if (parameterName.isSpecial) "_" else parameterName.asString().quoteIfNeeded()
},
typeParameters: Map<TypeConstructor, KotlinType> = emptyMap(),
replaceElement: (KtNamedFunction) -> KtExpression = { lambda.replaced(it) }
): KtExpression? {
val typeSourceCode = IdeDescriptorRenderers.SOURCE_CODE_TYPES
val functionLiteral = lambda.functionLiteral
val bodyExpression = functionLiteral.bodyExpression ?: return null
val context = bodyExpression.analyze(BodyResolveMode.PARTIAL)
val functionLiteralDescriptor by lazy { functionLiteral.descriptor }
bodyExpression.collectDescendantsOfType<KtReturnExpression>().forEach {
val targetDescriptor = it.getTargetFunctionDescriptor(context)
if (targetDescriptor == functionDescriptor || targetDescriptor == functionLiteralDescriptor) it.labeledExpression?.delete()
}
val psiFactory = KtPsiFactory(lambda)
val function = psiFactory.createFunction(
KtPsiFactory.CallableBuilder(KtPsiFactory.CallableBuilder.Target.FUNCTION).apply {
typeParams()
functionDescriptor.extensionReceiverParameter?.type?.let {
receiver(typeSourceCode.renderType(it))
}
name(functionName)
for ((index, parameter) in functionDescriptor.valueParameters.withIndex()) {
val type = parameter.type.let { if (it.isFlexible()) it.makeNotNullable() else it }
val renderType = typeSourceCode.renderType(
getTypeFromParameters(type, typeParameters)
)
val parameterName = functionParameterName(parameter, index)
param(parameterName, renderType)
}
functionDescriptor.returnType?.takeIf { !it.isUnit() }?.let {
val lastStatement = bodyExpression.statements.lastOrNull()
if (lastStatement != null && lastStatement !is KtReturnExpression) {
val foldableReturns = BranchedFoldingUtils.getFoldableReturns(lastStatement)
if (foldableReturns == null || foldableReturns.isEmpty()) {
lastStatement.replace(psiFactory.createExpressionByPattern("return $0", lastStatement))
}
}
val renderType = typeSourceCode.renderType(
getTypeFromParameters(it, typeParameters)
)
returnType(renderType)
} ?: noReturnType()
blockBody(" " + bodyExpression.text)
}.asString()
)
val result = wrapInParenthesisIfNeeded(replaceElement(function), psiFactory)
ShortenReferences.DEFAULT.process(result)
return result
}
private fun getTypeFromParameters(
type: KotlinType,
typeParameters: Map<TypeConstructor, KotlinType>
): KotlinType {
if (type.isTypeParameter())
return typeParameters[type.constructor] ?: type
return type
}
private fun wrapInParenthesisIfNeeded(expression: KtExpression, psiFactory: KtPsiFactory): KtExpression {
val parent = expression.parent ?: return expression
val grandParent = parent.parent ?: return expression
if (parent is KtCallExpression && grandParent !is KtParenthesizedExpression && grandParent !is KtDeclaration) {
return expression.replaced(psiFactory.createExpressionByPattern("($0)", expression))
}
return expression
}
}
}
| apache-2.0 | 1c754f31988f833dc28b0fe594373065 | 51.881988 | 158 | 0.695678 | 5.978933 | false | false | false | false |
TachiWeb/TachiWeb-Server | TachiServer/src/main/java/xyz/nulldev/ts/api/java/impl/downloads/DownloadTaskImpl.kt | 1 | 1690 | package xyz.nulldev.ts.api.java.impl.downloads
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.download.model.Download
import eu.kanade.tachiyomi.source.model.Page
import xyz.nulldev.ts.api.java.model.downloads.DownloadStatus
import xyz.nulldev.ts.api.java.model.downloads.DownloadTask
class DownloadTaskImpl(private val download: Download) : DownloadTask {
override val chapter: Chapter
get() = download.chapter
override val pages: List<Page>?
get() = download.pages
/**
* Download progress, a float between 0 and 1
*/
override val progress: Float
get() {
val pages = pages
// Calculate download progress
val downloadProgressMax: Float
val downloadProgress: Float
if(pages != null) {
downloadProgressMax = pages.size * 100f
downloadProgress = pages
.map { it.progress.toFloat() }
.sum()
} else {
downloadProgressMax = 1f
downloadProgress = 0f
}
return downloadProgress / downloadProgressMax
}
override val status: DownloadStatus
get() = when(download.status) {
Download.NOT_DOWNLOADED -> DownloadStatus.NOT_DOWNLOADED
Download.QUEUE -> DownloadStatus.QUEUE
Download.DOWNLOADING -> DownloadStatus.DOWNLOADING
Download.DOWNLOADED -> DownloadStatus.DOWNLOADED
Download.ERROR -> DownloadStatus.ERROR
else -> throw IllegalStateException("Unknown download status: ${download.status}!")
}
} | apache-2.0 | 5aa73fd8520c0337bb7fd0485c0f1ddb | 33.510204 | 95 | 0.62426 | 5.2 | false | false | false | false |
vector-im/vector-android | vector/src/main/java/im/vector/fragments/roomwidgets/RoomWidgetViewModel.kt | 2 | 10613 | /*
* Copyright 2019 New Vector 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 im.vector.fragments.roomwidgets
import android.content.Context
import android.text.TextUtils
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.MutableLiveData
import com.airbnb.mvrx.*
import im.vector.Matrix
import im.vector.R
import im.vector.VectorApp
import im.vector.activity.WidgetActivity
import im.vector.ui.arch.LiveEvent
import im.vector.widgets.Widget
import im.vector.widgets.WidgetsManager
import org.matrix.androidsdk.MXSession
import org.matrix.androidsdk.core.Log
import org.matrix.androidsdk.core.callback.ApiCallback
import org.matrix.androidsdk.core.model.MatrixError
import org.matrix.androidsdk.data.Room
import org.matrix.androidsdk.features.integrationmanager.IntegrationManager
import org.matrix.androidsdk.features.terms.TermsNotSignedException
enum class WidgetState {
UNKNOWN,
WIDGET_NOT_ALLOWED,
WIDGET_ALLOWED
}
data class RoomWidgetViewModelState(
val status: WidgetState = WidgetState.UNKNOWN,
val formattedURL: Async<String> = Uninitialized,
val webviewLoadedUrl: Async<String> = Uninitialized,
val widgetName: String = "",
val canManageWidgets: Boolean = false,
val createdByMe: Boolean = false
) : MvRxState
class RoomWidgetViewModel(initialState: RoomWidgetViewModelState, val widget: Widget)
: BaseMvRxViewModel<RoomWidgetViewModelState>(initialState, false) {
companion object : MvRxViewModelFactory<RoomWidgetViewModel, RoomWidgetViewModelState> {
const val NAVIGATE_FINISH = "NAVIGATE_FINISH"
override fun create(viewModelContext: ViewModelContext, state: RoomWidgetViewModelState): RoomWidgetViewModel? {
return (viewModelContext.activity.intent?.extras?.getSerializable(WidgetActivity.EXTRA_WIDGET_ID) as? Widget)?.let {
RoomWidgetViewModel(state, it)
} ?: super.create(viewModelContext, state)
}
override fun initialState(viewModelContext: ViewModelContext): RoomWidgetViewModelState? {
val widget = viewModelContext.activity.intent?.extras?.getSerializable(WidgetActivity.EXTRA_WIDGET_ID) as? Widget
?: return null
val session = Matrix.getInstance(viewModelContext.activity).getSession(widget.sessionId)
return RoomWidgetViewModelState(
widgetName = widget.humanName,
createdByMe = widget.widgetEvent.getSender() == session?.myUserId
)
}
}
var navigateEvent: MutableLiveData<LiveEvent<String>> = MutableLiveData()
var termsNotSignedEvent: MutableLiveData<LiveEvent<TermsNotSignedException>> = MutableLiveData()
var loadWebURLEvent: MutableLiveData<LiveEvent<String>> = MutableLiveData()
var toastMessageEvent: MutableLiveData<LiveEvent<String>> = MutableLiveData()
private var room: Room? = null
var session: MXSession? = null
var widgetsManager: WidgetsManager? = null
/**
* Widget events listener
*/
private val mWidgetListener = WidgetsManager.onWidgetUpdateListener { widget ->
if (TextUtils.equals(widget.widgetId, widget.widgetId)) {
if (!widget.isActive) {
doFinish()
}
}
}
init {
configure()
session?.integrationManager?.addListener(object : IntegrationManager.IntegrationManagerManagerListener {
override fun onIntegrationManagerChange(managerConfig: IntegrationManager) {
refreshPermissionStatus()
}
})
}
fun webviewStartedToLoad(url: String?) = withState {
//Only do it for first load
setState {
copy(webviewLoadedUrl = Loading())
}
}
fun webviewLoadingError(url: String?, reason: String?) = withState {
setState {
copy(webviewLoadedUrl = Fail(Throwable(reason)))
}
}
fun webviewLoadSuccess(url: String?) = withState {
setState {
copy(webviewLoadedUrl = Success(url ?: ""))
}
}
private fun configure() {
val applicationContext = VectorApp.getInstance().applicationContext
val matrix = Matrix.getInstance(applicationContext)
session = matrix.getSession(widget.sessionId)
if (session == null) {
//defensive code
doFinish()
return
}
room = session?.dataHandler?.getRoom(widget.roomId)
if (room == null) {
//defensive code
doFinish()
return
}
widgetsManager = matrix
.getWidgetManagerProvider(session)?.getWidgetManager(applicationContext)
setState {
copy(canManageWidgets = WidgetsManager.checkWidgetPermission(session, room) == null)
}
widgetsManager?.addListener(mWidgetListener)
refreshPermissionStatus(applicationContext)
}
private fun refreshPermissionStatus(applicationContext: Context = VectorApp.getInstance().applicationContext) {
//If it was added by me, consider it as allowed
if (widget.widgetEvent.getSender() == session?.myUserId) {
onWidgetAllowed(applicationContext)
return
}
val isAllowed = session
?.integrationManager
?.isWidgetAllowed(widget.widgetEvent.eventId)
?: false
if (!isAllowed) {
setState {
copy(status = WidgetState.WIDGET_NOT_ALLOWED)
}
} else {
//we can start loading the widget then
onWidgetAllowed(applicationContext)
}
}
fun doCloseWidget(context: Context) {
AlertDialog.Builder(context)
.setMessage(R.string.widget_delete_message_confirmation)
.setPositiveButton(R.string.remove) { _, _ ->
widgetsManager?.closeWidget(session, room, widget.widgetId, object : ApiCallback<Void> {
override fun onSuccess(info: Void?) {
doFinish()
}
private fun onError(errorMessage: String) {
toastMessageEvent.postValue(LiveEvent(errorMessage))
}
override fun onNetworkError(e: Exception) {
onError(e.localizedMessage)
}
override fun onMatrixError(e: MatrixError) {
onError(e.localizedMessage)
}
override fun onUnexpectedError(e: Exception) {
onError(e.localizedMessage)
}
})
}
.setNegativeButton(R.string.cancel, null)
.show()
}
fun doFinish() {
navigateEvent.postValue(LiveEvent(NAVIGATE_FINISH))
}
fun refreshAfterTermsAccepted() {
onWidgetAllowed()
}
private fun onWidgetAllowed(applicationContext: Context = VectorApp.getInstance().applicationContext) {
setState {
copy(
status = WidgetState.WIDGET_ALLOWED,
formattedURL = Loading()
)
}
if (widgetsManager != null) {
widgetsManager!!.getFormattedWidgetUrl(applicationContext, widget, object : ApiCallback<String> {
override fun onSuccess(url: String) {
loadWebURLEvent.postValue(LiveEvent(url))
setState {
//We use a live event to trigger the webview load
copy(
status = WidgetState.WIDGET_ALLOWED,
formattedURL = Success(url)
)
}
}
private fun onError(errorMessage: String) {
setState {
copy(
status = WidgetState.WIDGET_ALLOWED,
formattedURL = Fail(Throwable(errorMessage))
)
}
}
override fun onNetworkError(e: Exception) {
onError(e.localizedMessage)
}
override fun onMatrixError(e: MatrixError) {
onError(e.localizedMessage)
}
override fun onUnexpectedError(e: Exception) {
if (e is TermsNotSignedException) {
termsNotSignedEvent.postValue(LiveEvent(e))
} else {
onError(e.localizedMessage)
}
}
})
} else {
setState {
copy(
status = WidgetState.WIDGET_ALLOWED,
formattedURL = Success(widget.url)
)
}
loadWebURLEvent.postValue(LiveEvent(widget.url))
}
}
fun revokeWidget(onFinished: (() -> Unit)? = null) {
setState {
copy(
status = WidgetState.UNKNOWN
)
}
session?.integrationManager?.setWidgetAllowed(widget.widgetEvent?.eventId
?: "", false, object : ApiCallback<Void?> {
override fun onSuccess(info: Void?) {
onFinished?.invoke()
}
override fun onUnexpectedError(e: Exception) {
Log.e(this::class.java.name, e.message)
}
override fun onNetworkError(e: Exception) {
Log.e(this::class.java.name, e.message)
}
override fun onMatrixError(e: MatrixError) {
Log.e(this::class.java.name, e.message)
}
})
}
override fun onCleared() {
super.onCleared()
widgetsManager?.removeListener(mWidgetListener)
}
} | apache-2.0 | 661a3afdc8c2879920d0746ee0530bd3 | 32.588608 | 128 | 0.586168 | 5.464985 | false | false | false | false |
JcMinarro/RoundKornerLayouts | roundkornerlayout/src/main/java/com/jcminarro/roundkornerlayout/Extensions.kt | 1 | 2720 | package com.jcminarro.roundkornerlayout
import android.content.res.TypedArray
import android.graphics.Path
import android.graphics.RectF
import android.os.Build
import android.view.View
internal fun View.updateOutlineProvider(cornersHolder: CornersHolder) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
outlineProvider = RoundOutlineProvider(cornersHolder)
}
}
internal fun View.updateOutlineProvider(cornerRadius: Float) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
outlineProvider = RoundOutlineProvider(cornerRadius)
}
}
internal fun Path.addRoundRectWithRoundCorners(rectF: RectF, cornersHolder: CornersHolder) {
addRoundRectWithRoundCorners(
rectF,
cornersHolder.topLeftCornerRadius,
cornersHolder.topRightCornerRadius,
cornersHolder.bottomRightCornerRadius,
cornersHolder.bottomLeftCornerRadius
)
}
internal fun Path.addRoundRectWithRoundCorners(rectF: RectF,
topLeftCornerRadius: Float,
topRightCornerRadius: Float,
bottomRightCornerRadius: Float,
bottomLeftCornerRadius: Float) {
addRoundRect(
rectF,
floatArrayOf(
topLeftCornerRadius,
topLeftCornerRadius,
topRightCornerRadius,
topRightCornerRadius,
bottomRightCornerRadius,
bottomRightCornerRadius,
bottomLeftCornerRadius,
bottomLeftCornerRadius
),
Path.Direction.CW
)
}
internal fun TypedArray.getCornerRadius(attrCornerRadius: Int,
attrTopLeftCornerRadius: Int,
attrTopRightCornerRadius: Int,
attrBottomRightCornerRadius: Int,
attrBottomLeftCornerRadius: Int
): CornersHolder {
val cornerRadius = getDimension(attrCornerRadius, 0f)
val topLeftCornerRadius = getDimension(attrTopLeftCornerRadius, cornerRadius)
val topRightCornerRadius = getDimension(attrTopRightCornerRadius, cornerRadius)
val bottomRightCornerRadius = getDimension(attrBottomRightCornerRadius, cornerRadius)
val bottomLeftCornerRadius = getDimension(attrBottomLeftCornerRadius, cornerRadius)
return CornersHolder(
topLeftCornerRadius,
topRightCornerRadius,
bottomRightCornerRadius,
bottomLeftCornerRadius
)
}
| apache-2.0 | 3067e4f24d5a8dd1abb2784a1b51a6e5 | 37.857143 | 92 | 0.624265 | 6.585956 | false | false | false | false |
deltadak/plep | src/main/kotlin/nl/deltadak/plep/commands/DeleteSubtaskCommand.kt | 1 | 2682 | package nl.deltadak.plep.commands
import javafx.scene.control.ProgressIndicator
import javafx.scene.control.TreeItem
import javafx.scene.control.TreeView
import nl.deltadak.plep.HomeworkTask
import nl.deltadak.plep.database.DatabaseFacade
import nl.deltadak.plep.ui.treeview.TreeViewCleaner
import java.time.LocalDate
/**
* Delete a subtask only.
*/
class DeleteSubtaskCommand(progressIndicator: ProgressIndicator, day: LocalDate, treeViewItemsImmutable: List<List<HomeworkTask>>, index: Int, tree: TreeView<HomeworkTask>) : DeleteCommand(progressIndicator, day, treeViewItemsImmutable, index, tree) {
private val deletedTask: HomeworkTask = treeViewItems.flatten()[index]
/** Index of parent in treeview, only counting parents */
private var parentIndex: Int = -1
/** Index of subtask in the list of children of it's parent */
private var indexWithinParent: Int = -1
/** {@inheritDoc} */
override fun executionHook() {
if (treeViewItems.isEmpty()) {
throw IllegalStateException("cannot delete item from empty treeview")
}
// Remove task from saved state.
for (i in treeViewItems.indices) {
val taskList = treeViewItems[i].toMutableList()
if (taskList.contains(deletedTask)) {
parentIndex = i
// Subtract one because the parent is the first item in the list.
indexWithinParent = taskList.indexOf(deletedTask) - 1
taskList.remove(deletedTask)
treeViewItems[i] = taskList
}
}
// Known to be null when testing.
if (tree.root != null && tree.root.children != null) {
val parent = tree.root.children[parentIndex]
if (parent != null && parent.children.size > 0) {
parent.children.removeAt(indexWithinParent)
DatabaseFacade(progressIndicator).pushData(day, treeViewItems)
TreeViewCleaner().cleanSingleTreeView(tree)
}
}
}
/** {@inheritDoc} */
override fun undoHook() {
if (parentIndex == -1 || indexWithinParent == -1) {
throw IllegalStateException("cannot find the task to re-add")
}
// We add one to the index because the first one in the list is the parent task, and we count from there.
treeViewItems[parentIndex].add(indexWithinParent + 1, deletedTask)
val parent = tree.root.children[parentIndex]
parent.children.add(indexWithinParent, TreeItem(deletedTask))
DatabaseFacade(progressIndicator).pushData(day, treeViewItems)
TreeViewCleaner().cleanSingleTreeView(tree)
}
} | mit | 38112a33ed5f0897056f2407e609fa16 | 36.263889 | 251 | 0.661074 | 4.789286 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-moderation-bukkit/src/main/kotlin/com/rpkit/moderation/bukkit/command/ticket/list/TicketListClosedCommand.kt | 1 | 2486 | /*
* Copyright 2018 Ross Binden
*
* 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.rpkit.moderation.bukkit.command.ticket.list
import com.rpkit.moderation.bukkit.RPKModerationBukkit
import com.rpkit.moderation.bukkit.ticket.RPKTicketProvider
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
import java.time.format.DateTimeFormatter
class TicketListClosedCommand(private val plugin: RPKModerationBukkit): CommandExecutor {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (!sender.hasPermission("rpkit.moderation.command.ticket.list.closed")) {
sender.sendMessage(plugin.messages["no-permission-ticket-list-closed"])
}
val ticketProvider = plugin.core.serviceManager.getServiceProvider(RPKTicketProvider::class)
val closedTickets = ticketProvider.getClosedTickets()
sender.sendMessage(plugin.messages["ticket-list-title"])
val dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
closedTickets.forEach { ticket ->
val closeDate = ticket.closeDate
sender.sendMessage(plugin.messages["ticket-list-item", mapOf(
Pair("id", ticket.id.toString()),
Pair("reason", ticket.reason),
Pair("location", "${ticket.location?.world} ${ticket.location?.blockX}, ${ticket.location?.blockY}, ${ticket.location?.blockZ}"),
Pair("issuer", ticket.issuer.name),
Pair("resolver", ticket.resolver?.name?:"none"),
Pair("open-date", dateTimeFormatter.format(ticket.openDate)),
Pair("close-date", if (closeDate == null) "none" else dateTimeFormatter.format(ticket.closeDate)),
Pair("closed", ticket.isClosed.toString())
)])
}
return true
}
} | apache-2.0 | c29dfdb91cdb4c58da4ba692eec07e81 | 45.924528 | 149 | 0.687047 | 4.595194 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/servlet/ProfilesServlet.kt | 1 | 2219 | /*
* Copyright 2019 Ren Binden
*
* 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.rpkit.players.bukkit.servlet
import com.rpkit.core.web.RPKServlet
import com.rpkit.players.bukkit.RPKPlayersBukkit
import com.rpkit.players.bukkit.profile.RPKProfileProvider
import org.apache.velocity.VelocityContext
import org.apache.velocity.app.Velocity
import java.util.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpServletResponse.SC_OK
class ProfilesServlet(private val plugin: RPKPlayersBukkit): RPKServlet() {
override val url = "/profiles/"
override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) {
resp.contentType = "text/html"
resp.status = SC_OK
val templateBuilder = StringBuilder()
val scanner = Scanner(javaClass.getResourceAsStream("/web/profiles.html"))
while (scanner.hasNextLine()) {
templateBuilder.append(scanner.nextLine()).append('\n')
}
scanner.close()
val name = req.getParameter("name")
val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class)
val profile = if (name == null) null else profileProvider.getProfile(name)
val velocityContext = VelocityContext()
velocityContext.put("server", plugin.core.web.title)
velocityContext.put("navigationBar", plugin.core.web.navigationBar)
velocityContext.put("activeProfile", profileProvider.getActiveProfile(req))
velocityContext.put("profile", profile)
Velocity.evaluate(velocityContext, resp.writer, "/web/profiles.html", templateBuilder.toString())
}
} | apache-2.0 | 3de3185756fa7d4f00580ed8c36c23aa | 40.111111 | 105 | 0.736818 | 4.565844 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-drinks-bukkit/src/main/kotlin/com/rpkit/drinks/bukkit/RPKDrinksBukkit.kt | 1 | 3643 | /*
* Copyright 2020 Ren Binden
*
* 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.rpkit.drinks.bukkit
import com.rpkit.characters.bukkit.character.RPKCharacterProvider
import com.rpkit.core.bukkit.plugin.RPKBukkitPlugin
import com.rpkit.core.database.Database
import com.rpkit.drinks.bukkit.database.table.RPKDrunkennessTable
import com.rpkit.drinks.bukkit.drink.RPKDrinkProviderImpl
import com.rpkit.drinks.bukkit.listener.PlayerItemConsumeListener
import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider
import org.bstats.bukkit.Metrics
import org.bukkit.potion.PotionEffect
import org.bukkit.potion.PotionEffectType
import org.bukkit.scheduler.BukkitRunnable
class RPKDrinksBukkit: RPKBukkitPlugin() {
override fun onEnable() {
Metrics(this, 4389)
saveDefaultConfig()
val drinkProvider = RPKDrinkProviderImpl(this)
drinkProvider.drinks.forEach { server.addRecipe(it.recipe) }
serviceProviders = arrayOf(
drinkProvider
)
object: BukkitRunnable() {
override fun run() {
val minecraftProfileProvider = core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class)
val characterProvider = core.serviceManager.getServiceProvider(RPKCharacterProvider::class)
server.onlinePlayers.forEach { bukkitPlayer ->
val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(bukkitPlayer) ?: return@forEach
val character = characterProvider.getActiveCharacter(minecraftProfile) ?: return@forEach
val drunkenness = drinkProvider.getDrunkenness(character)
if (drunkenness > 0) {
if (drunkenness > 1000) {
if (config.getBoolean("kill-characters"))
character.isDead = true
characterProvider.updateCharacter(character)
}
if (drunkenness >= 75) {
bukkitPlayer.addPotionEffect(PotionEffect(PotionEffectType.POISON, 1200, drunkenness))
}
if (drunkenness >= 50) {
bukkitPlayer.addPotionEffect(PotionEffect(PotionEffectType.BLINDNESS, 1200, drunkenness))
}
if (drunkenness >= 10) {
bukkitPlayer.addPotionEffect(PotionEffect(PotionEffectType.WEAKNESS, 1200, drunkenness))
}
bukkitPlayer.addPotionEffect(PotionEffect(PotionEffectType.CONFUSION, 1200, drunkenness))
drinkProvider.setDrunkenness(character, drunkenness - 1)
}
}
}
}.runTaskTimer(this, 1200, 1200)
}
override fun registerListeners() {
registerListeners(
PlayerItemConsumeListener(this)
)
}
override fun createTables(database: Database) {
database.addTable(RPKDrunkennessTable(database, this))
}
} | apache-2.0 | 8c3f583b07c60fef88ead9c340d231d8 | 43.439024 | 121 | 0.645622 | 5.519697 | false | false | false | false |
gradle/gradle | .teamcity/src/main/kotlin/promotion/PublishNightlySnapshotFromQuickFeedback.kt | 2 | 1306 | /*
* Copyright 2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 promotion
import common.VersionedSettingsBranch
import vcsroots.gradlePromotionBranches
class PublishNightlySnapshotFromQuickFeedback(branch: VersionedSettingsBranch) : PublishGradleDistributionFullBuild(
promotedBranch = branch.branchName,
prepTask = branch.prepNightlyTaskName(),
promoteTask = branch.promoteNightlyTaskName(),
triggerName = "QuickFeedback",
vcsRootId = gradlePromotionBranches
) {
init {
id("Promotion_SnapshotFromQuickFeedback")
name = "Nightly Snapshot (from QuickFeedback)"
description = "Promotes the latest successful changes on '${branch.branchName}' from Quick Feedback as a new nightly snapshot"
}
}
| apache-2.0 | f0e9666bab979c6eb1a3588b13ded635 | 37.411765 | 134 | 0.754211 | 4.731884 | false | false | false | false |
google/private-compute-libraries | java/com/google/android/libraries/pcc/chronicle/testutil/ChronicleModule.kt | 1 | 4519 | /*
* Copyright 2022 Google LLC
*
* 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.google.android.libraries.pcc.chronicle.testutil
import com.google.android.libraries.pcc.chronicle.analysis.ChronicleContext
import com.google.android.libraries.pcc.chronicle.analysis.DefaultChronicleContext
import com.google.android.libraries.pcc.chronicle.analysis.PolicyEngine
import com.google.android.libraries.pcc.chronicle.analysis.PolicySet
import com.google.android.libraries.pcc.chronicle.api.Chronicle
import com.google.android.libraries.pcc.chronicle.api.ConnectionProvider
import com.google.android.libraries.pcc.chronicle.api.DataTypeDescriptor
import com.google.android.libraries.pcc.chronicle.api.DataTypeDescriptorSet
import com.google.android.libraries.pcc.chronicle.api.flags.FlagsReader
import com.google.android.libraries.pcc.chronicle.api.integration.DefaultChronicle
import com.google.android.libraries.pcc.chronicle.api.integration.DefaultDataTypeDescriptorSet
import com.google.android.libraries.pcc.chronicle.api.integration.NoOpChronicle
import com.google.android.libraries.pcc.chronicle.api.policy.DefaultPolicyConformanceCheck
import com.google.android.libraries.pcc.chronicle.api.policy.Policy
import com.google.android.libraries.pcc.chronicle.util.Logcat
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import dagger.multibindings.Multibinds
import javax.inject.Singleton
import kotlin.system.exitProcess
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
@Module
@InstallIn(SingletonComponent::class)
abstract class ChronicleModule {
@Multibinds abstract fun providesPolicies(): Set<Policy>
@Multibinds abstract fun providesConnectionProviders(): Set<ConnectionProvider>
@Multibinds abstract fun bindDtds(): Set<DataTypeDescriptor>
companion object {
val log = Logcat.default
@Provides
@Singleton
fun bindDtdSetImpl(dtds: Set<@JvmSuppressWildcards DataTypeDescriptor>): DataTypeDescriptorSet =
DefaultDataTypeDescriptorSet(dtds)
@Provides
@Singleton
fun bindChronicleContextImpl(
providers: Set<@JvmSuppressWildcards ConnectionProvider>,
policySet: PolicySet,
dtdSet: DataTypeDescriptorSet
): ChronicleContext = DefaultChronicleContext(providers, emptySet(), policySet, dtdSet)
@OptIn(DelicateCoroutinesApi::class)
@Provides
@Singleton
fun bindsChronicle(
context: ChronicleContext,
engine: PolicyEngine,
flags: FlagsReader,
): Chronicle {
// Because some policy checks happen in `ChronicleImpl` init(), when `failNewConnections`
// goes from true -> false have to wait for an app restart to get the real impl back.
val current = flags.config.value
if (current.failNewConnections || current.emergencyDisable) {
log.d("Starting Chronicle in no-op mode.")
return NoOpChronicle(disabledFromStartupFlags = true)
}
// This listener is here rather than in ChronicleImpl to make the decision on whether to use
// a NoOpImpl atomic with emergencyDisable and only enable this force-exit logic when the real
// impl is active.
flags.config
.onEach { value ->
if (value.emergencyDisable) {
// Force exit the app. It will be restarted by SystemServer and when it comes back up
// we will be using the no-op impl.
log.i("Emergency disable engaged, restarting APK.")
exitProcess(0)
}
}
.launchIn(GlobalScope)
log.d("Starting Chronicle in enabled mode.")
return DefaultChronicle(
context,
engine,
DefaultChronicle.Config(
policyMode = DefaultChronicle.Config.PolicyMode.STRICT,
policyConformanceCheck = DefaultPolicyConformanceCheck()
),
flags
)
}
}
}
| apache-2.0 | 77bf22a642c4c2eb262d0a6d1b6060e0 | 39.711712 | 100 | 0.756141 | 4.546278 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/profile/RPKProfileImpl.kt | 1 | 2773 | /*
* Copyright 2021 Ren Binden
* 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.rpkit.players.bukkit.profile
import java.security.SecureRandom
import java.util.Arrays
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
class RPKProfileImpl : RPKProfile {
override var id: RPKProfileId? = null
override var name: RPKProfileName
override var discriminator: RPKProfileDiscriminator
override var passwordHash: ByteArray?
override var passwordSalt: ByteArray?
constructor(id: RPKProfileId, name: RPKProfileName, discriminator: RPKProfileDiscriminator, passwordHash: ByteArray? = null, passwordSalt: ByteArray? = null) {
this.id = id
this.name = name
this.discriminator = discriminator
this.passwordHash = passwordHash
this.passwordSalt = passwordSalt
}
constructor(name: RPKProfileName, discriminator: RPKProfileDiscriminator, password: String?) {
this.id = null
this.name = name
this.discriminator = discriminator
if (password != null) {
val random = SecureRandom()
passwordSalt = ByteArray(16)
random.nextBytes(passwordSalt)
val spec = PBEKeySpec(password.toCharArray(), passwordSalt, 65536, 128)
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512")
passwordHash = factory.generateSecret(spec).encoded
} else {
passwordSalt = null
passwordHash = null
}
}
override fun setPassword(password: CharArray) {
val random = SecureRandom()
passwordSalt = ByteArray(16)
random.nextBytes(passwordSalt)
val spec = PBEKeySpec(password, passwordSalt, 65536, 128)
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512")
passwordHash = factory.generateSecret(spec).encoded
}
override fun checkPassword(password: CharArray): Boolean {
if (passwordHash == null || passwordSalt == null) return false
val spec = PBEKeySpec(password, passwordSalt, 65536, 128)
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512")
return Arrays.equals(passwordHash, factory.generateSecret(spec).encoded)
}
} | apache-2.0 | fe03451cf28f269ca30e8e9aceb320a1 | 37.527778 | 163 | 0.700325 | 4.969534 | false | false | false | false |
FWDekker/intellij-randomness | src/main/kotlin/com/fwdekker/randomness/template/TemplateReferenceEditor.kt | 1 | 6205 | package com.fwdekker.randomness.template
import com.fwdekker.randomness.Bundle
import com.fwdekker.randomness.CapitalizationMode.Companion.getMode
import com.fwdekker.randomness.SettingsState
import com.fwdekker.randomness.StateEditor
import com.fwdekker.randomness.array.ArrayDecoratorEditor
import com.fwdekker.randomness.template.TemplateReference.Companion.DEFAULT_CAPITALIZATION
import com.fwdekker.randomness.template.TemplateReference.Companion.DEFAULT_QUOTATION
import com.fwdekker.randomness.ui.MaxLengthDocumentFilter
import com.fwdekker.randomness.ui.UIConstants
import com.fwdekker.randomness.ui.VariableLabelRadioButton
import com.fwdekker.randomness.ui.addChangeListenerTo
import com.fwdekker.randomness.ui.getValue
import com.fwdekker.randomness.ui.setLabel
import com.fwdekker.randomness.ui.setValue
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.SeparatorFactory
import com.intellij.ui.TitledSeparator
import com.intellij.ui.components.JBList
import com.intellij.ui.components.JBScrollPane
import java.awt.BorderLayout
import javax.swing.ButtonGroup
import javax.swing.DefaultListModel
import javax.swing.JLabel
import javax.swing.JList
import javax.swing.JPanel
import javax.swing.ListSelectionModel
/**
* Component for editing [TemplateReference]s.
*
* @param reference the reference to edit
*/
@Suppress("LateinitUsage") // Initialized by scene builder
class TemplateReferenceEditor(reference: TemplateReference) : StateEditor<TemplateReference>(reference) {
override lateinit var rootComponent: JPanel private set
override val preferredFocusedComponent
get() = templateList
private lateinit var templateListSeparator: TitledSeparator
private lateinit var templateListPanel: JPanel
private lateinit var templateListModel: DefaultListModel<Template>
private lateinit var templateList: JBList<Template>
private lateinit var appearanceSeparator: TitledSeparator
private lateinit var capitalizationLabel: JLabel
private lateinit var capitalizationGroup: ButtonGroup
private lateinit var customQuotation: VariableLabelRadioButton
private lateinit var quotationLabel: JLabel
private lateinit var quotationGroup: ButtonGroup
private lateinit var arrayDecoratorEditor: ArrayDecoratorEditor
private lateinit var arrayDecoratorEditorPanel: JPanel
init {
nop() // Cannot use `lateinit` property as first statement in init
capitalizationGroup.setLabel(capitalizationLabel)
customQuotation.addToButtonGroup(quotationGroup)
quotationGroup.setLabel(quotationLabel)
loadState()
}
/**
* Initializes custom UI components.
*
* This method is called by the scene builder at the start of the constructor.
*/
@Suppress("UnusedPrivateMember") // Used by scene builder
private fun createUIComponents() {
templateListSeparator = SeparatorFactory.createSeparator(Bundle("reference.ui.template_list"), null)
templateListModel = DefaultListModel<Template>()
templateList = JBList(templateListModel)
templateList.cellRenderer = object : ColoredListCellRenderer<Template>() {
override fun customizeCellRenderer(
list: JList<out Template>,
value: Template?,
index: Int,
selected: Boolean,
hasFocus: Boolean
) {
icon = value?.icon ?: Template.DEFAULT_ICON
append(value?.name ?: Bundle("template.name.unknown"))
}
}
templateList.selectionMode = ListSelectionModel.SINGLE_SELECTION
templateList.setEmptyText(Bundle("reference.ui.empty"))
templateListPanel = JPanel(BorderLayout())
templateListPanel.add(JBScrollPane(templateList), BorderLayout.WEST)
appearanceSeparator = SeparatorFactory.createSeparator(Bundle("reference.ui.appearance"), null)
customQuotation = VariableLabelRadioButton(UIConstants.WIDTH_TINY, MaxLengthDocumentFilter(2))
arrayDecoratorEditor = ArrayDecoratorEditor(originalState.arrayDecorator)
arrayDecoratorEditorPanel = arrayDecoratorEditor.rootComponent
}
override fun loadState(state: TemplateReference) {
super.loadState(state)
// Find templates that would not cause recursion if selected
val listCopy = (+state.templateList).deepCopy(retainUuid = true)
.also { it.applySettingsState(SettingsState(it)) }
val referenceCopy =
listCopy.templates.flatMap { it.schemes }.single { it.uuid == originalState.uuid } as TemplateReference
val validTemplates =
(+state.templateList).templates
.filter { template ->
referenceCopy.template = template
listCopy.findRecursionFrom(referenceCopy) == null
}
templateListModel.removeAllElements()
templateListModel.addAll(validTemplates)
templateList.setSelectedValue(state.template, true)
customQuotation.label = state.customQuotation
quotationGroup.setValue(state.quotation)
capitalizationGroup.setValue(state.capitalization)
arrayDecoratorEditor.loadState(state.arrayDecorator)
}
override fun readState() =
TemplateReference(
templateUuid = templateList.selectedValue?.uuid,
quotation = quotationGroup.getValue() ?: DEFAULT_QUOTATION,
customQuotation = customQuotation.label,
capitalization = capitalizationGroup.getValue()?.let { getMode(it) } ?: DEFAULT_CAPITALIZATION,
arrayDecorator = arrayDecoratorEditor.readState()
).also {
it.uuid = originalState.uuid
it.templateList = originalState.templateList.copy()
}
override fun addChangeListener(listener: () -> Unit) {
templateList.addListSelectionListener { listener() }
addChangeListenerTo(
capitalizationGroup, quotationGroup, customQuotation, arrayDecoratorEditor,
listener = listener
)
}
}
/**
* Null operation, does nothing.
*/
private fun nop() {
// Does nothing
}
| mit | 9b03d117732a040fdd953ef74c633ed2 | 38.522293 | 115 | 0.727478 | 5.560036 | false | false | false | false |
Geobert/Efficio | app/src/main/kotlin/fr/geobert/efficio/widget/TaskListWidget.kt | 1 | 6187 | package fr.geobert.efficio.widget
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.widget.RemoteViews
import fr.geobert.efficio.R
import fr.geobert.efficio.db.TaskTable
import fr.geobert.efficio.db.WidgetTable
import fr.geobert.efficio.misc.OnRefreshReceiver
import kotlin.properties.Delegates
/**
* Implementation of App Widget functionality.
*/
class TaskListWidget : AppWidgetProvider() {
val TAG = "TaskListWidget"
var opacity: Float by Delegates.notNull<Float>()
var storeName by Delegates.notNull<String>()
var storeId by Delegates.notNull<Long>()
companion object {
val ACTION_CHECKBOX_CHANGED = "fr.geobert.efficio.action_checkbox_changed"
}
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
// There may be multiple widgets active, so update all of them
Log.d(TAG, "onUpdate: ${appWidgetIds.size}")
for (appWidgetId in appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId)
}
super.onUpdate(context, appWidgetManager, appWidgetIds)
}
override fun onReceive(context: Context, intent: Intent) {
val extras = intent.extras
Log.d(TAG, "onReceive: ${intent.action}")
val appWidgetManager = AppWidgetManager.getInstance(context)
when (intent.action) {
ACTION_CHECKBOX_CHANGED -> {
val widgetId = extras?.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID) ?: AppWidgetManager.INVALID_APPWIDGET_ID
TaskTable.updateDoneState(context, extras.getLong("taskId"), true)
appWidgetManager.notifyAppWidgetViewDataChanged(
widgetId, R.id.tasks_list_widget)
if (!fetchWidgetInfo(context, widgetId)) {
Log.e(TAG, "onReceive ACTION_CHECKBOX_CHANGED fetchWidgetInfo FAILED")
return
}
val i = Intent(OnRefreshReceiver.REFRESH_ACTION)
i.putExtra("storeId", storeId)
context.sendBroadcast(i)
}
"android.appwidget.action.APPWIDGET_DELETED" -> {
val widgetId = extras?.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID) ?: AppWidgetManager.INVALID_APPWIDGET_ID
Log.d(TAG, "widgetId: $widgetId")
WidgetTable.delete(context, widgetId)
}
"android.appwidget.action.APPWIDGET_UPDATE" -> {
val widgetIds = extras?.getIntArray(AppWidgetManager.EXTRA_APPWIDGET_IDS)
if (widgetIds != null) for (widgetId in widgetIds)
appWidgetManager.notifyAppWidgetViewDataChanged(widgetId, R.id.tasks_list_widget)
}
}
super.onReceive(context, intent)
}
override fun onEnabled(context: Context) {
// Enter relevant functionality for when the first widget is created
}
override fun onDisabled(context: Context) {
// Enter relevant functionality for when the last widget is disabled
}
private fun fetchWidgetInfo(ctx: Context, widgetId: Int): Boolean {
val cursor = WidgetTable.getWidgetInfo(ctx, widgetId)
if (cursor != null) {
if (cursor.count > 0 && cursor.moveToFirst()) {
storeId = cursor.getLong(0)
opacity = cursor.getFloat(1)
storeName = cursor.getString(2)
return true
}
cursor.close()
}
return false
}
fun updateAppWidget(context: Context, appWidgetManager: AppWidgetManager, appWidgetId: Int) {
Log.d(TAG, "updateAppWidget $appWidgetId")
val intent = Intent(context, TaskListWidgetService::class.java)
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
intent.data = Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME))
if (!fetchWidgetInfo(context, appWidgetId)) {
Log.e(TAG, "updateAppWidget fetchWidgetInfo FAILED")
return
}
// Construct the RemoteViews object
val views = RemoteViews(context.packageName, R.layout.task_list_widget)
views.setInt(R.id.widget_background, "setAlpha", (opacity * 255).toInt())
views.setTextViewText(R.id.widget_store_chooser_btn, storeName)
views.setRemoteAdapter(R.id.tasks_list_widget, intent)
views.setEmptyView(R.id.tasks_list_widget, R.id.empty_text_widget)
val onClickIntent = Intent(context, TaskListWidget::class.java)
onClickIntent.action = ACTION_CHECKBOX_CHANGED
onClickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
val pIntent = PendingIntent.getBroadcast(context, 0, onClickIntent,
PendingIntent.FLAG_UPDATE_CURRENT)
views.setPendingIntentTemplate(R.id.tasks_list_widget, pIntent)
val launchIntent = Intent("android.intent.action.MAIN")
launchIntent.addCategory("android.intent.category.LAUNCHER")
launchIntent.component = ComponentName("fr.geobert.efficio", "fr.geobert.efficio.MainActivity")
val lpIntent = PendingIntent.getActivity(context, 0, launchIntent, 0)
views.setOnClickPendingIntent(R.id.widget_store_chooser_btn, lpIntent)
val launchConfigIntent = Intent(context, WidgetSettingsActivity::class.java)
launchConfigIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
launchConfigIntent.putExtra(WidgetSettingsActivity.FIRST_CONFIG, false)
val cpIntent = PendingIntent.getActivity(context, 0, launchConfigIntent, PendingIntent.FLAG_UPDATE_CURRENT)
views.setOnClickPendingIntent(R.id.widget_settings_btn, cpIntent)
// Instruct the widget manager to update the widget
appWidgetManager.updateAppWidget(appWidgetId, views)
}
}
| gpl-2.0 | 92c9957bd34d0f3e7568d53b9538e605 | 42.879433 | 115 | 0.673994 | 4.796124 | false | false | false | false |
MaibornWolff/codecharta | analysis/import/SourceCodeParser/src/main/kotlin/de/maibornwolff/codecharta/importer/sourcecodeparser/ParserDialog.kt | 1 | 3009 | package de.maibornwolff.codecharta.importer.sourcecodeparser
import com.github.kinquirer.KInquirer
import com.github.kinquirer.components.promptConfirm
import com.github.kinquirer.components.promptInput
import com.github.kinquirer.components.promptListObject
import com.github.kinquirer.core.Choice
import de.maibornwolff.codecharta.tools.interactiveparser.ParserDialogInterface
class ParserDialog {
companion object : ParserDialogInterface {
override fun collectParserArgs(): List<String> {
val inputFileName = KInquirer.promptInput(
message = "Which project folder or code file should be parsed?",
hint = "file.java"
)
val outputFormat = KInquirer.promptListObject(
message = "Which output format should be generated?",
choices = listOf(Choice("CodeCharta JSON", OutputFormat.JSON), Choice("CSV", OutputFormat.TABLE)),
)
val defaultOutputFilename = if (outputFormat == OutputFormat.JSON) "output.cc.json" else "output.csv"
val outputFileName: String = KInquirer.promptInput(
message = "What is the name of the output file?",
hint = defaultOutputFilename,
default = defaultOutputFilename,
)
val findIssues = KInquirer.promptConfirm(
message = "Should we search for sonar issues?",
default = true
)
val defaultExcludes = KInquirer.promptConfirm(
message = "Should we apply default excludes (build, target, dist and out folders, hidden files/folders)?",
default = false
)
val exclude = mutableListOf<String>()
while (true) {
val additionalExclude = KInquirer.promptInput(
message = "Exclude file/folder according to regex pattern? Leave empty to skip.",
)
if (additionalExclude.isNotBlank()) {
exclude.add("--exclude=" + additionalExclude)
} else {
break
}
}
val isCompressed = (outputFileName.isEmpty()) || KInquirer.promptConfirm(
message = "Do you want to compress the output file?",
default = true
)
val isVerbose: Boolean =
KInquirer.promptConfirm(message = "Display info messages from sonar plugins?", default = false)
return listOfNotNull(
inputFileName,
"--format=$outputFormat",
"--output-file=$outputFileName",
if (isCompressed) null else "--not-compressed",
if (findIssues) null else "--no-issues",
if (defaultExcludes) "--default-excludes" else null,
if (isVerbose) "--verbose" else null,
) + exclude
}
}
}
| bsd-3-clause | d15f351499820c8dd76420bec03c5ba1 | 40.791667 | 126 | 0.575274 | 5.677358 | false | false | false | false |
LorittaBot/Loritta | web/showtime/backend/src/main/kotlin/net/perfectdreams/loritta/cinnamon/showtime/backend/utils/WebUtils.kt | 1 | 12264 | package net.perfectdreams.loritta.cinnamon.showtime.backend.utils
import kotlinx.html.DIV
import kotlinx.html.FlowOrInteractiveOrPhrasingContent
import kotlinx.html.IMG
import kotlinx.html.div
import kotlinx.html.fieldSet
import kotlinx.html.id
import kotlinx.html.img
import kotlinx.html.legend
import kotlinx.html.style
import net.perfectdreams.etherealgambi.data.DefaultImageVariantPreset
import net.perfectdreams.etherealgambi.data.ScaleDownToWidthImageVariantPreset
import net.perfectdreams.etherealgambi.data.api.responses.ImageVariantsResponse
import net.perfectdreams.loritta.cinnamon.showtime.backend.ShowtimeBackend
fun FlowOrInteractiveOrPhrasingContent.imgSrcSetFromResources(path: String, sizes: String, block: IMG.() -> Unit = {}) {
val imageInfo = ImageUtils.optimizedImagesInfoWithVariants.firstOrNull { it.path.removePrefix("static") == path }
if (imageInfo != null) {
imgSrcSet(
imageInfo.path.removePrefix("static"),
sizes,
(
imageInfo.variations!!.map {
"${it.path.removePrefix("static")} ${it.width}w"
} + "${imageInfo.path.removePrefix("static")} ${imageInfo.width}w"
).joinToString(", "),
block
)
} else error("Missing ImageInfo for \"$path\"!")
}
fun FlowOrInteractiveOrPhrasingContent.imgSrcSetFromEtherealGambi(m: ShowtimeBackend, variantInfo: ImageVariantsResponse, extension: String, sizes: String, block: IMG.() -> Unit = {}) {
val defaultVariant = variantInfo.variants.first { it.preset is DefaultImageVariantPreset }
val scaleDownVariants = variantInfo.variants.filter { it.preset is ScaleDownToWidthImageVariantPreset }
val imageUrls = (
scaleDownVariants.map {
"${m.etherealGambiClient.baseUrl}/${it.urlWithoutExtension}.$extension ${(it.preset as ScaleDownToWidthImageVariantPreset).width}w"
} + "${m.etherealGambiClient.baseUrl}/${defaultVariant.urlWithoutExtension}.$extension ${variantInfo.imageInfo.width}w"
).joinToString(", ")
imgSrcSet(
"${m.etherealGambiClient.baseUrl}/${defaultVariant.urlWithoutExtension}.$extension",
sizes,
imageUrls
) {
block()
style += "aspect-ratio: ${variantInfo.imageInfo.width}/${variantInfo.imageInfo.height}"
}
}
fun FlowOrInteractiveOrPhrasingContent.imgSrcSetFromResourcesOrFallbackToImgIfNotPresent(path: String, sizes: String, block: IMG.() -> Unit = {}) {
try {
imgSrcSetFromResources(path, sizes, block)
} catch (e: Exception) {
img(src = path, block = block)
}
}
// Generates Image Sets
fun DIV.imgSrcSet(path: String, fileName: String, sizes: String, max: Int, min: Int, stepInt: Int, block : IMG.() -> Unit = {}) {
val srcsets = mutableListOf<String>()
val split = fileName.split(".")
val ext = split.last()
for (i in (max - stepInt) downTo min step stepInt) {
// "${websiteUrl}$versionPrefix/assets/img/home/lori_gabi.png 1178w, ${websiteUrl}$versionPrefix/assets/img/home/lori_gabi_1078w.png 1078w, ${websiteUrl}$versionPrefix/assets/img/home/lori_gabi_978w.png 978w, ${websiteUrl}$versionPrefix/assets/img/home/lori_gabi_878w.png 878w, ${websiteUrl}$versionPrefix/assets/img/home/lori_gabi_778w.png 778w, ${websiteUrl}$versionPrefix/assets/img/home/lori_gabi_678w.png 678w, ${websiteUrl}$versionPrefix/assets/img/home/lori_gabi_578w.png 578w, ${websiteUrl}$versionPrefix/assets/img/home/lori_gabi_478w.png 478w, ${websiteUrl}$versionPrefix/assets/img/home/lori_gabi_378w.png 378w, ${websiteUrl}$versionPrefix/assets/img/home/lori_gabi_278w.png 278w, ${websiteUrl}$versionPrefix/assets/img/home/lori_gabi_178w.png 178w"
srcsets.add("$path${split.first()}_${i}w.$ext ${i}w")
}
srcsets.add("$path$fileName ${max}w")
imgSrcSet(
"$path$fileName",
sizes,
srcsets.joinToString(", "),
block
)
}
fun FlowOrInteractiveOrPhrasingContent.imgSrcSet(filePath: String, sizes: String, srcset: String, block : IMG.() -> Unit = {}) {
img(src = filePath) {
style = "width: auto;"
attributes["sizes"] = sizes
attributes["srcset"] = srcset
this.apply(block)
}
}
fun DIV.adWrapper(svgIconManager: SVGIconManager, callback: DIV.() -> Unit) {
// Wraps the div in a nice wrapper
div {
style = "text-align: center;"
fieldSet {
style = "display: inline;\n" +
"border: 2px solid rgba(0,0,0,.05);\n" +
"border-radius: 7px;\n" +
"color: rgba(0,0,0,.3);"
legend {
style = "margin-left: auto;"
svgIconManager.ad.apply(this)
}
div {
callback.invoke(this)
}
}
}
}
fun DIV.mediaWithContentWrapper(
mediaOnTheRightSide: Boolean,
mediaFigure: DIV.() -> (Unit),
mediaBody: DIV.() -> (Unit),
) {
div(classes = "media") {
if (mediaOnTheRightSide) {
div(classes = "media-body") {
mediaBody.invoke(this)
}
div(classes = "media-figure") {
mediaFigure.invoke(this)
}
} else {
div(classes = "media-figure") {
mediaFigure.invoke(this)
}
div(classes = "media-body") {
mediaBody.invoke(this)
}
}
}
}
fun DIV.innerContent(block: DIV.() -> (Unit)) = div {
id = "inner-content"
div(classes = "background-overlay") {}
block.invoke(this)
}
/* fun DIV.generateNitroPayAdOrSponsor(sponsorId: Int, adSlot: String, adName: String? = null, callback: (NitroPayAdDisplay) -> (Boolean)) {
// TODO: Fix
val sponsors = listOf<Sponsor>() // loritta.sponsors
val sponsor = sponsors.getOrNull(sponsorId)
if (sponsor != null) {
generateSponsor(sponsor)
} else {
generateNitroPayAdOrSponsor(sponsorId, "$adSlot-desktop", NitroPayAdDisplay.DESKTOP, "Loritta Daily Reward", callback.invoke(
NitroPayAdDisplay.DESKTOP))
generateNitroPayAdOrSponsor(sponsorId, "$adSlot-phone", NitroPayAdDisplay.PHONE, "Loritta Daily Reward", callback.invoke(
NitroPayAdDisplay.PHONE))
generateNitroPayAdOrSponsor(sponsorId, "$adSlot-tablet", NitroPayAdDisplay.TABLET, "Loritta Daily Reward", callback.invoke(
NitroPayAdDisplay.TABLET))
}
}
fun DIV.generateNitroPayAd(adSlot: String, adName: String? = null) {
generateNitroPayAd("$adSlot-desktop", NitroPayAdDisplay.DESKTOP, "Loritta Daily Reward")
generateNitroPayAd("$adSlot-phone", NitroPayAdDisplay.PHONE, "Loritta Daily Reward")
generateNitroPayAd("$adSlot-tablet", NitroPayAdDisplay.TABLET, "Loritta Daily Reward")
}
// TODO: Fix
fun DIV.generateNitroPayAdOrSponsor(sponsorId: Int, adSlot: String, displayType: NitroPayAdDisplay, adName: String? = null, showIfSponsorIsMissing: Boolean = true, showOnMobile: Boolean = true)
= generateNitroPayAdOrSponsor(listOf<Sponsor>(), sponsorId, adSlot, displayType, adName, showIfSponsorIsMissing)
fun DIV.generateNitroPayAdOrSponsor(sponsors: List<Sponsor>, sponsorId: Int, adSlot: String, displayType: NitroPayAdDisplay, adName: String? = null, showIfSponsorIsMissing: Boolean = true, showOnMobile: Boolean = true) {
val sponsor = sponsors.getOrNull(sponsorId)
if (sponsor != null) {
generateSponsor(sponsor)
} else if (showIfSponsorIsMissing) {
generateNitroPayAd(adSlot, displayType, adName)
}
}
// TODO: Fix
fun DIV.generateNitroPayVideoAdOrSponsor(sponsorId: Int, adSlot: String, adName: String? = null, showIfSponsorIsMissing: Boolean = true, showOnMobile: Boolean = true)
= generateNitroPayVideoAdOrSponsor(listOf(), sponsorId, adSlot, adName, showIfSponsorIsMissing)
fun DIV.generateNitroPayVideoAdOrSponsor(sponsors: List<Sponsor>, sponsorId: Int, adSlot: String, adName: String? = null, showIfSponsorIsMissing: Boolean = true, showOnMobile: Boolean = true) {
val sponsor = sponsors.getOrNull(sponsorId)
if (sponsor != null) {
generateSponsor(sponsor)
} else if (showIfSponsorIsMissing) {
generateNitroPayVideoAd(adSlot, adName)
}
}
fun DIV.generateAdOrSponsor(sponsorId: Int, adSlot: String, adName: String? = null, showIfSponsorIsMissing: Boolean = true, showOnMobile: Boolean = true)
= generateAdOrSponsor(listOf(), sponsorId, adSlot, adName, showIfSponsorIsMissing)
fun DIV.generateAdOrSponsor(sponsors: List<Sponsor>, sponsorId: Int, adSlot: String, adName: String? = null, showIfSponsorIsMissing: Boolean = true, showOnMobile: Boolean = true) {
val sponsor = sponsors.getOrNull(sponsorId)
if (sponsor != null) {
generateSponsor(sponsor)
} else if (showIfSponsorIsMissing) {
generateAd(adSlot, adName, showOnMobile)
}
}
fun DIV.generateSponsor(sponsor: Sponsor) {
div(classes = "media") {
generateSponsorNoWrap(sponsor)
}
}
fun DIV.generateSponsorNoWrap(sponsor: Sponsor) {
a(href = "/sponsor/${sponsor.slug}", classes = "sponsor-wrapper", target = "_blank") {
div(classes = "sponsor-pc-image") {
img(src = sponsor.getRectangularBannerUrl(), classes = "sponsor-banner")
}
div(classes = "sponsor-mobile-image") {
img(src = sponsor.getSquareBannerUrl(), classes = "sponsor-banner")
}
}
}
fun DIV.generateHowToSponsorButton(locale: BaseLocale) {
div(classes = "media") {
style = "justify-content: end;"
div {
style = "font-size: 0.8em; margin: 8px;"
+ (locale["website.sponsors.wantYourServerHere"] + " ")
a(href = "/sponsors") {
span(classes = "sponsor-button") {
+ "Premium Slots"
}
}
}
}
}
fun DIV.generateAd(adSlot: String, adName: String? = null, showOnMobile: Boolean = true) {
// O "adName" não é utilizado para nada, só está aí para que fique mais fácil de analisar aonde está cada ad (caso seja necessário)
// TODO: Random ID
val adGen = "ad-$adSlot-"
div(classes = "centralized-ad") {
ins(classes = "adsbygoogle") {
style = "display: block;"
if (!showOnMobile)
attributes["id"] = adGen
attributes["data-ad-client"] = "ca-pub-9989170954243288"
attributes["data-ad-slot"] = adSlot
attributes["data-ad-format"] = "auto"
attributes["data-full-width-responsive"] = "true"
}
}
if (!showOnMobile) {
script(type = ScriptType.textJavaScript) {
unsafe {
raw("if (document.body.clientWidth >= 1366) { (adsbygoogle = window.adsbygoogle || []).push({}); } else { console.log(\"Not displaying ad: Browser width is too smol!\"); document.querySelector(\"#$adGen\").remove(); }")
}
}
} else {
script(type = ScriptType.textJavaScript) {
unsafe {
raw("(adsbygoogle = window.adsbygoogle || []).push({});")
}
}
}
}
fun DIV.generateNitroPayAd(adId: String, displayType: NitroPayAdDisplay, adName: String? = null) {
// O "adName" não é utilizado para nada, só está aí para que fique mais fácil de analisar aonde está cada ad (caso seja necessário)
div(classes = "centralized-ad") {
div(classes = "nitropay-ad") {
id = adId
attributes["data-nitropay-ad-type"] = NitroPayAdType.STANDARD_BANNER.name.toLowerCase()
attributes["data-nitropay-ad-display"] = displayType.name.toLowerCase()
}
}
}
fun DIV.generateNitroPayVideoAd(adId: String, adName: String? = null) {
// O "adName" não é utilizado para nada, só está aí para que fique mais fácil de analisar aonde está cada ad (caso seja necessário)
div(classes = "centralized-ad") {
div(classes = "nitropay-ad") {
id = adId
attributes["data-nitropay-ad-type"] = NitroPayAdType.VIDEO_PLAYER.name.toLowerCase()
attributes["data-nitropay-ad-display"] = NitroPayAdDisplay.RESPONSIVE.name.toLowerCase()
}
}
} */ | agpl-3.0 | b40670d30ef29af9a0d97a245a34acb5 | 39.939799 | 768 | 0.648611 | 4.132343 | false | false | false | false |
christophpickl/gadsu | src/test/kotlin/non_test/kotlin_playground/misc.kt | 1 | 642 | package non_test.kotlin_playground
//fun `func is fun`() {
// val btn1: JButton = JButton().apply {
// text = "hihi"
// true
// }
// val btn2: JButton = with(JButton()) {
// text = "hihi"
// this
// }
// val panel = JPanel()
// panel.add(JButton().let { btn ->
// btn.text = "hihi"
// btn
// })
//}
fun main(args: Array<String>) {
myRecursion(10)
}
fun myRecursion(max: Int) {
_myRecursion(1, max)
}
fun _myRecursion(current: Int, max: Int) {
when {
current <= max -> { println(current); _myRecursion(current + 1, max) }
else -> return
}
}
| apache-2.0 | 927312d79abc9248c56d1e34ad9f6687 | 17.342857 | 78 | 0.507788 | 3.028302 | false | false | false | false |
eugeis/ee | ee-asm/src/main/kotlin/ee/asm/ClassTreeUtils.kt | 1 | 1786 | package ee.asm
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.MethodNode
internal interface ClassTreeUtils {
val classTree: ClassTree
fun isExcluded(node: ClassNode): Boolean
fun isExcluded(node: MethodNodeWithClass): Boolean
fun findAvailableClasses(): List<ClassNode> = classTree.filter { !isExcluded(it) }
fun findAvailableMethods(availableClasses: List<ClassNode>): List<MethodNodeWithClass> {
return availableClasses.flatMap { classNode ->
classNode.methods?.map { MethodNodeWithClass(classNode, it as MethodNode) }?.filter { !isExcluded(it) }
?: listOf()
}
}
val ClassNode.isView: Boolean
get() {
val isSuccessor = classTree.isSuccessorOf(this, "android/view/View") || this.name == "android/view/View"
return isSuccessor && !isInner
}
val ClassNode.isLayoutParams: Boolean
get() {
return isInner && (classTree.isSuccessorOf(this,
"android/view/ViewGroup\$LayoutParams") || this.name == "android/view/ViewGroup\$LayoutParams")
}
val ClassNode.isViewGroup: Boolean
get() {
return !isInner && (classTree.isSuccessorOf(this,
"android/view/ViewGroup") || this.name == "android/view/ViewGroup")
}
fun ClassNode.resolveAllMethods(): List<MethodNode> {
val node = classTree.findNode(this)
fun allMethodsTo(node: ClassTreeNode?, list: MutableList<MethodNode>) {
if (node == null) return
list.addAll(node.data.methods as List<MethodNode>)
allMethodsTo(node.parent, list)
}
val list = arrayListOf<MethodNode>()
allMethodsTo(node, list)
return list
}
} | apache-2.0 | bf207bb09dd0efcc3ed40c264267dc19 | 32.092593 | 116 | 0.636058 | 4.712401 | false | false | false | false |
STUDIO-apps/GeoShare_Android | mobile/src/main/java/uk/co/appsbystudio/geoshare/utils/Connectivity.kt | 1 | 862 | package uk.co.appsbystudio.geoshare.utils
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkInfo
private fun getNetworkInfo(context: Context): NetworkInfo? {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return connectivityManager.activeNetworkInfo
}
fun isConnected(context: Context): Boolean {
val info = getNetworkInfo(context)
return info != null && info.isConnected
}
fun isConnectedWifi(context: Context): Boolean {
val info = getNetworkInfo(context)
return info != null && info.isConnected && info.type == ConnectivityManager.TYPE_WIFI
}
fun isConnectedMobile(context: Context): Boolean {
val info = getNetworkInfo(context)
return info != null && info.isConnected && info.type == ConnectivityManager.TYPE_MOBILE
}
| apache-2.0 | c6da20d3e279c2fceaa88a101ab8a0c8 | 33.48 | 107 | 0.772622 | 4.762431 | false | false | false | false |
STUDIO-apps/GeoShare_Android | mobile/src/main/java/uk/co/appsbystudio/geoshare/friends/profile/friends/pages/all/ProfileFriendsAllInteractorImpl.kt | 1 | 2205 | package uk.co.appsbystudio.geoshare.friends.profile.friends.pages.all
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.*
import uk.co.appsbystudio.geoshare.utils.firebase.FirebaseHelper
class ProfileFriendsAllInteractorImpl: ProfileFriendsAllInteractor {
private lateinit var friendsListener: ChildEventListener
private var friendsRef: DatabaseReference? = null
override fun getFriends(uid: String?, listener: ProfileFriendsAllInteractor.OnFirebaseListener) {
val user = FirebaseAuth.getInstance().currentUser
friendsRef = FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.FRIENDS}/$uid")
friendsListener = object : ChildEventListener {
override fun onChildAdded(dataSnapshot: DataSnapshot, string: String?) {
if (dataSnapshot.key != user?.uid) listener.add(dataSnapshot.key)
}
override fun onChildChanged(dataSnapshot: DataSnapshot, string: String?) {
}
override fun onChildRemoved(dataSnapshot: DataSnapshot) {
listener.remove(dataSnapshot.key)
}
override fun onChildMoved(dataSnapshot: DataSnapshot, string: String?) {
}
override fun onCancelled(databaseError: DatabaseError) {
listener.error(databaseError.message)
}
}
friendsRef?.addChildEventListener(friendsListener)
}
override fun sendFriendRequest(uid: String?, listener: ProfileFriendsAllInteractor.OnFirebaseListener) {
val user = FirebaseAuth.getInstance().currentUser
FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.PENDING}/${user?.uid}/$uid/outgoing").setValue(true)
.addOnSuccessListener {
listener.success("Friend request sent")
}.addOnFailureListener {
listener.error(it.message.toString())
}
FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.PENDING}/$uid/${user?.uid}/outgoing").setValue(false)
}
override fun removeListener() {
friendsRef?.removeEventListener(friendsListener)
}
} | apache-2.0 | cd49e3637d58a650d60841bbfd25686e | 38.392857 | 126 | 0.680726 | 5.582278 | false | false | false | false |
carlphilipp/chicago-commutes | android-app/src/main/kotlin/fr/cph/chicago/core/model/TrainEta.kt | 1 | 3920 | /**
* Copyright 2021 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.core.model
import android.os.Parcel
import android.os.Parcelable
import fr.cph.chicago.core.model.enumeration.TrainLine
import java.io.Serializable
import java.util.Date
import java.util.Locale
import java.util.concurrent.TimeUnit
import org.apache.commons.lang3.StringUtils
/**
* TrainEta entity
*
* @author Carl-Philipp Harmant
* @version 1
*/
data class TrainEta(
val trainStation: TrainStation,
val stop: Stop,
val routeName: TrainLine,
val destName: String,
private val predictionDate: Date,
private val arrivalDepartureDate: Date,
private val isApp: Boolean,
private var isDly: Boolean) : Comparable<TrainEta>, Parcelable, Serializable {
companion object {
private const val serialVersionUID = 0L
fun buildFakeEtaWith(trainStation: TrainStation, arrivalDepartureDate: Date, predictionDate: Date, app: Boolean, delay: Boolean): TrainEta {
return TrainEta(trainStation, Stop.buildEmptyStop(), TrainLine.NA, StringUtils.EMPTY, predictionDate, arrivalDepartureDate, app, delay)
}
@JvmField
val CREATOR: Parcelable.Creator<TrainEta> = object : Parcelable.Creator<TrainEta> {
override fun createFromParcel(source: Parcel): TrainEta {
return TrainEta(source)
}
override fun newArray(size: Int): Array<TrainEta?> {
return arrayOfNulls(size)
}
}
}
constructor(source: Parcel) : this(
trainStation = source.readParcelable<TrainStation>(TrainStation::class.java.classLoader)
?: TrainStation.buildEmptyStation(),
stop = source.readParcelable<Stop>(Stop::class.java.classLoader) ?: Stop.buildEmptyStop(),
routeName = TrainLine.fromXmlString(source.readString() ?: StringUtils.EMPTY),
destName = source.readString() ?: StringUtils.EMPTY,
predictionDate = Date(source.readLong()),
arrivalDepartureDate = Date(source.readLong()),
isApp = source.readString()?.toBoolean() ?: false,
isDly = source.readString()?.toBoolean() ?: false
)
private val timeLeft: String
get() {
val time = arrivalDepartureDate.time - predictionDate.time
return String.format(Locale.ENGLISH, "%d min", TimeUnit.MILLISECONDS.toMinutes(time))
}
val timeLeftDueDelay: String
get() {
return if (isDly) {
"Delay"
} else {
if (isApp) "Due" else timeLeft
}
}
override fun compareTo(other: TrainEta): Int {
val time1 = arrivalDepartureDate.time - predictionDate.time
val time2 = other.arrivalDepartureDate.time - other.predictionDate.time
return time1.compareTo(time2)
}
override fun describeContents(): Int {
return 0
}
override fun writeToParcel(dest: Parcel, flags: Int) {
with(dest) {
writeParcelable(trainStation, flags)
writeParcelable(stop, flags)
writeString(routeName.toTextString())
writeString(destName)
writeLong(predictionDate.time)
writeLong(arrivalDepartureDate.time)
writeString(isApp.toString())
writeString(isDly.toString())
}
}
}
| apache-2.0 | 5b03402d05657bcc7ee1da9168960a2f | 33.086957 | 148 | 0.6625 | 4.639053 | false | false | false | false |
kotlintest/kotlintest | kotest-assertions/src/jvmTest/kotlin/com/sksamuel/kotest/throwablehandling/AnyThrowableHandlingTest.kt | 1 | 3241 | package com.sksamuel.kotest.throwablehandling
import io.kotest.assertions.throwables.shouldNotThrowAny
import io.kotest.assertions.throwables.shouldNotThrowAnyUnit
import io.kotest.assertions.throwables.shouldThrowAny
import io.kotest.assertions.throwables.shouldThrowAnyUnit
import io.kotest.core.spec.style.FreeSpec
import io.kotest.matchers.booleans.shouldBeTrue
import io.kotest.matchers.shouldBe
import io.kotest.matchers.types.shouldBeInstanceOf
import io.kotest.matchers.types.shouldBeSameInstanceAs
class AnyThrowableHandlingTest : FreeSpec() {
init {
onShouldThrowAnyMatcher { shouldThrowAnyMatcher ->
"Should throw any ($shouldThrowAnyMatcher)" - {
"Should throw an exception" - {
"When no exception is thrown in the code" {
verifyThrowsNoExceptionError {
shouldThrowAnyMatcher { /* No exception being thrown */ }
}
}
}
"Should return the thrown instance" - {
"When an exception is thrown in the code" {
val instanceToThrow = FooRuntimeException()
verifyReturnsExactly(instanceToThrow) {
shouldThrowAnyMatcher { throw instanceToThrow }
}
}
}
}
}
onShouldNotThrowAnyMatcher { shouldNotThrowAnyMatcher ->
"Should not throw any($shouldNotThrowAnyMatcher)" - {
"Should throw an exception" - {
"When any exception is thrown in the code" {
val exception = FooRuntimeException()
verifyThrowsAssertionWrapping(exception) {
shouldNotThrowAnyMatcher { throw exception }
}
}
}
"Should not throw an exception" - {
"When no exception is thrown in the code" {
verifyNoErrorIsThrown {
shouldNotThrowAnyMatcher { /* Nothing thrown */ }
}
}
}
}
}
}
private inline fun onShouldThrowAnyMatcher(func: (ShouldThrowAnyMatcher) -> Unit) {
func(::shouldThrowAny)
func(::shouldThrowAnyUnit)
}
private fun verifyThrowsNoExceptionError(block: () -> Unit) {
val thrown = catchThrowable(block)
thrown.shouldBeInstanceOf<AssertionError>()
thrown!!.message shouldBe "Expected a throwable, but nothing was thrown."
}
private fun verifyReturnsExactly(thrownInstance: Throwable, block: () -> Any?) {
val actualReturn = block()
(actualReturn === thrownInstance).shouldBeTrue()
}
private inline fun onShouldNotThrowAnyMatcher(func: (ShouldNotThrowAnyMatcher) -> Unit) {
func(::shouldNotThrowAny)
func(::shouldNotThrowAnyUnit)
}
private fun verifyThrowsAssertionWrapping(throwable: Throwable, block: () -> Any?) {
val thrownException = catchThrowable(block)
thrownException.shouldBeInstanceOf<AssertionError>()
thrownException!!.message shouldBe "No exception expected, but a ${throwable::class.simpleName} was thrown."
thrownException.cause shouldBeSameInstanceAs throwable
}
private fun verifyNoErrorIsThrown(block: () -> Unit) {
catchThrowable(block) shouldBe null
}
}
private typealias ShouldThrowAnyMatcher = (() -> Unit) -> Throwable
private typealias ShouldNotThrowAnyMatcher = (() -> Unit) -> Unit
| apache-2.0 | 199bf3beeda133d63ebc84655bdc886c | 32.071429 | 112 | 0.681271 | 5.087912 | false | true | false | false |
jiaweizhang/pokur | src/main/kotlin/pokur/calculate/HandProcessor.kt | 1 | 30585 | package pokur.calculate
import pokur.Card
/**
* Created by jiaweizhang on 6/12/2017.
*/
class HandProcessor {
private fun getSevenCards(communityCards: List<Card>, holeCards: PlayerHand): List<Card> {
return communityCards.plus(holeCards.holeCards.first).plus(holeCards.holeCards.second)
}
fun rank(communityCards: List<Card>, holeCards: List<PlayerHand>): List<List<RankingUnit>> {
val handRanking = mutableListOf<List<RankingUnit>>()
val temporaryRanking = mutableListOf<RankingUnit>()
holeCards.forEach {
val rank = findHandValue7Complex(getSevenCards(communityCards, it))
temporaryRanking.add(RankingUnit(it, rank))
}
val rankingGroups = temporaryRanking.groupBy { it.rank }
rankingGroups.keys.toSortedSet().reversed().mapTo(handRanking) { rankingGroups.getValue(it) }
return handRanking
}
fun findHandValue7Using5(sevenCards: List<Card>): Int {
val fiveCardsList = listOf(sevenCards.subList(0, 5),
listOf(sevenCards[0], sevenCards[1], sevenCards[2], sevenCards[3], sevenCards[5]),
listOf(sevenCards[0], sevenCards[1], sevenCards[2], sevenCards[3], sevenCards[6]),
listOf(sevenCards[0], sevenCards[1], sevenCards[2], sevenCards[4], sevenCards[5]),
listOf(sevenCards[0], sevenCards[1], sevenCards[2], sevenCards[4], sevenCards[6]),
listOf(sevenCards[0], sevenCards[1], sevenCards[2], sevenCards[5], sevenCards[6]),
listOf(sevenCards[0], sevenCards[1], sevenCards[3], sevenCards[4], sevenCards[5]),
listOf(sevenCards[0], sevenCards[1], sevenCards[3], sevenCards[4], sevenCards[6]),
listOf(sevenCards[0], sevenCards[1], sevenCards[3], sevenCards[5], sevenCards[6]),
listOf(sevenCards[0], sevenCards[1], sevenCards[4], sevenCards[5], sevenCards[6]),
listOf(sevenCards[0], sevenCards[2], sevenCards[3], sevenCards[4], sevenCards[5]),
listOf(sevenCards[0], sevenCards[2], sevenCards[3], sevenCards[4], sevenCards[6]),
listOf(sevenCards[0], sevenCards[2], sevenCards[3], sevenCards[5], sevenCards[6]),
listOf(sevenCards[0], sevenCards[2], sevenCards[4], sevenCards[5], sevenCards[6]),
listOf(sevenCards[0], sevenCards[3], sevenCards[4], sevenCards[5], sevenCards[6]),
listOf(sevenCards[1], sevenCards[2], sevenCards[3], sevenCards[4], sevenCards[5]),
listOf(sevenCards[1], sevenCards[2], sevenCards[3], sevenCards[4], sevenCards[6]),
listOf(sevenCards[1], sevenCards[2], sevenCards[3], sevenCards[5], sevenCards[6]),
listOf(sevenCards[1], sevenCards[2], sevenCards[4], sevenCards[5], sevenCards[6]),
listOf(sevenCards[1], sevenCards[3], sevenCards[4], sevenCards[5], sevenCards[6]),
listOf(sevenCards[2], sevenCards[3], sevenCards[4], sevenCards[5], sevenCards[6]))
return fiveCardsList.map {
findHandValue5(it)
}.max()!!.toInt()
}
fun findHandValue6Using5(sixCards: List<Card>): Int {
val fiveCardsList = listOf(sixCards.subList(0, 5),
listOf(sixCards[0], sixCards[2], sixCards[3], sixCards[4], sixCards[5]),
listOf(sixCards[0], sixCards[1], sixCards[3], sixCards[4], sixCards[5]),
listOf(sixCards[0], sixCards[1], sixCards[2], sixCards[4], sixCards[5]),
listOf(sixCards[0], sixCards[1], sixCards[2], sixCards[3], sixCards[5]),
listOf(sixCards[1], sixCards[2], sixCards[3], sixCards[4], sixCards[5]))
return fiveCardsList.map {
findHandValue5(it)
}.max()!!.toInt()
}
fun findHandValue5(fiveCards: List<Card>): Int {
// find handValue using grouping
var pair1 = -1
var pair2 = -1
var set = -1
var high2 = -1
var high3 = -1
var high4 = -1
val one = fiveCards[0]
val two = fiveCards[1]
val three = fiveCards[2]
val four = fiveCards[3]
val five = fiveCards[4]
// process first card
var high1 = one.face
// process second card
if (two.face == high1) {
// 2
pair1 = high1
high1 = -1
} else {
// 1 1
high2 = two.face
}
// process third card
if (three.face == pair1) {
// 3
set = pair1
pair1 = -1
} else if (pair1 != -1) {
// 2 1
high1 = three.face
} else {
if (three.face == high1) {
// 2 1
pair1 = high1
high1 = high2
high2 = -1
} else if (three.face == high2) {
// 2 1
pair1 = high2
high2 = -1
} else {
// 1 1 1
high3 = three.face
}
}
// process fourth card
if (four.face == set) {
// 4 - can return quad
return (8 shl 20) + (set shl 16) + (five.face shl 12)
} else if (set != -1) {
// 3 1
high1 = four.face
} else {
if (four.face == pair1) {
// 3 1
set = pair1
pair1 = -1
} else if ((pair1 != -1) and (four.face == high1)) {
// 2 2
pair2 = high1
high1 = -1
} else if ((pair1 != -1)) {
high2 = four.face
} else if (four.face == high1) {
// 2 1 1
pair1 = high1
high1 = high2
high2 = high3
high3 = -1
} else if (four.face == high2) {
// 2 1 1
pair1 = high2
high2 = high3
high3 = -1
} else if (four.face == high3) {
// 2 1 1
pair1 = high3
high3 = -1
} else {
// 1 1 1 1
high4 = four.face
}
}
// process fifth card
if (five.face == set) {
// 4 - return quad
return (8 shl 20) + (set shl 16) + (high1 shl 12)
} else {
if ((set != -1) and (five.face == high1)) {
// 3 2 - return FH
return (7 shl 20) + (set shl 16) + (high1 shl 12)
} else if (set != -1) {
// 3 1 1 - return set
return (4 shl 20) + (set shl 16) + ((if (high1 > five.face) high1 else five.face) shl 12) + ((if (high1 > five.face) five.face else high1) shl 8)
} else if (five.face == pair2) {
// 3 2 - return FH
return (7 shl 20) + (pair2 shl 16) + (pair1 shl 12)
} else if ((five.face == pair1) and (pair2 != -1)) {
// 3 2 - return FH
return (7 shl 20) + (pair1 shl 16) + (pair2 shl 12)
} else if ((pair1 != -1) and (pair2 != -1)) {
// 2 2 1
return (3 shl 20) + ((if (pair1 > pair2) pair1 else pair2) shl 16) + ((if (pair1 > pair2) pair2 else pair1) shl 12) + (five.face shl 8)
} else if (five.face == pair1) {
// 3 1 1
return (4 shl 20) + (pair1 shl 16) + ((if (high1 > high2) high1 else high2) shl 12) + ((if (high1 > high2) high2 else high1) shl 8)
} else if ((pair1 != -1) and (five.face == high1)) {
// 2 2 1
return (3 shl 20) + ((if (pair1 > high1) pair1 else high1) shl 16) + ((if (pair1 > high1) high1 else pair1) shl 12) + (high2 shl 8)
} else if ((pair1 != -1) and (five.face == high2)) {
// 2 2 1
return (3 shl 20) + ((if (pair1 > high2) pair1 else high2) shl 16) + ((if (pair1 > high2) high2 else pair1) shl 12) + (high1 shl 8)
} else if ((pair1 != -1)) {
// 2 1 1 1
return (2 shl 20) + (pair1 shl 16) + (order3(high1, high2, five.face) shl 4)
} else if (five.face == high1) {
// 2 1 1 1
return (2 shl 20) + (high1 shl 16) + (order3(high2, high3, high4) shl 4)
} else if (five.face == high2) {
// 2 1 1 1
return (2 shl 20) + (high2 shl 16) + (order3(high1, high3, high4) shl 4)
} else if (five.face == high3) {
// 2 1 1 1
return (2 shl 20) + (high3 shl 16) + (order3(high1, high2, high4) shl 4)
} else if (five.face == high4) {
// 2 1 1 1
return (2 shl 20) + (high4 shl 16) + (order3(high1, high2, high3) shl 4)
} else {
// 1 1 1 1 1
val flush = ((one.suit == two.suit) and (one.suit == three.suit) and (one.suit == four.suit) and (one.suit == five.suit))
val order5 = order5(one.face, two.face, three.face, four.face, five.face)
val straight = order5 and 0b1111
if (flush and (straight != 0)) {
return (9 shl 20) + (straight shl 16)
}
if (flush) {
return (6 shl 20) + (order5 shr 4)
}
if (straight != 0) {
return (5 shl 20) + (straight shl 16)
}
return (1 shl 20) + (order5 shr 4)
}
}
}
fun order3(one: Int, two: Int, three: Int): Int {
var tmp: Int
var a = one
var b = two
var c = three
if (b < c) {
tmp = b
b = c
c = tmp
}
if (a < c) {
tmp = a
a = c
c = tmp
}
if (a < b) {
tmp = a
a = b
b = tmp
}
return (a shl 8) + (b shl 4) + c
}
fun order5(one: Int, two: Int, three: Int, four: Int, five: Int): Int {
var tmp: Int
var a = one
var b = two
var c = three
var d = four
var e = five
if (a < b) {
tmp = a
a = b
b = tmp
}
if (d < e) {
tmp = d
d = e
e = tmp
}
if (c < e) {
tmp = c
c = e
e = tmp
}
if (c < d) {
tmp = c
c = d
d = tmp
}
if (b < e) {
tmp = b
b = e
e = tmp
}
if (a < d) {
tmp = a
a = d
d = tmp
}
if (a < c) {
tmp = a
a = c
c = tmp
}
if (b < d) {
tmp = b
b = d
d = tmp
}
if (b < c) {
tmp = b
b = c
c = tmp
}
val straight = if ((a == b + 1) and (a == c + 2) and (a == d + 3) and (a == e + 4)) {
a
} else if ((a == 12) and (b == 3) and (c == 2) and (d == 1) and (e == 0)) {
3
} else {
0
}
return (a shl 20) + (b shl 16) + (c shl 12) + (d shl 8) + (e shl 4) + straight
}
fun findHandValue7Complex(sevenCards: List<Card>): Int {
var type: Int
val sortedCards = sevenCards.sortedByDescending {
it.face
}
val groupedCards = sevenCards.groupBy {
it.face
}
val first = sortedCards.get(0).face
val second = sortedCards.get(1).face
val third = sortedCards.get(2).face
val fourth = sortedCards.get(3).face
val fifth = sortedCards.get(4).face
val sixth = sortedCards.get(5).face
val seventh = sortedCards.get(6).face
var twoPairTopPair = -1
var twoPairBottomPair = -1
var twoPairKicker = -1
var triple = -1
var tripleKicker = -1
var tripleKicker2 = -1
var pair = -1
var pairKicker = -1
var pairKicker2 = -1
var pairKicker3 = -1
var straightHigh = -1
var spadesCount = 0
var heartsCount = 0
var clubsCount = 0
var diamondsCount = 0
when (groupedCards.size) {
2 -> {
// 4 3 - Q
// if count quad, cannot possibly be SF
if (first == fourth) {
return (8 shl 20) + (first shl 16) + (fifth shl 12)
} else {
return (8 shl 20) + (fourth shl 16) + (first shl 12)
}
}
3 -> {
// 4 2 1 - Q
if (groupedCards.any { it.value.size == 4 }) {
if (first == second) {
if (second == third) {
// quad is top
return (8 shl 20) + (first shl 16) + (fifth shl 12)
} else {
// pair is top
if (third == fourth) {
// quad is after top
return (8 shl 20) + (third shl 16) + (first shl 12)
} else {
// quad is last
return (8 shl 20) + (fourth shl 16) + (first shl 12)
}
}
} else {
if (second == fourth) {
// 1 4 2
return (8 shl 20) + (second shl 16) + (first shl 12)
} else {
// 1 2 4
return (8 shl 20) + (fourth shl 16) + (first shl 12)
}
}
}
// 3 3 1 - FH
else if (groupedCards.any { it.value.size == 1 }) {
if (first == second) {
// 3 3 1 or 3 1 3
if (fourth == fifth) {
// 3 3 1
return (7 shl 20) + (first shl 16) + (fourth shl 12)
} else {
// 3 1 3
return (7 shl 20) + (first shl 16) + (fifth shl 12)
}
} else {
// 1 3 3
return (7 shl 20) + (second shl 16) + (fifth shl 12)
}
}
// 3 2 2 - FH
else {
if (second == third) {
// 3 2 2
return (7 shl 20) + (first shl 16) + (fourth shl 12)
} else if (fourth == fifth) {
// 2 3 2
return (7 shl 20) + (third shl 16) + (first shl 12)
} else {
// 2 2 3
return (7 shl 20) + (fifth shl 16) + (first shl 12)
}
}
}
4 -> {
// 4 1 1 1
if (groupedCards.any { it.value.size == 4 }) {
if (first == second) {
// 4 1 1 1
return (8 shl 20) + (first shl 16) + (fifth shl 12)
} else if (second == third) {
// 1 4 1 1
return (8 shl 20) + (second shl 16) + (first shl 12)
} else if (third == fourth) {
// 1 1 4 1
return (8 shl 20) + (third shl 16) + (first shl 12)
} else {
// 1 1 1 4
return (8 shl 20) + (fourth shl 16) + (first shl 12)
}
}
// 3 2 1 1
else if (groupedCards.any { it.value.size == 3 }) {
val advancedGroupedCards = sevenCards.groupingBy({
it.face
}).eachCount()
// triple and pair
var fhTriple = -1
var fhPair = -1
advancedGroupedCards.forEach {
if (it.value == 3) {
fhTriple = it.key
} else if (it.value == 2) {
fhPair = it.key
}
}
return (7 shl 20) + (fhTriple shl 16) + (fhPair shl 12)
}
// 2 2 2 1
else {
type = 3
if (first != second) {
// 1 2 2 2
twoPairTopPair = second
twoPairBottomPair = fourth
twoPairKicker = first
} else if (sixth != seventh) {
// 2 2 2 1
twoPairTopPair = first
twoPairBottomPair = third
twoPairKicker = fifth
} else if (fourth != fifth) {
// 2 2 1 2
twoPairTopPair = first
twoPairBottomPair = third
twoPairKicker = fifth
} else {
// 2 1 2 2
twoPairTopPair = first
twoPairBottomPair = fourth
twoPairKicker = third
}
}
}
5 -> {
// 3 1 1 1 1
if (groupedCards.any { it.value.size == 3 }) {
type = 4
if (first == second) {
// 3 1 1 1 1
triple = first
tripleKicker = fourth
tripleKicker2 = fifth
} else if (second == third) {
// 1 3 1 1 1
triple = second
tripleKicker = first
tripleKicker2 = fifth
} else if (third == fourth) {
// 1 1 3 1 1
triple = third
tripleKicker = first
tripleKicker2 = second
} else if (fourth == fifth) {
// 1 1 1 3 1
triple = fourth
tripleKicker = first
tripleKicker2 = second
} else {
// 1 1 1 1 3
triple = fifth
tripleKicker = first
tripleKicker2 = second
}
}
// 2 2 1 1 1
else {
type = 3
if (first == second) {
twoPairTopPair = first
if (third == fourth) {
// 2 2 1 1 1
twoPairBottomPair = third
twoPairKicker = fifth
} else if (fourth == fifth) {
// 2 1 2 1 1
twoPairBottomPair = fourth
twoPairKicker = third
} else if (fifth == sixth) {
// 2 1 1 2 1
twoPairBottomPair = fifth
twoPairKicker = third
} else {
// 2 1 1 1 2
twoPairBottomPair = sixth
twoPairKicker = third
}
} else {
twoPairKicker = first
if (second == third) {
twoPairTopPair = second
if (fourth == fifth) {
// 1 2 2 1 1
twoPairBottomPair = fourth
} else if (fifth == sixth) {
// 1 2 1 2 1
twoPairBottomPair = fifth
} else {
// 1 2 1 1 2
twoPairBottomPair = sixth
}
} else if (third == fourth) {
twoPairTopPair = third
if (fifth == sixth) {
// 1 1 2 2 1
twoPairBottomPair = fifth
} else {
// 1 1 2 1 2
twoPairBottomPair = sixth
}
} else {
// 1 1 1 2 2
twoPairTopPair = fourth
twoPairBottomPair = sixth
}
}
}
}
6 -> {
type = 2
if (first == second) {
// 2 1 1 1 1 1
pair = first
pairKicker = third
pairKicker2 = fourth
pairKicker3 = fifth
} else if (second == third) {
// 1 2 1 1 1 1
pair = second
pairKicker = first
pairKicker2 = fourth
pairKicker3 = fifth
} else if (third == fourth) {
// 1 1 2 1 1 1
pair = third
pairKicker = first
pairKicker2 = second
pairKicker3 = fifth
} else if (fourth == fifth) {
// 1 1 1 2 1 1
pair = fourth
pairKicker = first
pairKicker2 = second
pairKicker3 = third
} else if (fifth == sixth) {
// 1 1 1 1 2 1
pair = fifth
pairKicker = first
pairKicker2 = second
pairKicker3 = third
} else {
// 1 1 1 1 1 2
pair = sixth
pairKicker = first
pairKicker2 = second
pairKicker3 = third
}
}
else -> {
type = 1
}
}
sevenCards.forEach {
// fill suits - technically don't need to iterate all 7
val suit = it.suit
if (suit == 'S') {
spadesCount++
} else if (suit == 'H') {
heartsCount++
} else if (suit == 'C') {
clubsCount++
} else if (suit == 'D') {
diamondsCount++
}
}
// is flush
val flushSuit = when {
spadesCount >= 5 -> 'S'
heartsCount >= 5 -> 'H'
clubsCount >= 5 -> 'C'
diamondsCount >= 5 -> 'D'
else -> 'N'
}
// look for straight
val distinctCards = sortedCards.distinctBy {
it.face
}
if (distinctCards.size == 5) {
if (distinctCards.get(0).face == distinctCards.get(4).face + 4) {
// straight
type = 5
straightHigh = distinctCards.get(0).face
if (findStraightFlush(flushSuit, straightHigh, groupedCards)) {
return (9 shl 20) + (straightHigh shl 16)
}
}
if ((distinctCards.get(1).face == 3)
and (distinctCards.get(4).face == 0)
and (distinctCards.get(0).face == 12)) {
// 5-high straight
type = 5
if (straightHigh < 3) {
straightHigh = 3
}
if (findFiveHighStraightFlush(flushSuit, groupedCards)) {
return (9 shl 20) + (3 shl 16)
}
}
} else if (distinctCards.size == 6) {
if (distinctCards.get(0).face == distinctCards.get(4).face + 4) {
// straight
type = 5
straightHigh = distinctCards.get(0).face
if (findStraightFlush(flushSuit, straightHigh, groupedCards)) {
return (9 shl 20) + (straightHigh shl 16)
}
}
if (distinctCards.get(1).face == distinctCards.get(5).face + 4) {
type = 5
if (straightHigh < distinctCards.get(1).face) {
straightHigh = distinctCards.get(1).face
}
if (findStraightFlush(flushSuit, distinctCards.get(1).face, groupedCards)) {
return (9 shl 20) + (distinctCards.get(1).face shl 16)
}
}
if ((distinctCards.get(2).face == 3)
and (distinctCards.get(5).face == 0)
and (distinctCards.get(0).face == 12)) {
// 5-high straight
type = 5
if (straightHigh < 3) {
straightHigh = 3
}
if (findFiveHighStraightFlush(flushSuit, groupedCards)) {
return (9 shl 20) + (3 shl 16)
}
}
} else if (distinctCards.size == 7) {
// size 7 - all different digits
if (distinctCards.get(0).face == distinctCards.get(4).face + 4) {
type = 5
straightHigh = distinctCards.get(0).face
if (findStraightFlush(flushSuit, straightHigh, groupedCards)) {
return (9 shl 20) + (straightHigh shl 16)
}
}
if (distinctCards.get(1).face == distinctCards.get(5).face + 4) {
type = 5
if (straightHigh < distinctCards.get(1).face) {
straightHigh = distinctCards.get(1).face
}
if (findStraightFlush(flushSuit, distinctCards.get(1).face, groupedCards)) {
return (9 shl 20) + (distinctCards.get(1).face shl 16)
}
}
if (distinctCards.get(2).face == distinctCards.get(6).face + 4) {
type = 5
if (straightHigh < distinctCards.get(2).face) {
straightHigh = distinctCards.get(2).face
}
if (findStraightFlush(flushSuit, distinctCards.get(2).face, groupedCards)) {
return (9 shl 20) + (distinctCards.get(2).face shl 16)
}
}
if ((distinctCards.get(3).face == 3)
and (distinctCards.get(6).face == 0)
and (distinctCards.get(0).face == 12)) {
// 5-high straight
type = 5
if (straightHigh < 3) {
straightHigh = 3
}
if (findFiveHighStraightFlush(flushSuit, groupedCards)) {
return (9 shl 20) + (3 shl 16)
}
}
}
// SF, Q, and FH have returned
// return flush
if (flushSuit != 'N') {
// get five highest of suit
val sortedFlush = sortedCards.filter {
it.suit == flushSuit
}
return (6 shl 20) + (sortedFlush.get(0).face shl 16) + (sortedFlush.get(1).face shl 12) + (sortedFlush.get(2).face shl 8) + (sortedFlush.get(3).face shl 4) + (sortedFlush.get(4).face)
}
// return straight
if (type == 5) {
return (5 shl 20) + (straightHigh shl 16)
}
// return triple
if (type == 4) {
return (4 shl 20) + (triple shl 16) + (tripleKicker shl 12) + (tripleKicker2 shl 8)
}
// two pair
if (type == 3) {
return (3 shl 20) + (twoPairTopPair shl 16) + (twoPairBottomPair shl 12) + (twoPairKicker shl 8)
}
// pair
if (type == 2) {
return (2 shl 20) + (pair shl 16) + (pairKicker shl 12) + (pairKicker2 shl 8) + (pairKicker3 shl 4)
}
if (type == 1) {
return (1 shl 20) + (first shl 16) + (second shl 12) + (third shl 8) + (fourth shl 4) + fifth
}
throw Exception("Impossible type")
}
fun findStraightFlush(flushSuit: Char, straightHigh: Int, groupedCards: Map<Int, List<Card>>): Boolean {
if (flushSuit != 'N') {
// check series of 5 for flush
var isStraightFlush = true
for (i in straightHigh.downTo(straightHigh - 4)) {
var suitFoundInCurrent = false
for (j in groupedCards.getValue(i)) {
if (j.suit == flushSuit) {
suitFoundInCurrent = true
break
}
}
if (!suitFoundInCurrent) {
isStraightFlush = false
}
}
if (isStraightFlush) {
return true
}
}
return false
}
fun findFiveHighStraightFlush(flushSuit: Char, groupedCards: Map<Int, List<Card>>): Boolean {
if (flushSuit != 'N') {
var isStraightFlush = true
for (i in 0..3) {
var suitFoundInCurrent = false
for (j in groupedCards.getValue(i)) {
if (j.suit == flushSuit) {
suitFoundInCurrent = true
break
}
}
if (!suitFoundInCurrent) {
isStraightFlush = false
}
}
var aceSuitCorrect = false
for (i in groupedCards.getValue(12)) {
if (i.suit == flushSuit) {
aceSuitCorrect = true
}
}
if (isStraightFlush and aceSuitCorrect) {
return true
}
}
return false
}
} | gpl-3.0 | bb3a384745743d344917d04d407aa6c4 | 36.073939 | 195 | 0.398496 | 4.764019 | false | false | false | false |
alessio-b-zak/myRivers | android/app/src/main/java/com/epimorphics/android/myrivers/models/InputStreamToCDEClassification.kt | 1 | 3422 | package com.epimorphics.android.myrivers.models
import android.util.JsonReader
import com.epimorphics.android.myrivers.data.CDEPoint
import com.epimorphics.android.myrivers.data.Classification
import com.epimorphics.android.myrivers.helpers.InputStreamHelper
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
/**
* Consumes an InputStream and converts it to Classification
*
* @see Classification
*/
class InputStreamToCDEClassification : InputStreamHelper() {
/**
* Converts InputStream to JsonReader and consumes it.
*
* @param cdePoint CDEPoint to which parsed Classification belongs
* @param inputStream InputStream to be consumed
* @param group a name of the group of the Classifications
*
* @throws IOException
*/
@Throws(IOException::class)
fun readJsonStream(cdePoint: CDEPoint, inputStream: InputStream, group: String) {
val reader = JsonReader(InputStreamReader(inputStream, "UTF-8"))
reader.isLenient = true
reader.use {
readMessagesArray(cdePoint, reader, group)
}
}
/**
* Focuses on the array of objects that are to be converted to Classifications and parses
* them one by one.
*
* @param cdePoint CDEPoint to which parsed Classification belongs
* @param reader JsonReader to be consumed
* @param group a name of the group of the Classifications
*
* @throws IOException
*/
@Throws(IOException::class)
fun readMessagesArray(cdePoint: CDEPoint, reader: JsonReader, group: String) {
reader.beginObject()
while (reader.hasNext()) {
val name = reader.nextName()
if (name == "items") {
reader.beginArray()
while (reader.hasNext()) {
readMessage(cdePoint, reader, group)
}
reader.endArray()
} else {
reader.skipValue()
}
}
reader.endObject()
}
/**
* Converts single JsonObject to Classification and adds it to the given CDEPoint's
* classificationHashMap for a given group.
*
* @param cdePoint CDEPoint to which parsed Classification belongs
* @param reader JsonReader to be consumed
* @param group a name of the group of the Classifications
*
* @throws IOException
*/
@Throws(IOException::class)
fun readMessage(cdePoint: CDEPoint, reader: JsonReader, group: String) {
var item = ""
var certainty = ""
var value = ""
var year = ""
reader.beginObject()
while (reader.hasNext()) {
val name = reader.nextName()
when (name) {
"classificationCertainty" -> certainty = readItemToString(reader)
"classificationItem" -> item = readItemToString(reader)
"classificationValue" -> value = readItemToString(reader)
"classificationYear" -> year = reader.nextString()
else -> reader.skipValue()
}
}
reader.endObject()
if (certainty == "No Information") {
certainty = "No Info"
}
if (!cdePoint.getClassificationHashMap(group).containsKey(item)) {
cdePoint.getClassificationHashMap(group).put(item, Classification(value, certainty, year))
}
}
} | mit | 3e953855754bf676ef1dfa819a7152f0 | 32.23301 | 102 | 0.624781 | 5.054653 | false | false | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/network/gson/LocationsTypeAdapter.kt | 1 | 4735 | package mil.nga.giat.mage.network.gson
import android.util.Log
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
import mil.nga.giat.mage.sdk.datastore.location.Location
import mil.nga.giat.mage.sdk.datastore.location.LocationProperty
import mil.nga.giat.mage.sdk.utils.ISO8601DateFormatFactory
import java.io.IOException
import java.io.Serializable
import java.text.ParseException
class LocationsTypeAdapter: TypeAdapter<List<Location>>() {
private val geometryDeserializer = GeometryTypeAdapter()
override fun write(out: JsonWriter, value: List<Location>) {
throw UnsupportedOperationException()
}
override fun read(reader: JsonReader): List<Location> {
val locations = mutableListOf<Location>()
if (reader.peek() != JsonToken.BEGIN_ARRAY) {
reader.skipValue()
return locations
}
reader.beginArray()
while (reader.hasNext()) {
locations.addAll(readUserLocations(reader))
}
reader.endArray()
return locations
}
@Throws(IOException::class)
private fun readUserLocations(reader: JsonReader): List<Location> {
val locations = mutableListOf<Location>()
if (reader.peek() != JsonToken.BEGIN_OBJECT) {
reader.skipValue()
return locations
}
reader.beginObject()
while(reader.hasNext()) {
when(reader.nextName()) {
"locations" -> locations.addAll(readLocations(reader))
else -> reader.skipValue()
}
}
reader.endObject()
return locations
}
@Throws(IOException::class)
private fun readLocations(reader: JsonReader): List<Location> {
val locations = mutableListOf<Location>()
if (reader.peek() != JsonToken.BEGIN_ARRAY) {
reader.skipValue()
return locations
}
reader.beginArray()
while(reader.hasNext()) {
locations.add(readLocation(reader))
}
reader.endArray()
return locations
}
@Throws(IOException::class)
private fun readLocation(reader: JsonReader): Location {
val location = Location()
if (reader.peek() != JsonToken.BEGIN_OBJECT) {
reader.skipValue()
return location
}
reader.beginObject()
var userId: String? = null
var properties = mutableListOf<LocationProperty>()
while(reader.hasNext()) {
when(reader.nextName()) {
"_id" -> location.remoteId = reader.nextString()
"type" -> location.type = reader.nextString()
"geometry" -> location.geometry = geometryDeserializer.read(reader)
"properties" -> properties = readProperties(reader, location)
"userId" -> userId = reader.nextString()
else -> reader.skipValue()
}
}
// don't set the user at this time, only the id. Set it later.
properties.add(LocationProperty("userId", userId))
location.properties = properties
val propertiesMap = location.propertiesMap
// timestamp is special pull it out of properties and set it at the top level
propertiesMap["timestamp"]?.value?.toString()?.let {
try {
location.timestamp = ISO8601DateFormatFactory.ISO8601().parse(it)
} catch (e: ParseException) {
Log.w(LOG_NAME, "Unable to parse date: " + it + " for location: " + location.remoteId, e)
}
}
reader.endObject()
return location
}
@Throws(IOException::class)
private fun readProperties(reader: JsonReader, location: Location): MutableList<LocationProperty> {
val properties = mutableListOf<LocationProperty>()
if (reader.peek() != JsonToken.BEGIN_OBJECT) {
reader.skipValue()
return properties
}
reader.beginObject()
while(reader.hasNext()) {
val key = reader.nextName()
if (reader.peek() == JsonToken.BEGIN_OBJECT || reader.peek() == JsonToken.BEGIN_ARRAY) {
reader.skipValue()
} else {
val value: Serializable? = when(reader.peek()) {
JsonToken.NUMBER -> reader.nextNumberOrNull()
JsonToken.BOOLEAN -> reader.nextBooleanOrNull()
else -> reader.nextStringOrNull()
}
if (value != null) {
val property = LocationProperty(key, value)
property.location = location
properties.add(property)
}
}
}
reader.endObject()
return properties
}
companion object {
private val LOG_NAME = LocationsTypeAdapter::class.java.name
}
} | apache-2.0 | c09a11afae2ac9ff83f966d64ba5c056 | 27.878049 | 102 | 0.626399 | 4.702085 | false | false | false | false |
ze-pequeno/okhttp | okhttp/src/jvmMain/kotlin/okhttp3/ResponseBody.kt | 3 | 6029 | /*
* Copyright (C) 2014 Square, 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 okhttp3
import java.io.Closeable
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.io.Reader
import java.nio.charset.Charset
import okhttp3.internal.charset
import okhttp3.internal.chooseCharset
import okhttp3.internal.commonAsResponseBody
import okhttp3.internal.commonByteString
import okhttp3.internal.commonBytes
import okhttp3.internal.commonClose
import okhttp3.internal.commonToResponseBody
import okhttp3.internal.readBomAsCharset
import okio.Buffer
import okio.BufferedSource
import okio.ByteString
actual abstract class ResponseBody : Closeable {
/** Multiple calls to [charStream] must return the same instance. */
private var reader: Reader? = null
actual abstract fun contentType(): MediaType?
actual abstract fun contentLength(): Long
fun byteStream(): InputStream = source().inputStream()
actual abstract fun source(): BufferedSource
@Throws(IOException::class)
actual fun bytes() = commonBytes()
@Throws(IOException::class)
actual fun byteString() = commonByteString()
/**
* Returns the response as a character stream.
*
* If the response starts with a
* [Byte Order Mark (BOM)](https://en.wikipedia.org/wiki/Byte_order_mark), it is consumed and
* used to determine the charset of the response bytes.
*
* Otherwise if the response has a `Content-Type` header that specifies a charset, that is used
* to determine the charset of the response bytes.
*
* Otherwise the response bytes are decoded as UTF-8.
*/
fun charStream(): Reader = reader ?: BomAwareReader(source(), charset()).also {
reader = it
}
@Throws(IOException::class)
actual fun string(): String = source().use { source ->
source.readString(charset = source.readBomAsCharset(charset()))
}
private fun charset() = contentType().charset()
actual override fun close() = commonClose()
internal class BomAwareReader(
private val source: BufferedSource,
private val charset: Charset
) : Reader() {
private var closed: Boolean = false
private var delegate: Reader? = null
@Throws(IOException::class)
override fun read(cbuf: CharArray, off: Int, len: Int): Int {
if (closed) throw IOException("Stream closed")
val finalDelegate = delegate ?: InputStreamReader(
source.inputStream(),
source.readBomAsCharset(charset)).also {
delegate = it
}
return finalDelegate.read(cbuf, off, len)
}
@Throws(IOException::class)
override fun close() {
closed = true
delegate?.close() ?: run { source.close() }
}
}
actual companion object {
@JvmStatic
@JvmName("create")
actual fun String.toResponseBody(contentType: MediaType?): ResponseBody {
val (charset, finalContentType) = contentType.chooseCharset()
val buffer = Buffer().writeString(this, charset)
return buffer.asResponseBody(finalContentType, buffer.size)
}
@JvmStatic
@JvmName("create")
actual fun ByteArray.toResponseBody(contentType: MediaType?): ResponseBody = commonToResponseBody(contentType)
@JvmStatic
@JvmName("create")
actual fun ByteString.toResponseBody(contentType: MediaType?): ResponseBody = commonToResponseBody(contentType)
@JvmStatic
@JvmName("create")
actual fun BufferedSource.asResponseBody(
contentType: MediaType?,
contentLength: Long
): ResponseBody = commonAsResponseBody(contentType, contentLength)
@JvmStatic
@Deprecated(
message = "Moved to extension function. Put the 'content' argument first to fix Java",
replaceWith = ReplaceWith(
expression = "content.toResponseBody(contentType)",
imports = ["okhttp3.ResponseBody.Companion.toResponseBody"]
),
level = DeprecationLevel.WARNING)
fun create(contentType: MediaType?, content: String): ResponseBody = content.toResponseBody(contentType)
@JvmStatic
@Deprecated(
message = "Moved to extension function. Put the 'content' argument first to fix Java",
replaceWith = ReplaceWith(
expression = "content.toResponseBody(contentType)",
imports = ["okhttp3.ResponseBody.Companion.toResponseBody"]
),
level = DeprecationLevel.WARNING)
fun create(contentType: MediaType?, content: ByteArray): ResponseBody = content.toResponseBody(contentType)
@JvmStatic
@Deprecated(
message = "Moved to extension function. Put the 'content' argument first to fix Java",
replaceWith = ReplaceWith(
expression = "content.toResponseBody(contentType)",
imports = ["okhttp3.ResponseBody.Companion.toResponseBody"]
),
level = DeprecationLevel.WARNING)
fun create(contentType: MediaType?, content: ByteString): ResponseBody = content.toResponseBody(contentType)
@JvmStatic
@Deprecated(
message = "Moved to extension function. Put the 'content' argument first to fix Java",
replaceWith = ReplaceWith(
expression = "content.asResponseBody(contentType, contentLength)",
imports = ["okhttp3.ResponseBody.Companion.asResponseBody"]
),
level = DeprecationLevel.WARNING)
fun create(
contentType: MediaType?,
contentLength: Long,
content: BufferedSource
): ResponseBody = content.asResponseBody(contentType, contentLength)
}
}
| apache-2.0 | 93f44461b1793403fbdbc3aa3e3b105a | 33.649425 | 115 | 0.706585 | 4.769778 | false | false | false | false |
facebook/litho | litho-core-kotlin/src/main/kotlin/com/facebook/litho/flexbox/FlexboxStyle.kt | 1 | 11435 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho.flexbox
import com.facebook.litho.Border
import com.facebook.litho.Component
import com.facebook.litho.ComponentContext
import com.facebook.litho.Dimen
import com.facebook.litho.Style
import com.facebook.litho.StyleItem
import com.facebook.litho.StyleItemField
import com.facebook.litho.exhaustive
import com.facebook.litho.getCommonPropsHolder
import com.facebook.yoga.YogaAlign
import com.facebook.yoga.YogaDirection
import com.facebook.yoga.YogaEdge
import com.facebook.yoga.YogaPositionType
/** Enums for [FlexboxDimenStyleItem]. */
@PublishedApi
internal enum class FlexboxDimenField : StyleItemField {
FLEX_BASIS,
POSITION_ALL,
POSITION_START,
POSITION_TOP,
POSITION_END,
POSITION_BOTTOM,
POSITION_LEFT,
POSITION_RIGHT,
POSITION_HORIZONTAL,
POSITION_VERTICAL,
}
/** Enums for [FlexboxFloatStyleItem]. */
@PublishedApi
internal enum class FlexboxFloatField : StyleItemField {
FLEX,
FLEX_GROW,
FLEX_SHRINK,
FLEX_BASIS_PERCENT,
ASPECT_RATIO,
}
/** Enums for [FlexboxObjectStyleItem]. */
@PublishedApi
internal enum class FlexboxObjectField : StyleItemField {
ALIGN_SELF,
BORDER,
LAYOUT_DIRECTION,
MARGIN_AUTO,
POSITION_TYPE,
IS_REFERENCE_BASELINE,
USE_HEIGHT_AS_BASELINE,
}
/** Common style item for all dimen styles. See note on [FlexboxDimenField] about this pattern. */
@PublishedApi
internal data class FlexboxDimenStyleItem(
override val field: FlexboxDimenField,
override val value: Dimen
) : StyleItem<Dimen> {
override fun applyToComponent(context: ComponentContext, component: Component) {
val commonProps = component.getCommonPropsHolder()
val pixelValue = value.toPixels(context.resourceResolver)
when (field) {
FlexboxDimenField.FLEX_BASIS -> commonProps.flexBasisPx(pixelValue)
FlexboxDimenField.POSITION_ALL -> commonProps.positionPx(YogaEdge.ALL, pixelValue)
FlexboxDimenField.POSITION_START -> commonProps.positionPx(YogaEdge.START, pixelValue)
FlexboxDimenField.POSITION_END -> commonProps.positionPx(YogaEdge.END, pixelValue)
FlexboxDimenField.POSITION_TOP -> commonProps.positionPx(YogaEdge.TOP, pixelValue)
FlexboxDimenField.POSITION_BOTTOM -> commonProps.positionPx(YogaEdge.BOTTOM, pixelValue)
FlexboxDimenField.POSITION_LEFT -> commonProps.positionPx(YogaEdge.LEFT, pixelValue)
FlexboxDimenField.POSITION_RIGHT -> commonProps.positionPx(YogaEdge.RIGHT, pixelValue)
FlexboxDimenField.POSITION_HORIZONTAL ->
commonProps.positionPx(YogaEdge.HORIZONTAL, pixelValue)
FlexboxDimenField.POSITION_VERTICAL -> commonProps.positionPx(YogaEdge.VERTICAL, pixelValue)
}.exhaustive
}
}
/** Common style item for all float styles. See note on [FlexboxDimenField] about this pattern. */
@PublishedApi
internal class FloatStyleItem(override val field: FlexboxFloatField, override val value: Float) :
StyleItem<Float> {
override fun applyToComponent(context: ComponentContext, component: Component) {
val commonProps = component.getCommonPropsHolder()
when (field) {
FlexboxFloatField.FLEX -> commonProps.flex(value)
FlexboxFloatField.FLEX_GROW -> commonProps.flexGrow(value)
FlexboxFloatField.FLEX_SHRINK -> commonProps.flexShrink(value)
FlexboxFloatField.FLEX_BASIS_PERCENT -> commonProps.flexBasisPercent(value)
FlexboxFloatField.ASPECT_RATIO -> commonProps.aspectRatio(value)
}.exhaustive
}
}
/** Common style item for all object styles. See note on [FlexboxDimenField] about this pattern. */
@PublishedApi
internal class FlexboxObjectStyleItem(
override val field: FlexboxObjectField,
override val value: Any?
) : StyleItem<Any?> {
override fun applyToComponent(context: ComponentContext, component: Component) {
val commonProps = component.getCommonPropsHolder()
when (field) {
FlexboxObjectField.ALIGN_SELF -> value?.let { commonProps.alignSelf(it as YogaAlign) }
FlexboxObjectField.BORDER -> commonProps.border(value as Border?)
FlexboxObjectField.LAYOUT_DIRECTION -> commonProps.layoutDirection(value as YogaDirection)
FlexboxObjectField.POSITION_TYPE ->
value?.let { commonProps.positionType(it as YogaPositionType) }
FlexboxObjectField.MARGIN_AUTO -> value?.let { commonProps.marginAuto(it as YogaEdge) }
FlexboxObjectField.IS_REFERENCE_BASELINE ->
value?.let { commonProps.isReferenceBaseline(it as Boolean) }
FlexboxObjectField.USE_HEIGHT_AS_BASELINE ->
value?.let { commonProps.useHeightAsBaseline(it as Boolean) }
}.exhaustive
}
}
/**
* Flex allows you to define how this component should take up space within its parent. It's
* comprised of the following properties:
*
* **flex-grow**: This component should take up remaining space in its parent. If multiple children
* of the parent have a flex-grow set, the extra space is divided up based on proportions of
* flex-grow values, i.e. a child with flex-grow of 2 will get twice as much of the space as its
* sibling with flex-grow of 1.
*
* **flex-shrink**: This component should shrink if necessary. Similar to flex-grow, the value
* determines the proportion of space *taken* from each child. Setting a flex-shink of 0 means the
* child won't shrink.
*
* **flex-basis**: Defines the default size of the component before extra space is distributed. If
* omitted, the measured size of the content (or the width/height styles) will be used instead.
*
* **flex-basis-percent**: see **flex-basis**. Defines the default size as a percentage of its
* parent's size. Values should be from 0 to 100.
*
* - See https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for more documentation on flexbox
* properties.
* - See https://yogalayout.com/ for a web-based playground for trying out flexbox layouts.
*
* Defaults: flex-grow = 0, flex-shrink = 1, flex-basis = null, flex-basis-percent = null
*/
inline fun Style.flex(
grow: Float? = null,
shrink: Float? = null,
basis: Dimen? = null,
basisPercent: Float? = null
): Style =
this +
grow?.let { FloatStyleItem(FlexboxFloatField.FLEX_GROW, it) } +
shrink?.let { FloatStyleItem(FlexboxFloatField.FLEX_SHRINK, it) } +
basis?.let { FlexboxDimenStyleItem(FlexboxDimenField.FLEX_BASIS, it) } +
basisPercent?.let { FloatStyleItem(FlexboxFloatField.FLEX_BASIS_PERCENT, it) }
/**
* Defines how a child should be aligned with a Row or Column, overriding the parent's align-items
* property for this child.
*
* - See https://css-tricks.com/snippets/css/a-guide-to-flexbox/ for more documentation on flexbox
* properties.
* - See https://yogalayout.com/ for a web-based playground for trying out flexbox layouts.
*/
inline fun Style.alignSelf(align: YogaAlign): Style =
this + FlexboxObjectStyleItem(FlexboxObjectField.ALIGN_SELF, align)
/**
* Defines an aspect ratio for this component, meaning the ratio of width to height. This means if
* aspectRatio is set to 2 and width is calculated to be 50px, then height will be 100px.
*
* Note: This property is not part of the flexbox standard.
*/
inline fun Style.aspectRatio(aspectRatio: Float): Style =
this + FloatStyleItem(FlexboxFloatField.ASPECT_RATIO, aspectRatio)
/**
* Used in conjunction with [positionType] to define how a component should be positioned in its
* parent.
*
* For positionType of ABSOLUTE: the values specified here will define how inset the child is from
* the same edge on its parent. E.g. for `position(0.px, 0.px, 0.px, 0.px)`, it will be the full
* size of the parent (no insets). For `position(0.px, 10.px, 0.px, 10.px)`, the child will be the
* full width of the parent, but inset by 10px on the top and bottom.
*
* For positionType of RELATIVE: the values specified here will define how the child is positioned
* relative to where that edge would have normally been positioned.
*
* See https://yogalayout.com/ for a web-based playground for trying out flexbox layouts.
*/
inline fun Style.position(
all: Dimen? = null,
start: Dimen? = null,
top: Dimen? = null,
end: Dimen? = null,
bottom: Dimen? = null,
left: Dimen? = null,
right: Dimen? = null,
vertical: Dimen? = null,
horizontal: Dimen? = null
): Style =
this +
all?.let { FlexboxDimenStyleItem(FlexboxDimenField.POSITION_ALL, it) } +
start?.let { FlexboxDimenStyleItem(FlexboxDimenField.POSITION_START, it) } +
top?.let { FlexboxDimenStyleItem(FlexboxDimenField.POSITION_TOP, it) } +
end?.let { FlexboxDimenStyleItem(FlexboxDimenField.POSITION_END, it) } +
bottom?.let { FlexboxDimenStyleItem(FlexboxDimenField.POSITION_BOTTOM, it) } +
left?.let { FlexboxDimenStyleItem(FlexboxDimenField.POSITION_LEFT, it) } +
right?.let { FlexboxDimenStyleItem(FlexboxDimenField.POSITION_RIGHT, it) } +
vertical?.let { FlexboxDimenStyleItem(FlexboxDimenField.POSITION_VERTICAL, it) } +
horizontal?.let { FlexboxDimenStyleItem(FlexboxDimenField.POSITION_HORIZONTAL, it) }
/** See docs in [position]. */
inline fun Style.positionType(positionType: YogaPositionType): Style =
this + FlexboxObjectStyleItem(FlexboxObjectField.POSITION_TYPE, positionType)
/**
* Describes how a [Border] should be drawn around this component. Setting this property will cause
* the Component to be represented as a View at mount time if it wasn't going to already.
*/
inline fun Style.border(border: Border): Style =
this + FlexboxObjectStyleItem(FlexboxObjectField.BORDER, border)
/**
* Describes the RTL/LTR direction of component. Determines whether {@link YogaEdge#START} and
* {@link YogaEdge#END} will resolve to the left or right side, among other things. INHERIT
* indicates this setting will be inherited from this component's parent. Setting this property will
* cause the Component to be represented as a View at mount time if it wasn't going to already.
*
* <p>Default: {@link YogaDirection#INHERIT}
*/
inline fun Style.layoutDirection(layoutDirection: YogaDirection): Style =
this + FlexboxObjectStyleItem(FlexboxObjectField.LAYOUT_DIRECTION, layoutDirection)
/**
* Sets margin value for specified edge to auto. The item will extend the margin for this edge to
* occupy the extra space in the parent, depending on the direction (Row or Column).
*/
inline fun Style.marginAuto(edge: YogaEdge): Style =
this + FlexboxObjectStyleItem(FlexboxObjectField.MARGIN_AUTO, edge)
inline fun Style.isReferenceBaseline(isReferenceBaseline: Boolean): Style =
this + FlexboxObjectStyleItem(FlexboxObjectField.IS_REFERENCE_BASELINE, isReferenceBaseline)
inline fun Style.useHeightAsBaseline(useHeightAsBaseline: Boolean): Style =
this + FlexboxObjectStyleItem(FlexboxObjectField.USE_HEIGHT_AS_BASELINE, useHeightAsBaseline)
| apache-2.0 | 97fa3cb46b41a484f56908735e54ab1a | 42.980769 | 100 | 0.744993 | 4.318353 | false | false | false | false |
devknightz/MinimalWeatherApp | app/src/main/java/you/devknights/minimalweather/database/entity/WeatherEntity.kt | 1 | 2372 | /*
* Copyright 2017 vinayagasundar
* Copyright 2017 randhirgupta
*
* 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 you.devknights.minimalweather.database.entity
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
import you.devknights.minimalweather.database.WeatherDatabase
/**
* @author Randhir
* @since 6/6/2017.
*/
@Entity(tableName = WeatherDatabase.TABLE_WEATHER)
class WeatherEntity {
@PrimaryKey(autoGenerate = true)
var _id: Long = 0
///////////////////////////////////////////////////////////////////////////
// Place information
///////////////////////////////////////////////////////////////////////////
var placeId: Int = 0
var placeName: String? = null
var placeLat: Double = 0.toDouble()
var placeLon: Double = 0.toDouble()
///////////////////////////////////////////////////////////////////////////
// Weather Information
///////////////////////////////////////////////////////////////////////////
var weatherId: Int = 0
var weatherMain: String? = null
var weatherDescription: String? = null
var weatherIcon: String? = null
///////////////////////////////////////////////////////////////////////////
// Temperature, wind , pressure information
///////////////////////////////////////////////////////////////////////////
var temperature: Float = 0.toFloat()
var pressure: Float = 0.toFloat()
var humidity: Float = 0.toFloat()
var windSpeed: Float = 0.toFloat()
///////////////////////////////////////////////////////////////////////////
// Sunrise and sunset timing information
///////////////////////////////////////////////////////////////////////////
var sunriseTime: Long = 0
var sunsetTime: Long = 0
var startTime: Long = 0
var endTime: Long = 0
}
| apache-2.0 | 57092b3f3d37b4de741f3bf0e74f289c | 31.493151 | 79 | 0.516442 | 5.403189 | false | false | false | false |
facebook/litho | sample/src/main/java/com/facebook/samples/litho/java/lifecycle/LifecycleFragment.kt | 1 | 4269 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.samples.litho.java.lifecycle
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.widget.Button
import android.widget.LinearLayout
import androidx.fragment.app.Fragment
import com.facebook.litho.Column
import com.facebook.litho.Component
import com.facebook.litho.ComponentContext
import com.facebook.litho.LithoLifecycleProvider
import com.facebook.litho.LithoLifecycleProviderDelegate
import com.facebook.litho.LithoView
import com.facebook.samples.litho.R
import java.util.concurrent.atomic.AtomicInteger
class LifecycleFragment : Fragment(), View.OnClickListener {
private var lithoView: LithoView? = null
private var consoleView: ConsoleView? = null
private val consoleDelegateListener = ConsoleDelegateListener()
private val delegateListener: DelegateListener =
object : DelegateListener {
override fun onDelegateMethodCalled(
type: Int,
thread: Thread,
timestamp: Long,
id: String
) {
val prefix = LifecycleDelegateLog.prefix(thread, timestamp, id)
val logRunnable =
ConsoleView.LogRunnable(consoleView, prefix, LifecycleDelegateLog.log(type))
consoleView?.post(logRunnable)
}
override fun setRootComponent(isSync: Boolean) = Unit
}
// start_example_lifecycleprovider
private val delegate: LithoLifecycleProviderDelegate = LithoLifecycleProviderDelegate()
override fun onClick(view: View) {
// Replaces the current fragment with a new fragment
replaceFragment()
// inform the LithoView
delegate.moveToLifecycle(LithoLifecycleProvider.LithoLifecycle.HINT_VISIBLE)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val parent =
inflater.inflate(R.layout.activity_fragment_transactions_lifecycle, container, false)
as ViewGroup
val c = ComponentContext(requireContext())
lithoView =
LithoView.create(
c,
getComponent(c),
delegate /* The LithoLifecycleProvider delegate for this LithoView */)
// end_example_lifecycleprovider
val layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)
layoutParams.weight = 1f
lithoView?.layoutParams = layoutParams
consoleView = ConsoleView(requireContext())
consoleView?.layoutParams = layoutParams
parent.addView(consoleView)
return parent
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val fragmentButton = view.findViewById<Button>(R.id.new_fragment_button)
fragmentButton.text = "New Fragment"
fragmentButton.setOnClickListener(this)
val fragmentLithoView = view.findViewById<ViewGroup>(R.id.fragment_litho_view)
fragmentLithoView.addView(lithoView)
}
private fun getComponent(c: ComponentContext): Component =
Column.create(c)
.child(
LifecycleDelegateComponent.create(c)
.id(atomicId.getAndIncrement().toString())
.delegateListener(delegateListener)
.consoleDelegateListener(consoleDelegateListener)
.build())
.build()
private fun replaceFragment() {
parentFragmentManager
.beginTransaction()
.replace(R.id.fragment_view, LifecycleFragment(), null)
.addToBackStack(null)
.commit()
}
companion object {
private val atomicId = AtomicInteger(0)
}
}
| apache-2.0 | d98e66ddd139412eecdfe914096ffaf6 | 33.427419 | 93 | 0.716093 | 4.840136 | false | false | false | false |
angryziber/picasa-gallery | src/web/RequestRouter.kt | 1 | 5398 | package web
import integration.BackgroundTasks
import integration.OAuth
import photos.AlbumPart
import photos.Cache
import photos.Picasa
import java.util.*
import javax.servlet.FilterChain
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpServletResponse.SC_MOVED_PERMANENTLY
import javax.servlet.http.HttpServletResponse.SC_NOT_FOUND
class RequestRouter(
val req: HttpServletRequest,
val res: HttpServletResponse,
val chain: FilterChain,
val render: Renderer,
var requestedUser: String? = req["by"],
val auth: OAuth = requestedUser?.let { OAuth.auths[it] } ?: OAuth.default,
val picasa: Picasa = Picasa.of(auth)
) {
val userAgent: String = req.getHeader("User-Agent") ?: ""
val path = req.servletPath
val pathParts = path.substring(1).split("/")
val random = req["random"]
val bot = isBot(userAgent) || req["bot"] != null
val reqProps = RequestProps(picasa.urlPrefix, picasa.urlSuffix, req.getHeader("host"), bot, detectMobile())
fun invoke() {
try {
if (req["clear"] != null) Cache.clear()
if (req["reload"] != null) Cache.reload()
when {
"/poll" == path || "/_ah/start" == path -> BackgroundTasks.run().also { res.writer.use { it.write("OK") } }
"/oauth" == path -> handleOAuth()
auth.refreshToken == null -> throw Redirect("/oauth")
random != null -> renderRandom()
(path == null || "/" == path) && requestedUser == null -> throw Redirect(picasa.urlPrefix)
picasa.urlPrefix == path || "/" == path -> renderGallery()
pathParts.size == 1 && path.endsWith(".jpg") -> renderAlbumThumb(pathParts.last().substringBefore(".jpg"))
path.isResource() -> chain.doFilter(req, res)
// pathParts.size == 1 -> throw Redirect(picasa.urlPrefix + path)
pathParts.size == 2 -> renderPhotoPage(pathParts[0], pathParts[1])
else -> renderAlbum(pathParts.last())
}
}
catch (e: Redirect) {
res.status = SC_MOVED_PERMANENTLY
res.setHeader("Location", e.path)
}
catch (e: MissingResourceException) {
res.sendError(SC_NOT_FOUND, e.message)
}
}
private fun String.isResource() = lastIndexOf('.') >= length - 5
private fun renderGallery() {
render(res, picasa.gallery.loadedAt.time) { views.gallery(reqProps, picasa.gallery, auth.profile!!) }
}
private fun renderPhotoPage(albumName: String, photoIdxOrId: String) {
val album = picasa.gallery[albumName] ?: throw Redirect("/")
val photo = picasa.findAlbumPhoto(album, photoIdxOrId) ?: throw Redirect(album.url)
val redirectUrl = "/$albumName${picasa.urlSuffix}#$photoIdxOrId"
render(res) { views.photo(photo, album, auth.profile!!, if (bot) null else redirectUrl) }
}
private fun renderAlbum(name: String) {
val album = picasa.gallery[name] ?: throw Redirect("/")
if (album.id == name && album.id != album.name)
throw Redirect("${album.url}${picasa.urlSuffix}")
val pageToken = req["pageToken"]
val part = if (bot) AlbumPart(picasa.getAlbumPhotos(album), null)
else picasa.getAlbumPhotos(album, pageToken)
if (pageToken == null)
render(res, album.timestamp) { views.album(album, part, auth.profile!!, reqProps) }
else
render(res) { views.albumPart(part, album, reqProps) }
}
private fun renderAlbumThumb(name: String) {
val album = picasa.gallery[name] ?: throw MissingResourceException(path, "", "")
val x2 = req["x2"] != null
val thumbContent = if (x2) album.thumbContent2x else album.thumbContent
if (thumbContent == null) res.sendRedirect(album.baseUrl?.crop(album.thumbSize * (if (x2) 2 else 1)))
else {
res.contentType = "image/jpeg"
res.addIntHeader("Content-Length", thumbContent.size)
res.addDateHeader("Last-Modified", album.timestamp!!)
res.addHeader("Cache-Control", "public, max-age=" + (14 * 24 * 3600))
res.outputStream.write(thumbContent)
}
}
private fun handleOAuth() {
val code = req["code"] ?: throw Redirect(OAuth.startUrl(reqProps.host))
val auth = if (OAuth.default.refreshToken == null) OAuth.default else OAuth(null)
val token = auth.token(code)
auth.profile?.slug?.let {
OAuth.auths[it] = auth
if (!auth.isDefault) throw Redirect("/?by=$it")
}
render(res) { views.oauth(token.refreshToken) }
}
private fun renderRandom() {
if (req.remoteAddr == "82.131.59.12" && isNight())
return render(res) { "<h1>Night mode</h1>" }
val numRandom = if (random.isNotEmpty()) random.toInt() else 1
val randomPhotos = picasa.getRandomPhotos(numRandom)
render(res) { views.random(randomPhotos, req["delay"], req["refresh"] != null) }
}
private fun isNight(): Boolean {
val utcHours = Date().let { it.hours + it.timezoneOffset / 60 }
return utcHours >= 18 || utcHours < 5
}
private fun detectMobile() =
userAgent.contains("Mobile") && !userAgent.contains("iPad") && !userAgent.contains("Tab")
internal fun isBot(userAgent: String) =
userAgent.contains("bot/", true) || userAgent.contains("spider/", true)
}
class Redirect(val path: String): Exception()
class RequestProps(val urlPrefix: String, val urlSuffix: String, val host: String, val bot: Boolean, val mobile: Boolean)
operator fun HttpServletRequest.get(param: String) = getParameter(param)
| gpl-3.0 | d6e3be09b0aee816aff182ebff7b084e | 37.834532 | 121 | 0.666914 | 3.812147 | false | false | false | false |
Ekito/koin | koin-projects/examples/androidx-compose-jetnews/src/main/java/com/example/jetnews/ui/state/UiState.kt | 1 | 1731 | /*
* Copyright 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
*
* 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.example.jetnews.ui.state
import com.example.jetnews.data.Result
/**
* Immutable data class that allows for loading, data, and exception to be managed independently.
*
* This is useful for screens that want to show the last successful result while loading or a later
* refresh has caused an error.
*/
data class UiState<T>(
val loading: Boolean = false,
val exception: Exception? = null,
val data: T? = null
) {
/**
* True if this contains an error
*/
val hasError: Boolean
get() = exception != null
/**
* True if this represents a first load
*/
val initialLoad: Boolean
get() = data == null && loading && !hasError
}
/**
* Copy a UiState<T> based on a Result<T>.
*
* Result.Success will set all fields
* Result.Error will reset loading and exception only
*/
fun <T> UiState<T>.copyWithResult(value: Result<T>): UiState<T> {
return when (value) {
is Result.Success -> copy(loading = false, exception = null, data = value.data)
is Result.Error -> copy(loading = false, exception = value.exception)
}
}
| apache-2.0 | 71ba4454b19fad5d4d6bdee54d849815 | 29.910714 | 99 | 0.68342 | 4.034965 | false | false | false | false |
tinypass/piano-sdk-for-android | show-helper/src/main/java/io/piano/android/showhelper/BaseShowController.kt | 1 | 3440 | package io.piano.android.showhelper
import android.os.Build
import android.view.View
import android.webkit.WebView
import androidx.annotation.UiThread
import androidx.fragment.app.FragmentActivity
import io.piano.android.composer.model.DisplayMode
import io.piano.android.composer.model.events.BaseShowType
import timber.log.Timber
abstract class BaseShowController<T : BaseShowType, V : BaseJsInterface> constructor(
protected val eventData: T,
protected val jsInterface: V
) {
abstract val url: String
abstract val fragmentTag: String
abstract val fragmentProvider: () -> BaseShowDialogFragment
protected abstract fun WebView.configure()
protected open fun processDelay(activity: FragmentActivity, showFunction: () -> Unit) = showFunction()
protected open fun checkPrerequisites(callback: (Boolean) -> Unit) = callback(true)
@JvmOverloads
@Suppress("unused") // Public API.
@UiThread
fun show(
activity: FragmentActivity,
inlineWebViewProvider: (FragmentActivity, String) -> WebView? = defaultWebViewProvider
) {
checkPrerequisites { canShow ->
if (canShow) {
when (eventData.displayMode) {
DisplayMode.MODAL -> showModal(activity)
DisplayMode.INLINE -> showInline(activity, inlineWebViewProvider)
else -> Timber.w("Unknown display mode %s", eventData.displayMode)
}
} else {
Timber.w("Showing forbidden due to prerequisites ")
}
}
}
@Suppress("unused") // Public API.
@UiThread
abstract fun close(data: String? = null)
private fun showInline(
activity: FragmentActivity,
webViewProvider: (FragmentActivity, String) -> WebView?
) = eventData.containerSelector
.takeUnless { it.isNullOrEmpty() }
?.let { id ->
runCatching {
val webView = requireNotNull(webViewProvider(activity, id)) {
"Can't find WebView with id $id"
}
webView.configure()
processDelay(activity) {
webView.loadUrl(url)
webView.visibility = View.VISIBLE
}
}.onFailure {
Timber.e(it)
}.getOrNull()
}
private fun showModal(
activity: FragmentActivity
) = fragmentProvider().apply {
isCancelable = eventData.showCloseButton
javascriptInterface = jsInterface
processDelay(activity) {
show(activity.supportFragmentManager, fragmentTag)
}
}
companion object {
fun WebView.executeJavascriptCode(code: String) =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
evaluateJavascript(code, null)
else loadUrl("javascript:$code")
@JvmStatic
private val defaultWebViewProvider: (FragmentActivity, String) -> WebView? = { activity, webViewId ->
activity.resources
.getIdentifier(webViewId, "id", activity.packageName)
.takeUnless { it == 0 }
?.let { id ->
runCatching {
activity.findViewById<WebView>(id)
}.onFailure {
Timber.e(it)
}.getOrNull()
}
}
}
}
| apache-2.0 | a50b40eff3f650e0e564889d7bce3dd9 | 33.4 | 109 | 0.594477 | 5.227964 | false | false | false | false |
OurFriendIrony/MediaNotifier | app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/general/Helper.kt | 1 | 2186 | package uk.co.ourfriendirony.medianotifier.general
import android.database.Cursor
import java.io.UnsupportedEncodingException
import java.net.URLEncoder
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
object Helper {
private val PREFIXES = arrayOf("A ", "The ")
private val dateFormat: DateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.UK)
@JvmStatic
fun cleanUrl(url: String): String {
return try {
URLEncoder.encode(url, "UTF-8")
} catch (e: UnsupportedEncodingException) {
url
}
}
@JvmStatic
fun cleanTitle(string: String): String {
for (prefix in PREFIXES) {
if (string.startsWith(prefix)) {
return string.substring(prefix.length) + ", " + prefix.substring(
0,
prefix.length - 1
)
}
}
return string
}
@JvmStatic
fun dateToString(date: Date?): String? {
return if (date != null) dateFormat.format(date) else null
}
@JvmStatic
fun stringToDate(date: String?): Date? {
return if (date == null) {
null
} else try {
dateFormat.parse(date)
} catch (e: Exception) {
null
}
}
@JvmStatic
fun replaceTokens(original: String, token: String, value: String): String {
return replaceTokens(original, arrayOf(token), arrayOf(value))
}
@JvmStatic
fun replaceTokens(s: String, tokens: Array<String>, values: Array<String>): String {
var string = s
if (tokens.size == values.size) {
for (i in tokens.indices) {
string = string.replace(tokens[i], values[i])
}
}
return string
}
@JvmStatic
fun getNotificationNumber(num: Int): String {
return if (num <= 9) num.toString() else "9+"
}
@JvmStatic
fun getColumnValue(cursor: Cursor, field: String?): String {
// Log.d("[FIELD]", "$field")
val colIndex = cursor.getColumnIndex(field)
val value = cursor.getString(colIndex)
return value ?: ""
}
} | apache-2.0 | 07d15c5f47ef175b3c8452c7cc4cb7f8 | 26.3375 | 88 | 0.57548 | 4.39839 | false | false | false | false |
neva-dev/javarel | tooling/gradle-plugin/src/main/kotlin/com/neva/javarel/gradle/internal/Behaviors.kt | 1 | 1015 | package com.neva.javarel.gradle.internal
object Behaviors {
fun waitFor(duration: Int) {
waitFor(duration.toLong())
}
fun waitFor(duration: Long) {
Thread.sleep(duration)
}
fun waitUntil(interval: Int, condition: (Timer) -> Boolean) {
waitUntil(interval.toLong(), condition)
}
fun waitUntil(interval: Long, condition: (Timer) -> Boolean) {
val timer = Timer()
while (condition(timer)) {
waitFor(interval)
timer.tick()
}
}
class Timer {
private var _started = time()
private var _ticks = 0L
private fun time(): Long {
return System.currentTimeMillis()
}
fun reset() {
this._ticks = 0
}
fun tick() {
this._ticks++
}
val started: Long
get() = _started
val elapsed: Long
get() = time() - _started
val ticks: Long
get() = _ticks
}
} | apache-2.0 | c23a68ebbabb0cd75c0c729d3b212f65 | 17.814815 | 66 | 0.503448 | 4.49115 | false | false | false | false |
dataloom/conductor-client | src/main/kotlin/com/openlattice/authorization/aggregators/PrincipalAggregator.kt | 1 | 1703 | package com.openlattice.authorization.aggregators
import com.hazelcast.aggregation.Aggregator
import com.openlattice.authorization.*
import com.openlattice.organizations.PrincipalSet
import java.util.Map
class PrincipalAggregator(private val principalsMap: MutableMap<AclKey, PrincipalSet>
) : Aggregator<MutableMap.MutableEntry<AceKey, AceValue>, PrincipalAggregator> {
override fun accumulate(input: MutableMap.MutableEntry<AceKey, AceValue>) {
val key = input.key.aclKey
val principal = input.key.principal
if (principalsMap.containsKey(key)) {
principalsMap[key]!!.add(principal)
} else {
principalsMap[key] = PrincipalSet(mutableSetOf(principal))
}
}
override fun combine(aggregator: Aggregator<*, *>) {
if (aggregator is PrincipalAggregator) {
aggregator.principalsMap.forEach {
if (principalsMap.containsKey(it.key)) {
principalsMap[it.key]!!.addAll(it.value)
} else {
principalsMap[it.key] = it.value
}
}
}
}
override fun aggregate(): PrincipalAggregator {
return this
}
fun getResult(): MutableMap<AclKey, PrincipalSet> {
return principalsMap
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (other !is PrincipalAggregator) return false
return principalsMap == other.principalsMap
}
override fun hashCode(): Int {
return principalsMap.hashCode()
}
override fun toString(): String {
return "PrincipalAggregator{principalsMap=$principalsMap}"
}
} | gpl-3.0 | e1a1f8b1faffdc366bd2865176a50194 | 27.881356 | 85 | 0.642983 | 5.207951 | false | false | false | false |
weibaohui/korm | src/main/kotlin/com/sdibt/korm/core/callbacks/CallBackExecute.kt | 1 | 1825 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.sdibt.korm.core.callbacks
import com.sdibt.korm.core.db.DataSourceType
import com.sdibt.korm.core.db.KormSqlSession
class CallBackExecute(db: KormSqlSession) {
val defaultCallBack = DefaultCallBack.instance.getCallBack(db)
fun init() {
defaultCallBack.execute().reg("sqlProcess") { CallBackCommon().sqlProcess(it) }
defaultCallBack.execute().reg("setDataSource") { CallBackCommon().setDataSoure(it) }
defaultCallBack.execute().reg("exec") { execCallback(it) }
}
fun execCallback(scope: Scope): Scope {
if (scope.db.Error == null) {
val (rowsAffected, generatedKeys) = scope.db.executeUpdate(
scope.sqlString, scope.sqlParam,
dsName = scope.dsName,
dsType = DataSourceType.WRITE
)
scope.rowsAffected = rowsAffected
scope.generatedKeys = generatedKeys
scope.result = rowsAffected
}
return scope
}
}
| apache-2.0 | 5e0b3438676e37b59408a92e97a11ea4 | 34.096154 | 92 | 0.68 | 4.418886 | false | false | false | false |
jcgay/gradle-notifier | src/main/kotlin/fr/jcgay/gradle/notifier/extension/Pushbullet.kt | 1 | 444 | package fr.jcgay.gradle.notifier.extension
import java.util.Properties
class Pushbullet: NotifierConfiguration {
var apikey: String? = null
var device: String? = null
override fun asProperties(): Properties {
val prefix = "notifier.pushbullet"
val result = Properties()
apikey?.let { result["${prefix}.apikey"] = it }
device?.let { result["${prefix}.device"] = it }
return result
}
}
| mit | 794b8213badac5f99f36b55840b9dd56 | 25.117647 | 55 | 0.63964 | 4.188679 | false | true | false | false |
loloof64/BasicChessEndGamesTrainer | app/src/main/java/com/loloof64/android/basicchessendgamestrainer/ui/theme/Type.kt | 1 | 823 | package com.loloof64.android.basicchessendgamestrainer.ui.theme
import androidx.compose.material.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
body1 = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp
)
/* Other default text styles to override
button = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.W500,
fontSize = 14.sp
),
caption = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 12.sp
)
*/
) | gpl-3.0 | 9665415a6e1fb43ccd9608a22196bd4e | 28.428571 | 63 | 0.699878 | 4.331579 | false | false | false | false |
squark-io/yggdrasil | yggdrasil-maven-plugin/yggdrasil-maven-plugin-test/src/main/kotlin/test/TestDelegatedMainClass.kt | 2 | 1639 | package test
import org.apache.logging.log4j.Level
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.core.LoggerContext
import org.apache.logging.log4j.core.appender.FileAppender
import org.apache.logging.log4j.core.config.AppenderRef
import org.apache.logging.log4j.core.config.LoggerConfig
import org.apache.logging.log4j.core.layout.PatternLayout
/**
* yggdrasil
*
* Created by Erik Håkansson on 2017-03-26.
* Copyright 2017
*
*/
class TestDelegatedMainClass {
companion object {
class KBuilder : FileAppender.Builder<KBuilder>()
@JvmStatic
fun main(args: Array<String>) {
val ctx = LogManager.getContext(false) as LoggerContext
val config = ctx.configuration
val layout = PatternLayout.newBuilder().withConfiguration(config).withPattern(
PatternLayout.SIMPLE_CONVERSION_PATTERN)
val builder = KBuilder().withFileName(args[0]).withLayout(layout.build()).setConfiguration(config).withName(
"TEST")
val appender = builder.build()
appender.start()
config.addAppender(appender)
val ref = AppenderRef.createAppenderRef("File", null, null)
val refs = arrayOf(ref)
val loggerConfig = LoggerConfig.createLogger(false, Level.INFO, TestDelegatedMainClass::class.java.name,
"true", refs, null, config, null)
loggerConfig.addAppender(appender, null, null)
config.addLogger(TestDelegatedMainClass::class.java.name, loggerConfig)
ctx.updateLoggers()
LogManager.getLogger(TestDelegatedMainClass::class.java.name).info(
"${TestDelegatedMainClass::class.java.name} loaded")
}
}
}
| apache-2.0 | 99da6e57d912321cf7890336c2701049 | 34.608696 | 114 | 0.733822 | 3.966102 | false | true | false | false |
openhab/openhab.android | mobile/src/main/java/org/openhab/habdroid/ui/widget/AutoHeightPlayerView.kt | 1 | 1736 | /*
* Copyright (c) 2010-2022 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.habdroid.ui.widget
import android.content.Context
import android.util.AttributeSet
import android.view.View
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.ui.StyledPlayerView
import com.google.android.exoplayer2.video.VideoSize
class AutoHeightPlayerView constructor(context: Context, attrs: AttributeSet) :
StyledPlayerView(context, attrs),
Player.Listener {
private var currentPlayer: ExoPlayer? = null
override fun setPlayer(player: Player?) {
currentPlayer?.removeListener(this)
super.setPlayer(player)
currentPlayer = player as ExoPlayer?
currentPlayer?.addListener(this)
}
override fun onVideoSizeChanged(size: VideoSize) {
requestLayout()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val size = currentPlayer?.videoFormat ?: return super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val measuredWidth = View.resolveSize(0, widthMeasureSpec)
val measuredHeight = (measuredWidth.toDouble() * size.height / size.width).toInt()
val newHeightMeasureSpec = MeasureSpec.makeMeasureSpec(measuredHeight, MeasureSpec.getMode(widthMeasureSpec))
super.onMeasure(widthMeasureSpec, newHeightMeasureSpec)
}
}
| epl-1.0 | 3e7724e9d171f7ad3fee9a0511dcf6b3 | 35.166667 | 117 | 0.751152 | 4.55643 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/anki/dialogs/CreateDeckDialog.kt | 1 | 9253 | /****************************************************************************************
* Copyright (c) 2021 Akshay Jadhav <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki.dialogs
import android.annotation.SuppressLint
import android.content.Context
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.WhichButton
import com.afollestad.materialdialogs.actions.setActionButtonEnabled
import com.afollestad.materialdialogs.input.getInputField
import com.afollestad.materialdialogs.input.input
import com.ichi2.anki.CollectionHelper
import com.ichi2.anki.CollectionManager.withCol
import com.ichi2.anki.R
import com.ichi2.anki.UIUtils.showThemedToast
import com.ichi2.anki.servicelayer.DeckService.deckExists
import com.ichi2.annotations.NeedsTest
import com.ichi2.libanki.DeckId
import com.ichi2.libanki.Decks
import com.ichi2.libanki.backend.exception.DeckRenameException
import com.ichi2.libanki.getOrCreateFilteredDeck
import com.ichi2.utils.displayKeyboard
import net.ankiweb.rsdroid.BackendFactory
import timber.log.Timber
import java.util.function.Consumer
// TODO: Use snackbars instead of toasts: https://github.com/ankidroid/Anki-Android/pull/12139#issuecomment-1224963182
@NeedsTest("Ensure a toast is shown on a successful action")
class CreateDeckDialog(private val context: Context, private val title: Int, private val deckDialogType: DeckDialogType, private val parentId: Long?) {
private var mPreviousDeckName: String? = null
private var mOnNewDeckCreated: Consumer<Long>? = null
private var mInitialDeckName = ""
private var mShownDialog: MaterialDialog? = null
enum class DeckDialogType {
FILTERED_DECK, DECK, SUB_DECK, RENAME_DECK
}
private val col
get() = CollectionHelper.instance.getCol(context)!!
suspend fun showFilteredDeckDialog() {
Timber.i("CreateDeckDialog::showFilteredDeckDialog")
mInitialDeckName = withCol {
if (!BackendFactory.defaultLegacySchema) {
newBackend.getOrCreateFilteredDeck(did = 0).name
} else {
val names = decks.allNames()
var n = 1
val namePrefix = context.resources.getString(R.string.filtered_deck_name) + " "
while (names.contains(namePrefix + n)) {
n++
}
namePrefix + n
}
}
showDialog()
}
/** Used for rename */
var deckName: String
get() = mShownDialog!!.getInputField().text.toString()
set(deckName) {
mPreviousDeckName = deckName
mInitialDeckName = deckName
}
fun showDialog(): MaterialDialog {
@SuppressLint("CheckResult")
val dialog = MaterialDialog(context).show {
title(title)
positiveButton(R.string.dialog_ok) {
onPositiveButtonClicked()
}
negativeButton(R.string.dialog_cancel)
input(prefill = mInitialDeckName, waitForPositiveButton = false) { dialog, text ->
// we need the fully-qualified name for subdecks
val fullyQualifiedDeckName = fullyQualifyDeckName(dialogText = text)
// if the name is empty, it seems distracting to show an error
if (!Decks.isValidDeckName(fullyQualifiedDeckName)) {
dialog.setActionButtonEnabled(WhichButton.POSITIVE, false)
return@input
}
if (deckExists(col, fullyQualifiedDeckName!!)) {
dialog.setActionButtonEnabled(WhichButton.POSITIVE, false)
dialog.getInputField().error = context.getString(R.string.validation_deck_already_exists)
return@input
}
dialog.setActionButtonEnabled(WhichButton.POSITIVE, true)
}
displayKeyboard(getInputField())
}
mShownDialog = dialog
return dialog
}
/**
* Returns the fully qualified deck name for the provided input
* @param dialogText The user supplied text in the dialog
* @return [dialogText], or the deck name containing `::` in case of [DeckDialogType.SUB_DECK]
*/
private fun fullyQualifyDeckName(dialogText: CharSequence) =
when (deckDialogType) {
DeckDialogType.DECK, DeckDialogType.FILTERED_DECK, DeckDialogType.RENAME_DECK -> dialogText.toString()
DeckDialogType.SUB_DECK -> col.decks.getSubdeckName(parentId!!, dialogText.toString())
}
fun closeDialog() {
mShownDialog?.dismiss()
}
fun createSubDeck(did: DeckId, deckName: String?) {
val deckNameWithParentName = col.decks.getSubdeckName(did, deckName)
createDeck(deckNameWithParentName!!)
}
fun createDeck(deckName: String) {
if (Decks.isValidDeckName(deckName)) {
createNewDeck(deckName)
// 11668: Display feedback if a deck is created
showThemedToast(context, R.string.deck_created, true)
} else {
Timber.d("CreateDeckDialog::createDeck - Not creating invalid deck name '%s'", deckName)
showThemedToast(context, context.getString(R.string.invalid_deck_name), false)
}
closeDialog()
}
fun createFilteredDeck(deckName: String): Boolean {
try {
// create filtered deck
Timber.i("CreateDeckDialog::createFilteredDeck...")
val newDeckId = col.decks.newDyn(deckName)
mOnNewDeckCreated!!.accept(newDeckId)
} catch (ex: DeckRenameException) {
showThemedToast(context, ex.getLocalizedMessage(context.resources), false)
return false
}
return true
}
private fun createNewDeck(deckName: String): Boolean {
try {
// create normal deck or sub deck
Timber.i("CreateDeckDialog::createNewDeck")
val newDeckId = col.decks.id(deckName)
mOnNewDeckCreated!!.accept(newDeckId)
} catch (filteredAncestor: DeckRenameException) {
Timber.w(filteredAncestor)
return false
}
return true
}
private fun onPositiveButtonClicked() {
if (deckName.isNotEmpty()) {
when (deckDialogType) {
DeckDialogType.DECK -> {
// create deck
createDeck(deckName)
}
DeckDialogType.RENAME_DECK -> {
renameDeck(deckName)
}
DeckDialogType.SUB_DECK -> {
// create sub deck
createSubDeck(parentId!!, deckName)
}
DeckDialogType.FILTERED_DECK -> {
// create filtered deck
createFilteredDeck(deckName)
}
}
}
}
fun renameDeck(newDeckName: String) {
val newName = newDeckName.replace("\"".toRegex(), "")
if (!Decks.isValidDeckName(newName)) {
Timber.i("CreateDeckDialog::renameDeck not renaming deck to invalid name '%s'", newName)
showThemedToast(context, context.getString(R.string.invalid_deck_name), false)
} else if (newName != mPreviousDeckName) {
try {
val decks = col.decks
val deckId = decks.id(mPreviousDeckName!!)
decks.rename(decks.get(deckId), newName)
mOnNewDeckCreated!!.accept(deckId)
// 11668: Display feedback if a deck is renamed
showThemedToast(context, R.string.deck_renamed, true)
} catch (e: DeckRenameException) {
Timber.w(e)
// We get a localized string from libanki to explain the error
showThemedToast(context, e.getLocalizedMessage(context.resources), false)
}
}
}
fun setOnNewDeckCreated(c: Consumer<Long>?) {
mOnNewDeckCreated = c
}
}
| gpl-3.0 | 33bf37d4031c5a97251611ca5b6f1973 | 41.059091 | 151 | 0.588998 | 5.212958 | false | false | false | false |
raatiniemi/worker | app/src/main/java/me/raatiniemi/worker/data/projects/TimeIntervalDao.kt | 1 | 1558 | /*
* Copyright (C) 2018 Tobias Raatiniemi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package me.raatiniemi.worker.data.projects
import androidx.room.*
@Dao
interface TimeIntervalDao {
@Query("""SELECT * FROM time_intervals
WHERE project_id = :projectId AND
(start_in_milliseconds >= :startInMilliseconds OR stop_in_milliseconds = 0)
ORDER BY stop_in_milliseconds ASC, start_in_milliseconds ASC""")
fun findAll(projectId: Long, startInMilliseconds: Long): List<TimeIntervalEntity>
@Query("SELECT * FROM time_intervals WHERE _id = :id LIMIT 1")
fun find(id: Long): TimeIntervalEntity?
@Query("""SELECT * FROM time_intervals
WHERE project_id = :projectId AND stop_in_milliseconds = 0""")
fun findActiveTime(projectId: Long): TimeIntervalEntity?
@Insert
fun add(entity: TimeIntervalEntity): Long
@Update
fun update(entities: List<TimeIntervalEntity>)
@Delete
fun remove(entities: List<TimeIntervalEntity>)
}
| gpl-2.0 | 77d60c0334e5b0ba66bd0fc79019523f | 34.409091 | 87 | 0.718228 | 4.315789 | false | false | false | false |
WindSekirun/RichUtilsKt | RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/module/reference/ActivityReference.kt | 1 | 2398 | package pyxis.uzuki.live.richutilskt.module.reference
import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import java.lang.ref.WeakReference
import java.util.*
/**
* RichUtilsKt
* Class: ActivityReference
* Created by Pyxis on 2/4/18.
*
* Description:
*/
object ActivityReference {
private var mTopActivityWeakRef: WeakReference<Activity>? = null
private val mActivityList: LinkedList<Activity> = LinkedList()
private var mApplicationWeakRef: WeakReference<Application>? = null
private val mCallbacks = object : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, bundle: Bundle?) {
mActivityList.add(activity)
setTopActivityWeakRef(activity)
}
override fun onActivityStarted(activity: Activity) {
setTopActivityWeakRef(activity)
}
override fun onActivityResumed(activity: Activity) {
setTopActivityWeakRef(activity)
}
override fun onActivityDestroyed(activity: Activity) {
mActivityList.remove(activity)
}
override fun onActivityPaused(activity: Activity) {}
override fun onActivityStopped(activity: Activity) {}
override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle?) {}
}
@JvmStatic
fun initialize(application: Application) {
mApplicationWeakRef = WeakReference(application)
application.registerActivityLifecycleCallbacks(mCallbacks)
}
@JvmStatic
fun getActivtyReference(): Activity? {
if (mTopActivityWeakRef != null) {
val activity = (mTopActivityWeakRef as WeakReference<Activity>).get()
if (activity != null) {
return activity
}
}
val size = mActivityList.size
return if (size > 0) mActivityList[size - 1] else null
}
@JvmStatic
fun getContext(): Context {
return getActivtyReference() ?: mApplicationWeakRef?.get() as Context
}
@JvmStatic
fun getActivityList() = mActivityList
private fun setTopActivityWeakRef(activity: Activity) {
if (mTopActivityWeakRef == null || activity != (mTopActivityWeakRef as WeakReference<Activity>).get()) {
mTopActivityWeakRef = WeakReference(activity)
}
}
} | apache-2.0 | 8d5604e81972f23b2df699dccabb2e60 | 29.75641 | 112 | 0.678065 | 5.317073 | false | false | false | false |
debop/debop4k | debop4k-core/src/main/kotlin/debop4k/core/kodatimes/TimestampZoneText.kt | 1 | 1350 | /*
* Copyright (c) 2016. KESTI co, 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 debop4k.core.kodatimes
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
/**
* [DateTime] 의 TimeZone 정보를 제공합니다
*
* @author [email protected]
*/
open class TimestampZoneText(val datetime: DateTime?) {
constructor(timestamp: Long, zone: DateTimeZone) : this(DateTime(timestamp, zone))
constructor(timestamp: Long, zoneId: String) : this(DateTime(timestamp, DateTimeZone.forID(zoneId)))
val timestamp: Long?
get() = datetime?.millis
val zoneId: String?
get() = datetime?.zone?.id
val timetext: String?
get() = datetime?.toIsoFormatHMSString()
override fun toString(): String {
return "TimestampZoneText(timestamp=$timestamp, zoneId=$zoneId, timetext=$timetext)"
}
} | apache-2.0 | 6c16d0ffd0b06db92f8fa319849be6e5 | 29.295455 | 102 | 0.727477 | 3.906158 | false | false | false | false |
Dimigo-AppClass-Mission/SaveTheEarth | app/src/main/kotlin/me/hyemdooly/sangs/dimigo/app/project/service/STERealtimeService.kt | 1 | 1926 | package me.hyemdooly.sangs.dimigo.app.project.service
import android.app.Notification
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.IBinder
import android.support.v4.app.NotificationCompat
import io.realm.Realm
import me.hyemdooly.sangs.dimigo.app.project.receiver.ScreenOnOffReceiver
import me.hyemdooly.sangs.dimigo.app.project.R
class STERealtimeService : Service() {
lateinit var screenReceiver: ScreenOnOffReceiver
override fun onCreate() {
Realm.init(applicationContext)
registerStatusReceiver()
startForeground(33233317, getNotification(this))
}
override fun onDestroy() {
unregisterStatusReceiver()
stopForeground(true)
}
override fun onBind(p0: Intent?): IBinder? {
return null
}
private fun registerStatusReceiver() {
screenReceiver = ScreenOnOffReceiver()
val filter = IntentFilter()
filter.addAction(Intent.ACTION_SCREEN_ON)
filter.addAction(Intent.ACTION_SCREEN_OFF)
registerReceiver(screenReceiver, filter)
}
private fun unregisterStatusReceiver() {
if(screenReceiver != null){
unregisterReceiver(screenReceiver)
}
}
private fun getNotification(paramContext: Context): Notification {
val smallIcon = R.drawable.ic_eco_energy
val notification = NotificationCompat.Builder(paramContext, "SaveEnergy")
.setSmallIcon(smallIcon)
.setPriority(NotificationCompat.PRIORITY_MIN)
.setAutoCancel(true)
.setWhen(0)
.setContentTitle("휴대폰 사용절약 프로젝트 진행!")
.setContentText("휴대폰을 사용하지 않으면 지구가 치유됩니다 :)").build()
notification.flags = 16
return notification
}
} | gpl-3.0 | 29a3c969671c0bc6feae6d7490ba2f20 | 28.109375 | 81 | 0.684748 | 4.475962 | false | false | false | false |
EMResearch/EMB | jdk_8_maven/cs/graphql/graphql-scs/src/main/kotlin/org/graphqlscs/type/Text2Txt.kt | 1 | 1128 | package org.graphqlscs.type
import org.springframework.stereotype.Component
import java.util.*
@Component
class Text2Txt {
fun subject(word1: String, word2: String, word3: String): String {
//CONVERT ENGLISH TEXT txt INTO MOBILE TELEPHONE TXT
//BY SUBSTITUTING ABBREVIATIONS FOR COMMON WORDS
var word1 = word1
var word2 = word2
var word3 = word3
word1 = word1.lowercase(Locale.getDefault())
word2 = word2.lowercase(Locale.getDefault())
word3 = word3.lowercase(Locale.getDefault())
var result = ""
if (word1 == "two") {
result = "2"
}
if (word1 == "for" || word1 == "four") {
result = "4"
}
if (word1 == "you") {
result = "u"
}
if (word1 == "and") {
result = "n"
}
if (word1 == "are") {
result = "r"
} else if (word1 == "see" && word2 == "you") {
result = "cu"
} else if (word1 == "by" && word2 == "the" && word3 == "way") {
result = "btw"
}
return result
}
} | apache-2.0 | 1a32b31c3f62d0a68b26ccc22f49710d | 27.948718 | 71 | 0.499113 | 3.615385 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/tags/TagPickerActivity.kt | 1 | 3902 | package org.tasks.tags
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.EditText
import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import org.tasks.R
import org.tasks.Strings.isNullOrEmpty
import org.tasks.billing.Inventory
import org.tasks.data.TagData
import org.tasks.databinding.ActivityTagPickerBinding
import org.tasks.injection.ThemedInjectingAppCompatActivity
import org.tasks.themes.ColorProvider
import org.tasks.themes.Theme
import java.util.*
import javax.inject.Inject
@AndroidEntryPoint
class TagPickerActivity : ThemedInjectingAppCompatActivity() {
@Inject lateinit var theme: Theme
@Inject lateinit var inventory: Inventory
@Inject lateinit var colorProvider: ColorProvider
private val viewModel: TagPickerViewModel by viewModels()
private var taskIds: ArrayList<Long>? = null
private lateinit var editText: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val intent = intent
taskIds = intent.getSerializableExtra(EXTRA_TASKS) as ArrayList<Long>?
if (savedInstanceState == null) {
intent.getParcelableArrayListExtra<TagData>(EXTRA_SELECTED)?.let {
viewModel.setSelected(
it,
intent.getParcelableArrayListExtra(EXTRA_PARTIALLY_SELECTED)
)
}
}
val binding = ActivityTagPickerBinding.inflate(layoutInflater)
editText = binding.searchInput.apply {
addTextChangedListener(
onTextChanged = { text, _, _, _ -> onSearch(text) }
)
}
setContentView(binding.root)
val toolbar = binding.toolbar
toolbar.setNavigationIcon(R.drawable.ic_outline_arrow_back_24px)
toolbar.setNavigationOnClickListener { onBackPressed() }
val themeColor = theme.themeColor
themeColor.applyToNavigationBar(this)
val recyclerAdapter = TagRecyclerAdapter(this, viewModel, inventory, colorProvider) { tagData, vh ->
onToggle(tagData, vh)
}
val recyclerView = binding.recyclerView
recyclerView.adapter = recyclerAdapter
(recyclerView.itemAnimator as DefaultItemAnimator?)!!.supportsChangeAnimations = false
recyclerView.layoutManager = LinearLayoutManager(this)
viewModel.observe(this) { recyclerAdapter.submitList(it) }
editText.setText(viewModel.text)
}
private fun onToggle(tagData: TagData, vh: TagPickerViewHolder) = lifecycleScope.launch {
val newTag = tagData.id == null
val newState = viewModel.toggle(tagData, vh.isChecked || newTag)
vh.updateCheckbox(newState)
if (newTag) {
clear()
}
}
private fun onSearch(text: CharSequence?) {
viewModel.search(text?.toString() ?: "")
}
override fun onBackPressed() {
if (isNullOrEmpty(viewModel.text)) {
val data = Intent()
data.putExtra(EXTRA_TASKS, taskIds)
data.putParcelableArrayListExtra(EXTRA_PARTIALLY_SELECTED, viewModel.getPartiallySelected())
data.putParcelableArrayListExtra(EXTRA_SELECTED, viewModel.getSelected())
setResult(Activity.RESULT_OK, data)
finish()
} else {
clear()
}
}
private fun clear() {
editText.setText("")
}
companion object {
const val EXTRA_SELECTED = "extra_tags"
const val EXTRA_PARTIALLY_SELECTED = "extra_partial"
const val EXTRA_TASKS = "extra_tasks"
}
} | gpl-3.0 | b78cc161ed6aa238d9eee8fde7bef6fa | 36.171429 | 108 | 0.688877 | 5.120735 | false | false | false | false |
meteochu/DecisionKitchen | Android/app/src/main/java/com/decisionkitchen/decisionkitchen/GameActivity.kt | 1 | 6252 | package com.decisionkitchen.decisionkitchen
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.drawable.GradientDrawable
import android.location.Location
import android.os.Bundle
import android.support.design.widget.CoordinatorLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.LinearLayout
import android.widget.TextView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.*
import java.util.*
data class Question (val title: String, val options: Array<String>);
class GameActivity : Activity() {
private var mRecyclerView: RecyclerView? = null
private var mAdapter: RecyclerView.Adapter<GameAdapter.ViewHolder>? = null
private var mLayoutManager: RecyclerView.LayoutManager? = null
private var group : Group? = null
private var groupRef: DatabaseReference? = null
private var question: Int = -1
private var gameId: Int? = null
private var user: FirebaseUser? = null
private var qOrder: ArrayList<Int> = ArrayList<Int>()
private var questions: ArrayList<Question> = arrayListOf(
Question("How much do you want to spend?", arrayOf("$", "$$", "$$$", "$$$$")),
Question("What kind of food do you want?", arrayOf("Breakfast & Brunch", "Chinese", "Diners", "Fast Food", "Hot Pot", "Italian", "Japanese", "Korean", "Mongolian", "Pizza", "Steakhouses", "Sushi Bars", "American (Traditional)", "Vegetarian")),
Question("Delivery of dine-in?", arrayOf("Delivery", "Dine-in"))
)
private var location: Location? = null
private var responses: ArrayList<ArrayList<Int>> = ArrayList<ArrayList<Int>>();
public fun getContext(): Context {
return this
}
public fun getGameActivity(): GameActivity {
return this
}
fun render() {
if (question == questions.size) {
val intent: Intent = Intent(applicationContext, FinishedActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
applicationContext.startActivity(intent)
} else if (group != null && groupRef != null && qOrder != null && question != -1 && user != null && gameId != null) {
val q = questions[question]
(findViewById(R.id.question) as TextView).text = q.title
var options:List<String> = ArrayList<String>()
for (question in q.options) {
options += question
}
mAdapter = GameAdapter(options, responses[question], mRecyclerView, getGameActivity(), q.title)
mRecyclerView!!.adapter = mAdapter
}
}
fun nextQuestion() {
val game = group!!.games!![gameId!!]
question++
if (question < questions.size) render()
else {
groupRef!!.child("games").child(gameId.toString()).child("responses").child(user!!.uid)
.setValue(Response(responses, hashMapOf("latitude" to location!!.latitude, "longitude" to location!!.longitude)))
}
}
public fun nextQuestion(view: View) {
nextQuestion()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_game)
responses = ArrayList<ArrayList<Int>>(questions.size);
val database = FirebaseDatabase.getInstance()
user = FirebaseAuth.getInstance().currentUser;
location = getIntent().extras["LOCATION"] as Location
groupRef = database.getReference("groups/" + getIntent().getStringExtra("GROUP_ID"))
val groupListener = object : ValueEventListener {
override fun onCancelled(p0: DatabaseError?) {
}
override fun onDataChange(dataSnapshot: DataSnapshot) {
group = dataSnapshot.getValue<Group>(Group::class.java)!!
if (gameId == null) {
for (index in 0 .. (group!!.games!!.size - 1)) {
val game = group!!.games!![index]
if (game.meta!!.end == null && (game.responses == null || !game.responses.containsKey(user!!.uid))) {
gameId = index
for (i in 0 .. (questions.size - 1)) {
qOrder.add(i)
val tmp = ArrayList<Int>(questions[i].options.size)
for (j in 0 .. questions[i].options.size - 1) {
tmp.add(0)
}
responses.add(tmp);
}
Collections.shuffle(qOrder);
nextQuestion()
return
}
}
val intent: Intent = Intent(applicationContext, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
applicationContext.startActivity(intent)
} else {
render()
}
}
}
groupRef!!.addValueEventListener(groupListener)
mRecyclerView = findViewById(R.id.checkbox_recycler) as RecyclerView
mRecyclerView!!.setHasFixedSize(true)
val rParams: LinearLayout.LayoutParams = LinearLayout.LayoutParams(CoordinatorLayout.LayoutParams.MATCH_PARENT, CoordinatorLayout.LayoutParams.MATCH_PARENT)
mRecyclerView!!.layoutParams = rParams
mLayoutManager = LinearLayoutManager(getContext())
mRecyclerView!!.layoutManager = mLayoutManager
mLayoutManager!!.setMeasuredDimension(CoordinatorLayout.LayoutParams.MATCH_PARENT, CoordinatorLayout.LayoutParams.MATCH_PARENT)
mAdapter = GameAdapter(ArrayList<String>(), ArrayList<Int>(), mRecyclerView, getGameActivity(), "" )
mRecyclerView!!.adapter = mAdapter
}
}
| apache-2.0 | adaa0724e479f29a9dd0c4caf532af19 | 40.959732 | 251 | 0.615483 | 4.997602 | false | false | false | false |
michaelgallacher/intellij-community | platform/configuration-store-impl/src/schemeLoader.kt | 1 | 1618 | package com.intellij.configurationStore
import org.xmlpull.mxp1.MXParser
import org.xmlpull.v1.XmlPullParser
internal inline fun lazyPreloadScheme(bytes: ByteArray, isUseOldFileNameSanitize: Boolean, consumer: (name: String?, parser: XmlPullParser) -> Unit) {
val parser = MXParser()
parser.setInput(bytes.inputStream().reader())
consumer(preload(isUseOldFileNameSanitize, parser), parser)
}
private fun preload(isUseOldFileNameSanitize: Boolean, parser: MXParser): String? {
var eventType = parser.eventType
fun findName(): String? {
eventType = parser.next()
while (eventType != XmlPullParser.END_DOCUMENT) {
when (eventType) {
XmlPullParser.START_TAG -> {
if (parser.name == "option" && parser.getAttributeValue(null, "name") == "myName") {
return parser.getAttributeValue(null, "value")
}
}
}
eventType = parser.next()
}
return null
}
do {
when (eventType) {
XmlPullParser.START_TAG -> {
if (!isUseOldFileNameSanitize || parser.name != "component") {
if (parser.name == "profile" || (isUseOldFileNameSanitize && parser.name == "copyright")) {
return findName()
}
else if (parser.name == "inspections") {
// backward compatibility - we don't write PROFILE_NAME_TAG anymore
return parser.getAttributeValue(null, "profile_name") ?: findName()
}
else {
return null
}
}
}
}
eventType = parser.next()
}
while (eventType != XmlPullParser.END_DOCUMENT)
return null
} | apache-2.0 | 88b8b0b3e57cb526984c92538bd07728 | 30.134615 | 150 | 0.6267 | 4.506964 | false | false | false | false |
bailuk/AAT | aat-lib/src/main/java/ch/bailu/aat_lib/map/layer/selector/AbsNodeSelectorLayer.kt | 1 | 5046 | package ch.bailu.aat_lib.map.layer.selector
import ch.bailu.aat_lib.coordinates.BoundingBoxE6
import ch.bailu.aat_lib.dispatcher.OnContentUpdatedInterface
import ch.bailu.aat_lib.gpx.GpxInformation
import ch.bailu.aat_lib.gpx.GpxNodeFinder
import ch.bailu.aat_lib.gpx.GpxPointNode
import ch.bailu.aat_lib.map.MapColor
import ch.bailu.aat_lib.map.MapContext
import ch.bailu.aat_lib.map.edge.EdgeViewInterface
import ch.bailu.aat_lib.map.edge.Position
import ch.bailu.aat_lib.map.layer.MapLayerInterface
import ch.bailu.aat_lib.preferences.StorageInterface
import ch.bailu.aat_lib.preferences.map.SolidMapGrid
import ch.bailu.aat_lib.service.ServicesInterface
import ch.bailu.aat_lib.util.IndexedMap
import ch.bailu.aat_lib.util.Rect
abstract class AbsNodeSelectorLayer(
private val services: ServicesInterface,
s: StorageInterface,
mc: MapContext,
private val pos: Position
) : MapLayerInterface, OnContentUpdatedInterface, EdgeViewInterface {
private val square_size = mc.metrics.density.toPixel_i(SQUARE_SIZE.toFloat())
private val square_hsize = mc.metrics.density.toPixel_i(SQUARE_HSIZE.toFloat())
private var visible = true
private val infoCache = IndexedMap<Int, GpxInformation>()
private val centerRect = Rect()
private var foundID = 0
private var foundIndex = 0
private var selectedNode: GpxPointNode? = null
private val sgrid = SolidMapGrid(s, mc.solidKey)
private var coordinates = sgrid.createCenterCoordinatesLayer(services)
companion object {
const val SQUARE_SIZE = 30
const val SQUARE_HSIZE = SQUARE_SIZE / 2
}
init {
centerRect.left = 0
centerRect.right = square_size
centerRect.top = 0
centerRect.bottom = square_size
}
open fun getSelectedNode(): GpxPointNode? {
return selectedNode
}
override fun drawForeground(mcontext: MapContext) {
if (visible) {
centerRect.offsetTo(
mcontext.metrics.width / 2 - square_hsize,
mcontext.metrics.height / 2 - square_hsize
)
val centerBounding = BoundingBoxE6()
val lt = mcontext.metrics.fromPixel(centerRect.left, centerRect.top)
val rb = mcontext.metrics.fromPixel(centerRect.right, centerRect.bottom)
if (lt != null && rb != null) {
centerBounding.add(lt)
centerBounding.add(rb)
findNodeAndNotify(centerBounding)
}
centerRect.offset(mcontext.metrics.left, mcontext.metrics.top)
drawSelectedNode(mcontext)
drawCenterSquare(mcontext)
coordinates.drawForeground(mcontext)
}
}
override fun drawInside(mcontext: MapContext) {
if (visible) {
coordinates.drawInside(mcontext)
}
}
private fun findNodeAndNotify(centerBounding: BoundingBoxE6) {
if (selectedNode == null || !centerBounding.contains(selectedNode)) {
if (findNode(centerBounding)) {
val info = infoCache.getValue(foundID)
val node = selectedNode
if (info is GpxInformation && node is GpxPointNode) {
setSelectedNode(foundID, info, node, foundIndex)
}
}
}
}
private fun findNode(centerBounding: BoundingBoxE6): Boolean {
var found = false
var i = 0
while (i < infoCache.size() && !found) {
val list = infoCache.getValueAt(i)!!.gpxList
val finder = GpxNodeFinder(centerBounding)
finder.walkTrack(list)
if (finder.haveNode()) {
found = true
foundID = infoCache.getKeyAt(i)!!
foundIndex = finder.nodeIndex
selectedNode = finder.node
}
i++
}
return found
}
abstract fun setSelectedNode(IID: Int, info: GpxInformation, node: GpxPointNode, index: Int)
private fun drawSelectedNode(mcontext: MapContext) {
val node = selectedNode
if (node != null) {
val selectedPixel = mcontext.metrics.toPixel(node)
mcontext.draw()
.bitmap(mcontext.draw().nodeBitmap, selectedPixel, MapColor.NODE_SELECTED)
}
}
private fun drawCenterSquare(mcontext: MapContext) {
mcontext.draw().rect(centerRect, mcontext.draw().gridPaint)
mcontext.draw().point(mcontext.metrics.centerPixel)
}
override fun onContentUpdated(iid: Int, info: GpxInformation) {
if (info.isLoaded) {
infoCache.put(iid, info)
} else {
infoCache.remove(iid)
}
}
override fun onPreferencesChanged(s: StorageInterface, key: String) {
if (sgrid.hasKey(key)) {
coordinates = sgrid.createCenterCoordinatesLayer(services)
}
}
override fun show() { visible = true }
override fun hide() { visible = false }
override fun pos() : Position { return pos }
} | gpl-3.0 | 0a180f4564b1bd0b5223b14f4f7ccb0a | 32.423841 | 96 | 0.638724 | 4.357513 | false | false | false | false |
aglne/mycollab | mycollab-services/src/main/java/com/mycollab/module/project/ProjectResources.kt | 3 | 1568 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.module.project
import com.mycollab.core.MyCollabException
import org.slf4j.LoggerFactory
import java.lang.reflect.Method
/**
* @author MyCollab Ltd.
* @since 1.0
*/
object ProjectResources {
private val LOG = LoggerFactory.getLogger(ProjectResources::class.java)
private var toHtmlMethod: Method? = null
init {
try {
val resourceCls = Class.forName("com.mycollab.module.project.ui.ProjectAssetsManager")
toHtmlMethod = resourceCls.getMethod("toHtml", String::class.java)
} catch (e: Exception) {
throw MyCollabException("Can not reload resource", e)
}
}
fun getFontIconHtml(type: String): String = try {
toHtmlMethod!!.invoke(null, type) as String
} catch (e: Exception) {
LOG.error("Can not get resource type $type")
""
}
}
| agpl-3.0 | 2a644a9e9f491f34fe9a905cd207cd42 | 33.065217 | 98 | 0.696235 | 4.201072 | false | false | false | false |
mobilejazz/Colloc | server/src/test/kotlin/com/mobilejazz/colloc/feature/encoder/domain/interactor/AngularEncodeInteractorTest.kt | 1 | 1642 | package com.mobilejazz.colloc.feature.encoder.domain.interactor
import com.mobilejazz.colloc.domain.model.Language
import com.mobilejazz.colloc.ext.toJsonElement
import com.mobilejazz.colloc.randomString
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.verify
import kotlinx.serialization.json.Json
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.io.File
internal class AngularEncodeInteractorTest {
@TempDir
private val localizationDirectory: File = File("{src/test/resources}/encode_localization/")
@MockK
private lateinit var json: Json
@BeforeEach
fun setUp() {
MockKAnnotations.init(this)
}
@Test
fun `assert content encoded properly`() {
val language = Language(code = randomString(), name = randomString())
val expectedTranslation = randomString()
val rawTranslation = anyTranslation()
val dictionary = mapOf(language to rawTranslation)
val translationHierarchy = rawTranslation.mapValues {
it.value.toJsonElement()
}
every { json.encodeToString(any(), translationHierarchy) } returns expectedTranslation
givenEncodeInteractor()(localizationDirectory, dictionary)
verify(exactly = 1) { json.encodeToString(any(), translationHierarchy) }
val actualTranslation = File(localizationDirectory, "angular/${language.code}.json").readText()
assertEquals(expectedTranslation, actualTranslation)
}
private fun givenEncodeInteractor() = AngularEncodeInteractor(json)
}
| apache-2.0 | d72890a3e2e2c1931f6bdba7595c0aa3 | 32.510204 | 99 | 0.780146 | 4.461957 | false | true | false | false |
StephaneBg/ScoreItProject | ui/src/main/java/com/sbgapps/scoreit/ui/view/UniversalEditionFragment.kt | 1 | 3566 | /*
* Copyright 2018 Stéphane Baiget
*
* 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.sbgapps.scoreit.ui.view
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.sbgapps.scoreit.ui.R
import com.sbgapps.scoreit.ui.base.BaseFragment
import com.sbgapps.scoreit.ui.ext.observe
import com.sbgapps.scoreit.ui.model.UniversalLap
import com.sbgapps.scoreit.ui.viewmodel.UniversalViewModel
import com.sbgapps.scoreit.ui.widget.LinearListView
import kotlinx.android.synthetic.main.fragment_universal_edition.*
import kotlinx.android.synthetic.main.item_universal_edition.view.*
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
class UniversalEditionFragment : BaseFragment() {
private val model by sharedViewModel<UniversalViewModel>()
private val adapter: PlayerAdapter = PlayerAdapter()
private var points = mutableListOf<Int>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? = inflater.inflate(R.layout.fragment_universal_edition, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
players.setAdapter(adapter)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
observe(model.getEditedLap(), ::setGame)
}
private fun setGame(laps: Pair<UniversalLap, List<String>>?) {
laps?.let {
points = it.first.points
adapter.items = it.second.zip(it.first.points)
}
}
inner class PlayerAdapter : LinearListView.Adapter<Pair<String, Int>>() {
override val layoutId = R.layout.item_universal_edition
override fun bind(position: Int, view: View) {
val (player, _points) = getItem(position)
with(view) {
playerName.text = player
playerPoints.text = _points.toString()
plusOne.setOnClickListener { addPoints(1, position, playerPoints) }
plusFive.setOnClickListener { addPoints(5, position, playerPoints) }
plusTen.setOnClickListener { addPoints(10, position, playerPoints) }
plusHundred.setOnClickListener { addPoints(100, position, playerPoints) }
minusOne.setOnClickListener { addPoints(-1, position, playerPoints) }
minusFive.setOnClickListener { addPoints(-5, position, playerPoints) }
minusTen.setOnClickListener { addPoints(-10, position, playerPoints) }
minusHundred.setOnClickListener { addPoints(-100, position, playerPoints) }
}
}
private fun addPoints(_points: Int, position: Int, textView: TextView) {
points[position] += _points
textView.text = points[position].toString()
}
}
companion object {
fun newInstance() = UniversalEditionFragment()
}
} | apache-2.0 | 595ceed78a71357f96877b7ff228ac04 | 37.76087 | 91 | 0.697055 | 4.647979 | false | false | false | false |
Nilhcem/xebia-android-hp-kotlin | app/src/main/kotlin/com/nilhcem/henripotier/ui/cart/CartAdapter.kt | 1 | 1022 | package com.nilhcem.henripotier.ui.cart
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import com.nilhcem.henripotier.core.cart.ShoppingCart
import com.nilhcem.henripotier.core.extensions.createHolder
import com.nilhcem.henripotier.core.extensions.getView
import com.nilhcem.henripotier.core.extensions.replaceAll
import java.util.ArrayList
class CartAdapter(val cart: ShoppingCart) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
var items: ArrayList<CartItemData> = ArrayList()
set(value) {
$items.replaceAll(value)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder =
createHolder(CartItem(parent.getContext()))
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) =
getView<CartItem>(holder).bindData(items.get(position), position >= cart.getNbItemsInCart())
override fun getItemCount(): Int = items.size()
}
| apache-2.0 | 86280bb9ea8e0ebbc3e7797936fa17d1 | 38.307692 | 104 | 0.754403 | 4.58296 | false | false | false | false |
ol-loginov/intellij-community | platform/script-debugger/protocol/protocol-reader/src/ReaderRoot.kt | 2 | 3115 | package org.jetbrains.protocolReader
import gnu.trove.THashSet
import org.jetbrains.io.JsonReaderEx
import org.jetbrains.jsonProtocol.JsonParseMethod
import java.lang.reflect.Method
import java.lang.reflect.ParameterizedType
import java.util.Arrays
import java.util.Comparator
import java.util.LinkedHashMap
class ReaderRoot<R>(public val type: Class<R>, private val typeToTypeHandler: LinkedHashMap<Class<*>, TypeWriter<*>>) {
private val visitedInterfaces = THashSet<Class<*>>(1)
val methodMap = LinkedHashMap<Method, ReadDelegate>();
init {
readInterfaceRecursive(type)
}
throws(javaClass<JsonProtocolModelParseException>())
private fun readInterfaceRecursive(clazz: Class<*>) {
if (visitedInterfaces.contains(clazz)) {
return
}
visitedInterfaces.add(clazz)
// todo sort by source location
val methods = clazz.getMethods()
Arrays.sort<Method>(methods, object : Comparator<Method> {
override fun compare(o1: Method, o2: Method): Int {
return o1.getName().compareTo(o2.getName())
}
})
for (m in methods) {
val jsonParseMethod = m.getAnnotation<JsonParseMethod>(javaClass<JsonParseMethod>())
if (jsonParseMethod == null) {
continue
}
val exceptionTypes = m.getExceptionTypes()
if (exceptionTypes.size() > 1) {
throw JsonProtocolModelParseException("Too many exception declared in " + m)
}
var returnType = m.getGenericReturnType()
var isList = false
if (returnType is ParameterizedType) {
val parameterizedType = returnType as ParameterizedType
if (parameterizedType.getRawType() == javaClass<List<Any>>()) {
isList = true
returnType = parameterizedType.getActualTypeArguments()[0]
}
}
//noinspection SuspiciousMethodCalls
var typeWriter: TypeWriter<*>? = typeToTypeHandler.get(returnType)
if (typeWriter == null) {
typeWriter = createHandler(typeToTypeHandler, m.getReturnType())
if (typeWriter == null) {
throw JsonProtocolModelParseException("Unknown return type in " + m)
}
}
val arguments = m.getGenericParameterTypes()
if (arguments.size() > 2) {
throw JsonProtocolModelParseException("Exactly one argument is expected in " + m)
}
val argument = arguments[0]
if (argument == javaClass<JsonReaderEx>() || argument == javaClass<Any>()) {
methodMap.put(m, ReadDelegate(typeWriter!!, isList, arguments.size() != 1))
}
else {
throw JsonProtocolModelParseException("Unrecognized argument type in " + m)
}
}
for (baseType in clazz.getGenericInterfaces()) {
if (baseType !is Class<*>) {
throw JsonProtocolModelParseException("Base interface must be class in " + clazz)
}
readInterfaceRecursive(baseType)
}
}
public fun writeStaticMethodJava(scope: ClassScope) {
val out = scope.output
for (entry in methodMap.entrySet()) {
out.newLine()
entry.getValue().write(scope, entry.getKey(), out)
out.newLine()
}
}
} | apache-2.0 | e1ff03d1f738c26e165dbc4bd660c9c4 | 32.148936 | 119 | 0.671589 | 4.852025 | false | false | false | false |
FFlorien/AmpachePlayer | app/src/main/java/be/florien/anyflow/data/TimeOperations.kt | 1 | 1598 | package be.florien.anyflow.data
import java.text.SimpleDateFormat
import java.util.*
object TimeOperations {
private const val AMPACHE_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ssXXX"
private val ampacheCompleteFormatter = SimpleDateFormat(AMPACHE_DATE_FORMAT, Locale.getDefault())
private val ampacheGetFormatter = SimpleDateFormat("yyyy-MM-dd", Locale.US)
var currentTimeUpdater: CurrentTimeUpdater? = null
fun getCurrentDate(): Calendar {
var calendar = Calendar.getInstance()
calendar = currentTimeUpdater?.getCurrentTimeUpdated(calendar) ?: calendar
return calendar
}
fun getCurrentDatePlus(field: Int, increment: Int): Calendar {
var calendar = Calendar.getInstance().apply {
add(field, increment)
}
calendar = currentTimeUpdater?.getCurrentTimeUpdated(calendar) ?: calendar
return calendar
}
fun getDateFromMillis(millis: Long): Calendar = Calendar.getInstance().apply {
timeInMillis = millis
}
fun getDateFromAmpacheComplete(formatted: String): Calendar = Calendar.getInstance().apply {
time = ampacheCompleteFormatter.parse(formatted)
?: throw IllegalArgumentException("The provided string could not be parsed to an ampache date")
}
fun getAmpacheCompleteFormatted(time: Calendar): String = ampacheCompleteFormatter.format(time.time)
fun getAmpacheGetFormatted(time: Calendar): String = ampacheGetFormatter.format(time.time)
interface CurrentTimeUpdater {
fun getCurrentTimeUpdated(current: Calendar): Calendar
}
} | gpl-3.0 | e7c759059cca36502b5a5ec9bebd73ba | 35.340909 | 111 | 0.719024 | 4.916923 | false | false | false | false |
MimiReader/mimi-reader | mimi-app/src/main/java/com/emogoth/android/phone/mimi/span/YoutubeLinkSpan.kt | 1 | 2233 | package com.emogoth.android.phone.mimi.span
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Handler
import android.os.Looper
import android.text.TextPaint
import android.view.View
import android.widget.Toast
import com.emogoth.android.phone.mimi.R
import com.emogoth.android.phone.mimi.util.MimiUtil
import com.google.android.material.dialog.MaterialAlertDialogBuilder
class YoutubeLinkSpan(private val videoId: String, private val linkColor: Int) : LongClickableSpan() {
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.isUnderlineText = true
ds.color = linkColor
}
override fun onClick(widget: View) {
openLink(widget.context)
}
private fun showChoiceDialog(context: Context) {
val url = MimiUtil.https() + "youtube.com/watch?v=" + videoId
val handler = Handler(Looper.getMainLooper())
handler.post {
MaterialAlertDialogBuilder(context)
.setTitle(R.string.youtube_link)
.setItems(R.array.youtube_dialog_list) { dialog, which ->
if (which == 0) {
openLink(context)
} else {
val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clipboardManager.setPrimaryClip(ClipData.newPlainText("youtube_link", url))
Toast.makeText(context, R.string.link_copied_to_clipboard, Toast.LENGTH_SHORT).show()
}
}
.setCancelable(true)
.show()
.setCanceledOnTouchOutside(true)
}
}
private fun openLink(context: Context) {
val url = MimiUtil.https() + "youtube.com/watch?v=" + videoId
val openIntent = Intent(Intent.ACTION_VIEW)
openIntent.data = Uri.parse(url)
context.startActivity(openIntent)
}
override fun onLongClick(v: View): Boolean {
showChoiceDialog(v.context)
return true
}
} | apache-2.0 | 32aeb8161f99a9f4d1d1d78a7451d941 | 35.622951 | 122 | 0.630094 | 4.71097 | false | false | false | false |
Endran/Sandbox | KotlinSkeleton/app/src/main/java/nl/endran/skeleton/kotlin/mvp/BaseFragmentView.kt | 2 | 1397 | package nl.endran.skeleton.kotlin.mvp
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
abstract class BaseFragmentView<VM, P : BaseFragmentPresenter<VM>> {
protected var rootView: View? = null
protected var presenter: P? = null
open fun inflate(inflater: LayoutInflater, container: ViewGroup, @SuppressWarnings("unused") savedInstanceState: Bundle?): View {
rootView = inflater.inflate(getViewId(), container, false)
return rootView!!
}
fun androidViewReady() {
if (rootView != null) {
prepare(rootView!!)
}
}
fun deflate() {
stop()
rootView = null
}
fun start(presenter: P) {
this.presenter = presenter
val viewModel = getViewModel()
presenter.start(viewModel)
}
fun stop() {
presenter?.stop()
presenter = null
}
/**
* Return the view id to be inflated
*/
@LayoutRes
protected abstract fun getViewId(): Int
/**
* Create and return the implementation of the ViewModel
*/
protected abstract fun getViewModel(): VM
/**
* Convenience method so that the implementation knows when UI widget can be obtained and prepared.
*/
protected abstract fun prepare(rootView: View);
}
| apache-2.0 | 20f6cc40d85bc597242f2e3551e0e539 | 23.508772 | 133 | 0.647817 | 4.817241 | false | false | false | false |
CherepanovAleksei/BinarySearchTree | src/RBTree/RBTree.kt | 1 | 9163 | /**
*
* by Cherepanov Aleksei (PI-171)
*
* [email protected]
*
**/
package RBTree
import Interfaces.Tree
class RedBlackTree<K:Comparable<K>,V>:Tree<K,V>, Iterable<RBNode<K, V>>{
/*private*/var root: RBNode<K,V>? = null
override fun insert(key:K,value:V){
val newNode = RBNode(key, value)
var y:RBNode<K,V>?=null
var x:RBNode<K,V>?=this.root
while (x!=null){
y=x
when {
newNode.key < x.key -> x= x.left
newNode.key > x.key -> x=x.right
newNode.key == x.key -> {
x.value = newNode.value
return
}
}
}
newNode.parent=y
if(y==null) {
this.root=newNode
}
else if(newNode.key<y.key){
y.left=newNode
}
else{
y.right=newNode
}
newNode.color=true
newNode.right=null
newNode.left=null
this.stabilization(newNode)
}
fun stabilization(newNode: RBNode<K, V>?){
var z = newNode
var y:RBNode<K,V>?
while(z!!.parent?.color==true){
if (z.parent== z.parent?.parent?.left){
y=z.parent!!.parent!!.right
if(y?.color ==true){
z.parent!!.color=false
y.color=false
z.parent!!.parent!!.color=true
z=z.parent!!.parent
}else if(z== z.parent!!.right){
z=z.parent
leftRotate(z!!)
}else if(z==z.parent!!.left) {
z.parent!!.color = false
z.parent!!.parent!!.color = true
rightRotate(z.parent!!.parent!!)
}
}else{
y= z.parent?.parent?.left
if(y?.color==true){
z.parent!!.color=false
y.color=false
z.parent!!.parent!!.color=true
z=z.parent!!.parent
}else if(z== z.parent!!.left){
z=z.parent
rightRotate(z!!)
}else if(z== z.parent!!.right) {
z.parent!!.color = false
z.parent?.parent?.color = true
leftRotate(z.parent!!.parent!!)
}
}
}
this.root!!.color=false
}
override fun delete(key: K) {
val node = searchNode(key, root) ?: return
val min = searchMin(node.right)
when {
((node.right != null) && (node.left != null))
-> {
val nextKey = min!!.key
val nextValue = min.value
delete(min.key)
node.key = nextKey
node.value = nextValue
}
((node == root) && (node.right == null && node.left == null))
-> {
root = null
return
}
(node.color == true && node.right == null && node.left == null)
-> {
if (node.key < node.parent!!.key) {
node.parent!!.left = null
} else {
node.parent!!.right = null
}
return
}
(node.color == false && ((node.left != null) && (node.left!!.color == true)))
-> {
node.key = node.left!!.key
node.value = node.left!!.value
node.left = null
return
}
(node.color == false && (node.right != null) && (node.right!!.color == true))
-> {
node.key = node.right!!.key
node.value = node.right!!.value
node.right = null
return
}
else
-> {
deleteCase1(node)
}
}
if (node.key == key) {
if (node.key < node.parent!!.key) {
node.parent!!.left = null
} else {
node.parent!!.right = null
}
}
return
}
private fun deleteCase1(node: RBNode<K,V>) {
if (node == root) {
node.color = false
return
}
val brother = node.brother()
if (brother!!.color) {
node.parent!!.recoloring()
brother.recoloring()
if (node == node.parent!!.left) {
leftRotate(node.parent!!)
} else {
rightRotate(node.parent!!)
}
deleteCase1(node)
return
}
deleteCase2(node)
}
private fun deleteCase2(node: RBNode<K,V>) {
val brother = node.brother()
if (((brother!!.left == null) || !brother.left!!.color)
&& ((brother.right == null) || !brother.right!!.color))
{
node.color = false
brother.recoloring()
if (node.parent!!.color == true) {
node.parent!!.recoloring()
return
}
deleteCase1(node.parent!!)
return
}
if (node == node.parent!!.left) {
deleteCase3(node)
} else {
deleteCase4(node)
}
}
private fun deleteCase3(node: RBNode<K,V>) {
val brother = node.brother()
if ((brother!!.right == null) || brother.right!!.color == false) {
brother.recoloring()
brother.left!!.recoloring()
rightRotate(brother)
deleteCase1(node)
return
}
deleteCase3_2(node)
}
private fun deleteCase4(node: RBNode<K,V>) {
val brother = node.brother()
if ((brother!!.left == null) || brother.left!!.color == false) {
brother.recoloring()
brother.right!!.recoloring()
leftRotate(brother)
deleteCase1(node)
return
}
deleteCase4_2(node)
}
private fun deleteCase3_2(node: RBNode<K,V>) {
val brother = node.brother()
if ((brother!!.right != null) && brother.right!!.color == true) {
brother.color = node.parent!!.color
node.color = false
node.parent!!.color = false
brother.right!!.color = false
leftRotate(node.parent!!)
return
}
}
private fun deleteCase4_2(node: RBNode<K,V>) {
val brother = node.brother()
if ((brother!!.left != null) && brother.left!!.color == true) {
brother.color = node.parent!!.color
node.color = false
node.parent!!.color = false
brother.left!!.color = false
rightRotate(node.parent!!)
return
}
}
private fun leftRotate(x: RBNode<K,V>?){
val y:RBNode<K,V>?= x?.right
x?.right= y?.left
y?.left?.parent=x
y?.parent =x?.parent
if(x?.parent==null){
this.root=y
}
if(x == x?.parent?.left){
x?.parent?.left=y
}
if(x== x?.parent?.right){
x?.parent?.right=y
}
y?.left =x
x?.parent=y
}
private fun rightRotate(x: RBNode<K,V>?){
val y:RBNode<K,V>?= x!!.left
x.left= y!!.right
y.right?.parent=x
y.parent=x.parent
if(x.parent==null){
this.root=y
}
if(x==x.parent?.right){
x.parent?.right=y
}
if(x==x.parent?.left){
x.parent!!.left=y
}
y.right=x
x.parent=y
}
override fun search(key: K)=searchNode(key)?.value
/*private*/fun searchNode(key: K, node: RBNode<K,V>?=root): RBNode<K,V>? {
if(node==null) return null
if(key == node.key)return node
if(key < node.key) return searchNode(key, node.left)
else return searchNode(key, node.right)
}
private fun searchMax(node: RBNode<K, V>?=root): RBNode<K, V>? {
var max = node
while (max?.right != null) {
max = max.right
}
return max
}
private fun searchMin(node: RBNode<K, V>?=root): RBNode<K, V>? {
var min = node
while (min?.left != null) {
min = min.left
}
return min
}
override fun iterator(): Iterator<RBNode<K, V>> {
return (object : Iterator<RBNode<K, V>> {
var node = searchMax()
var next = searchMax()
val last = searchMin()
override fun hasNext(): Boolean {
return (node != null) && (node!!.key >= last!!.key)
}
override fun next(): RBNode<K, V> {
next = node
node = nextSmaller(node)
return next!!
}
})
}
private fun nextSmaller(node: RBNode<K, V>?): RBNode<K, V>?{
var smaller = node ?: return null
if ((smaller.left != null)) {
return searchMax(smaller.left!!)
}
else if ((smaller == smaller.parent?.left)) {
while (smaller == smaller.parent?.left) {
smaller = smaller.parent!!
}
}
return smaller.parent
}
} | mit | 77c8fffc63403f1cd271f1339567d5ad | 26.192878 | 85 | 0.45149 | 4.20514 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/page/PageProperties.kt | 1 | 2887 | package org.wikipedia.page
import android.location.Location
import android.os.Parcelable
import kotlinx.parcelize.IgnoredOnParcel
import kotlinx.parcelize.Parcelize
import kotlinx.parcelize.TypeParceler
import org.wikipedia.auth.AccountUtil
import org.wikipedia.dataclient.page.PageSummary
import org.wikipedia.dataclient.page.Protection
import org.wikipedia.parcel.DateParceler
import org.wikipedia.util.DateUtil
import org.wikipedia.util.DimenUtil
import org.wikipedia.util.ImageUrlUtil
import org.wikipedia.util.UriUtil
import java.util.*
@Parcelize
@TypeParceler<Date, DateParceler>()
data class PageProperties constructor(
val pageId: Int = 0,
val namespace: Namespace,
val revisionId: Long = 0,
val lastModified: Date = Date(),
val displayTitle: String = "",
private var editProtectionStatus: String = "",
val isMainPage: Boolean = false,
/** Nullable URL with no scheme. For example, foo.bar.com/ instead of http://foo.bar.com/. */
val leadImageUrl: String? = null,
val leadImageName: String? = null,
val leadImageWidth: Int = 0,
val leadImageHeight: Int = 0,
val geo: Location? = null,
val wikiBaseItem: String? = null,
val descriptionSource: String? = null,
// FIXME: This is not a true page property, since it depends on current user.
var canEdit: Boolean = false
) : Parcelable {
@IgnoredOnParcel
var protection: Protection? = null
set(value) {
field = value
editProtectionStatus = value?.firstAllowedEditorRole.orEmpty()
canEdit = editProtectionStatus.isEmpty() || isLoggedInUserAllowedToEdit
}
/**
* Side note: Should later be moved out of this class but I like the similarities with
* PageProperties(JSONObject).
*/
constructor(pageSummary: PageSummary) : this(
pageSummary.pageId,
pageSummary.ns,
pageSummary.revision,
if (pageSummary.timestamp.isEmpty()) Date() else DateUtil.iso8601DateParse(pageSummary.timestamp),
pageSummary.displayTitle,
isMainPage = pageSummary.type == PageSummary.TYPE_MAIN_PAGE,
leadImageUrl = pageSummary.thumbnailUrl?.let { ImageUrlUtil.getUrlForPreferredSize(it, DimenUtil.calculateLeadImageWidth()) },
leadImageName = UriUtil.decodeURL(pageSummary.leadImageName.orEmpty()),
leadImageWidth = pageSummary.thumbnailWidth,
leadImageHeight = pageSummary.thumbnailHeight,
geo = pageSummary.geo,
wikiBaseItem = pageSummary.wikiBaseItem,
descriptionSource = pageSummary.descriptionSource
)
constructor(title: PageTitle, isMainPage: Boolean) : this(namespace = title.namespace(),
displayTitle = title.displayText, isMainPage = isMainPage)
private val isLoggedInUserAllowedToEdit: Boolean
get() = protection?.run { AccountUtil.isMemberOf(editRoles) } ?: false
}
| apache-2.0 | d79ed49eb93dce785b7b7c774df56122 | 38.547945 | 134 | 0.720125 | 4.58254 | false | false | false | false |
AndroidX/androidx | window/window-samples/src/main/java/androidx/window/sample/embedding/SplitPipActivityBase.kt | 3 | 12807 | /*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.window.sample.embedding
import android.content.ComponentName
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.CompoundButton
import android.widget.RadioGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.util.Consumer
import androidx.window.embedding.ActivityFilter
import androidx.window.embedding.EmbeddingRule
import androidx.window.embedding.SplitController
import androidx.window.embedding.SplitInfo
import androidx.window.embedding.SplitPairFilter
import androidx.window.embedding.SplitPairRule
import androidx.window.embedding.SplitPlaceholderRule
import androidx.window.embedding.SplitRule
import androidx.window.sample.R
import androidx.window.sample.databinding.ActivitySplitPipActivityLayoutBinding
import androidx.window.sample.util.PictureInPictureUtil.setPictureInPictureParams
import androidx.window.sample.util.PictureInPictureUtil.startPictureInPicture
/**
* Sample showcase of split activity rules with picture-in-picture. Allows the user to select some
* split and PiP configuration options with checkboxes and launch activities with those options
* applied.
*/
abstract class SplitPipActivityBase : AppCompatActivity(), CompoundButton.OnCheckedChangeListener,
View.OnClickListener, RadioGroup.OnCheckedChangeListener {
lateinit var splitController: SplitController
lateinit var viewBinding: ActivitySplitPipActivityLayoutBinding
lateinit var componentNameA: ComponentName
lateinit var componentNameB: ComponentName
lateinit var componentNameNotPip: ComponentName
lateinit var componentNamePlaceholder: ComponentName
private val splitChangeListener = SplitStateChangeListener()
private val splitRatio = 0.5f
private var enterPipOnUserLeave = false
private var autoEnterPip = false
/** In the process of updating checkboxes based on split rule. */
private var updatingConfigs = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewBinding = ActivitySplitPipActivityLayoutBinding.inflate(layoutInflater)
setContentView(viewBinding.root)
componentNameA = ComponentName(packageName, SplitPipActivityA::class.java.name)
componentNameB = ComponentName(packageName, SplitPipActivityB::class.java.name)
componentNameNotPip = ComponentName(packageName, SplitPipActivityNoPip::class.java.name)
componentNamePlaceholder = ComponentName(packageName,
SplitPipActivityPlaceholder::class.java.name)
splitController = SplitController.getInstance(this)
// Buttons for split rules of the main activity.
viewBinding.splitMainCheckBox.setOnCheckedChangeListener(this)
viewBinding.finishPrimaryWithSecondaryCheckBox.setOnCheckedChangeListener(this)
viewBinding.finishSecondaryWithPrimaryCheckBox.setOnCheckedChangeListener(this)
// Buttons for split rules of the secondary activity.
viewBinding.launchBButton.setOnClickListener(this)
viewBinding.usePlaceHolderCheckBox.setOnCheckedChangeListener(this)
viewBinding.useStickyPlaceHolderCheckBox.setOnCheckedChangeListener(this)
// Buttons for launching an activity that doesn't support PiP
viewBinding.launchNoPipButton.setOnClickListener(this)
// Buttons for PiP options.
viewBinding.enterPipButton.setOnClickListener(this)
viewBinding.supportPipRadioGroup.setOnCheckedChangeListener(this)
}
/** Called on checkbox changed. */
override fun onCheckedChanged(button: CompoundButton, isChecked: Boolean) {
if (button.id == R.id.split_main_check_box) {
if (isChecked) {
viewBinding.finishPrimaryWithSecondaryCheckBox.isEnabled = true
viewBinding.finishSecondaryWithPrimaryCheckBox.isEnabled = true
} else {
viewBinding.finishPrimaryWithSecondaryCheckBox.isEnabled = false
viewBinding.finishPrimaryWithSecondaryCheckBox.isChecked = false
viewBinding.finishSecondaryWithPrimaryCheckBox.isEnabled = false
viewBinding.finishSecondaryWithPrimaryCheckBox.isChecked = false
}
}
if (button.id == R.id.use_place_holder_check_box) {
if (isChecked) {
viewBinding.useStickyPlaceHolderCheckBox.isEnabled = true
} else {
viewBinding.useStickyPlaceHolderCheckBox.isEnabled = false
viewBinding.useStickyPlaceHolderCheckBox.isChecked = false
}
}
if (!updatingConfigs) {
updateSplitRules()
}
}
/** Called on button clicked. */
override fun onClick(button: View) {
when (button.id) {
R.id.launch_b_button -> {
startActivity(Intent(this, SplitPipActivityB::class.java))
return
}
R.id.launch_no_pip_button -> {
startActivity(Intent(this, SplitPipActivityNoPip::class.java))
return
}
R.id.enter_pip_button -> {
startPictureInPicture(this, autoEnterPip)
}
}
}
/** Called on RatioGroup (PiP options) changed. */
override fun onCheckedChanged(group: RadioGroup, id: Int) {
when (id) {
R.id.support_pip_not_enter_on_exit -> {
enterPipOnUserLeave = false
autoEnterPip = false
}
R.id.support_pip_enter_on_user_leave -> {
enterPipOnUserLeave = true
autoEnterPip = false
}
R.id.support_pip_auto_enter -> {
enterPipOnUserLeave = false
autoEnterPip = true
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
Toast.makeText(this, "auto enter PiP not supported", Toast.LENGTH_LONG)
.show()
}
}
}
setPictureInPictureParams(this, autoEnterPip)
}
/** Enters PiP if enterPipOnUserLeave checkbox is checked. */
override fun onUserLeaveHint() {
super.onUserLeaveHint()
if (enterPipOnUserLeave) {
startPictureInPicture(this, autoEnterPip)
}
}
/** Updates the checkboxes states after the split rules are changed by other activity. */
internal fun updateCheckboxes() {
updatingConfigs = true
val curRules = splitController.getSplitRules()
val splitRule = curRules.firstOrNull { isRuleForSplit(it) }
val placeholderRule = curRules.firstOrNull { isRuleForPlaceholder(it) }
if (splitRule != null && splitRule is SplitPairRule) {
viewBinding.splitMainCheckBox.isChecked = true
viewBinding.finishPrimaryWithSecondaryCheckBox.isEnabled = true
viewBinding.finishPrimaryWithSecondaryCheckBox.isChecked =
splitRule.finishPrimaryWithSecondary == SplitRule.FINISH_ALWAYS
viewBinding.finishSecondaryWithPrimaryCheckBox.isEnabled = true
viewBinding.finishSecondaryWithPrimaryCheckBox.isChecked =
splitRule.finishSecondaryWithPrimary == SplitRule.FINISH_ALWAYS
} else {
viewBinding.splitMainCheckBox.isChecked = false
viewBinding.finishPrimaryWithSecondaryCheckBox.isEnabled = false
viewBinding.finishPrimaryWithSecondaryCheckBox.isChecked = false
viewBinding.finishSecondaryWithPrimaryCheckBox.isEnabled = false
viewBinding.finishSecondaryWithPrimaryCheckBox.isChecked = false
}
if (placeholderRule != null && placeholderRule is SplitPlaceholderRule) {
viewBinding.usePlaceHolderCheckBox.isChecked = true
viewBinding.useStickyPlaceHolderCheckBox.isEnabled = true
viewBinding.useStickyPlaceHolderCheckBox.isChecked = placeholderRule.isSticky
} else {
viewBinding.usePlaceHolderCheckBox.isChecked = false
viewBinding.useStickyPlaceHolderCheckBox.isEnabled = false
viewBinding.useStickyPlaceHolderCheckBox.isChecked = false
}
updatingConfigs = false
}
/** Whether the given rule is for splitting activity A and others. */
private fun isRuleForSplit(rule: EmbeddingRule): Boolean {
if (rule !is SplitPairRule) {
return false
}
for (filter in rule.filters) {
if (filter.primaryActivityName.className == SplitPipActivityA::class.java.name) {
return true
}
}
return false
}
/** Whether the given rule is for launching placeholder with activity B. */
private fun isRuleForPlaceholder(rule: EmbeddingRule): Boolean {
if (rule !is SplitPlaceholderRule) {
return false
}
for (filter in rule.filters) {
if (filter.componentName.className == SplitPipActivityB::class.java.name) {
return true
}
}
return false
}
/** Updates the split rules based on the current selection on checkboxes. */
private fun updateSplitRules() {
splitController.clearRegisteredRules()
if (viewBinding.splitMainCheckBox.isChecked) {
val pairFilters = HashSet<SplitPairFilter>()
pairFilters.add(SplitPairFilter(componentNameA, componentNameB, null))
pairFilters.add(SplitPairFilter(componentNameA, componentNameNotPip, null))
val finishAWithB = viewBinding.finishPrimaryWithSecondaryCheckBox.isChecked
val finishBWithA = viewBinding.finishSecondaryWithPrimaryCheckBox.isChecked
val rule = SplitPairRule.Builder(pairFilters)
.setMinWidthDp(0)
.setMinSmallestWidthDp(0)
.setFinishPrimaryWithSecondary(
if (finishAWithB) SplitRule.FINISH_ALWAYS else SplitRule.FINISH_NEVER)
.setFinishSecondaryWithPrimary(
if (finishBWithA) SplitRule.FINISH_ALWAYS else SplitRule.FINISH_NEVER)
.setClearTop(true)
.setSplitRatio(splitRatio)
.build()
splitController.registerRule(rule)
}
if (viewBinding.usePlaceHolderCheckBox.isChecked) {
val activityFilters = HashSet<ActivityFilter>()
activityFilters.add(ActivityFilter(componentNameB, null))
val intent = Intent().setComponent(componentNamePlaceholder)
val isSticky = viewBinding.useStickyPlaceHolderCheckBox.isChecked
val rule = SplitPlaceholderRule.Builder(activityFilters, intent)
.setMinWidthDp(0)
.setMinSmallestWidthDp(0)
.setSticky(isSticky)
.setFinishPrimaryWithPlaceholder(SplitRule.FINISH_ADJACENT)
.setSplitRatio(splitRatio)
.build()
splitController.registerRule(rule)
}
}
override fun onStart() {
super.onStart()
splitController.addSplitListener(
this,
ContextCompat.getMainExecutor(this),
splitChangeListener
)
}
override fun onStop() {
super.onStop()
splitController.removeSplitListener(splitChangeListener)
}
/** Updates the embedding status when receives callback from the extension. */
inner class SplitStateChangeListener : Consumer<List<SplitInfo>> {
override fun accept(newSplitInfos: List<SplitInfo>) {
var isInSplit = false
for (info in newSplitInfos) {
if (info.contains(this@SplitPipActivityBase) && info.splitRatio > 0) {
isInSplit = true
break
}
}
runOnUiThread {
viewBinding.activityEmbeddedStatusTextView.visibility =
if (isInSplit) View.VISIBLE else View.GONE
updateCheckboxes()
}
}
}
} | apache-2.0 | 3ea176b734f7f75bf4049059c40150bd | 40.993443 | 98 | 0.674787 | 5.651809 | false | false | false | false |
salRoid/Filmy | app/src/main/java/tech/salroid/filmy/ui/widget/FilmyWidgetProvider.kt | 1 | 3202 | /*
package tech.salroid.filmy.ui.widget
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.content.Intent
import android.widget.RemoteViews
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.AppWidgetTarget
import tech.salroid.filmy.R
import tech.salroid.filmy.ui.activities.MovieDetailsActivity
import tech.salroid.filmy.data.local.database.FilmContract
class FilmyWidgetProvider : AppWidgetProvider() {
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
var movieId = " "
var movieTitle = " "
var moviePoster = " "
for (element in appWidgetIds) {
val appWidgetId = element
val moviesForTheUri = FilmContract.MoviesEntry.CONTENT_URI
val selection: String? = null
val selectionArgs: Array<String>? = null
val cursor = context.contentResolver.query(
moviesForTheUri,
MovieProjection.MOVIE_COLUMNS,
selection,
selectionArgs,
null
)
if (cursor != null && cursor.count > 0) {
cursor.moveToFirst()
val idIndex = cursor.getColumnIndex(FilmContract.MoviesEntry.MOVIE_ID)
val titleIndex = cursor.getColumnIndex(FilmContract.MoviesEntry.MOVIE_TITLE)
val posterIndex = cursor.getColumnIndex(FilmContract.MoviesEntry.MOVIE_POSTER_LINK)
val yearIndex = cursor.getColumnIndex(FilmContract.MoviesEntry.MOVIE_YEAR)
movieId = cursor.getString(idIndex)
movieTitle = cursor.getString(titleIndex)
moviePoster = cursor.getString(posterIndex)
//String imdb_id = cursor.getString(id_index);
//int movie_year = cursor.getInt(year_index);
}
cursor?.close()
val remoteViews = RemoteViews(context.packageName, R.layout.filmy_appwidget)
remoteViews.setTextViewText(R.id.widget_movie_name, movieTitle)
val appWidgetTarget =
AppWidgetTarget(context, R.id.widget_movie_image, remoteViews, *appWidgetIds)
Glide.with(context)
.asBitmap()
.load(moviePoster)
.into(appWidgetTarget)
val intent = Intent(context, MovieDetailsActivity::class.java)
intent.putExtra("title", movieTitle)
intent.putExtra("activity", true)
intent.putExtra("type", -1)
intent.putExtra("database_applicable", false)
intent.putExtra("network_applicable", true)
intent.putExtra("id", movieId)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val pendingIntent =
PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
remoteViews.setOnClickPendingIntent(R.id.activity_opener, pendingIntent)
appWidgetManager.updateAppWidget(appWidgetId, remoteViews)
}
}
}*/
| apache-2.0 | b16d4c52095472fea1097c6011026ced | 38.530864 | 99 | 0.637414 | 5.098726 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/refactoring/RsDowngradeModuleToFileTest.kt | 3 | 2121 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.refactoring
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.psi.PsiElement
import org.rust.FileTree
import org.rust.RsTestBase
import org.rust.fileTree
import org.rust.launchAction
class RsDowngradeModuleToFileTest : RsTestBase() {
fun `test works on file`() = checkAvailable(
"foo/mod.rs",
fileTree {
dir("foo") {
rust("mod.rs", "fn hello() {}")
}
},
fileTree {
rust("foo.rs", "fn hello() {}")
}
)
fun `test works on directory`() = checkAvailable(
"foo",
fileTree {
dir("foo") {
rust("mod.rs", "fn hello() {}")
}
},
fileTree {
rust("foo.rs", "fn hello() {}")
}
)
fun `test not available on wrong file`() = checkNotAvailable(
"foo/bar.rs",
fileTree {
dir("foo") {
rust("mod.rs", "")
rust("bar.rs", "")
}
}
)
fun `test not available on full directory`() = checkNotAvailable(
"foo/mod.rs",
fileTree {
dir("foo") {
rust("mod.rs", "")
rust("bar.rs", "")
}
}
)
private fun checkAvailable(target: String, before: FileTree, after: FileTree) {
val file = before.create().psiFile(target)
testActionOnElement(file, shouldBeEnabled = true)
after.assertEquals(myFixture.findFileInTempDir("."))
}
private fun checkNotAvailable(target: String, before: FileTree) {
val file = before.create().psiFile(target)
testActionOnElement(file, shouldBeEnabled = false)
}
private fun testActionOnElement(element: PsiElement, shouldBeEnabled: Boolean) {
myFixture.launchAction(
"Rust.RsDowngradeModuleToFile",
CommonDataKeys.PSI_ELEMENT to element,
shouldBeEnabled = shouldBeEnabled
)
}
}
| mit | 9091a10920da4f0b7886d17ff41c64db | 25.5125 | 84 | 0.550212 | 4.661538 | false | true | false | false |
androidx/androidx | compose/desktop/desktop/samples/src/jvmMain/kotlin/androidx/compose/desktop/examples/popupexample/AppState.jvm.kt | 3 | 2717 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.desktop.examples.popupexample
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import java.awt.image.BufferedImage
import javax.imageio.ImageIO
object AppState {
private val imageRes: String = "androidx/compose/desktop/example/tray.png"
private var icon: BufferedImage? = null
var isMainWindowOpen by mutableStateOf(true)
private set
val secondaryWindowIds = mutableStateListOf<Int>()
private var lastId = 0
fun openSecondaryWindow() {
secondaryWindowIds.add(lastId++)
}
fun closeMainWindow() {
isMainWindowOpen = false
}
fun closeSecondaryWindow(id: Int) {
secondaryWindowIds.remove(id)
}
fun closeAll() {
isMainWindowOpen = false
secondaryWindowIds.clear()
}
fun image(): BufferedImage {
if (icon != null) {
return icon!!
}
try {
val img = Thread.currentThread().contextClassLoader.getResource(imageRes)
val bitmap: BufferedImage? = ImageIO.read(img)
if (bitmap != null) {
icon = bitmap
return bitmap
}
} catch (e: Exception) {
e.printStackTrace()
}
return BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)
}
val wndTitle = mutableStateOf("Desktop Compose Popup")
val popupState = mutableStateOf(false)
val amount = mutableStateOf(0)
val undecorated = mutableStateOf(false)
val alertDialog = mutableStateOf(false)
val notify = mutableStateOf(true)
val warn = mutableStateOf(false)
val error = mutableStateOf(false)
fun diselectOthers(state: MutableState<Boolean>) {
if (notify != state) {
notify.value = false
}
if (warn != state) {
warn.value = false
}
if (error != state) {
error.value = false
}
}
} | apache-2.0 | 18e8bdbce6453a1c36be536b5dff4287 | 28.225806 | 85 | 0.659183 | 4.62862 | false | false | false | false |
nimakro/tornadofx | src/main/java/tornadofx/ListView.kt | 1 | 8306 | package tornadofx
import javafx.beans.property.ObjectProperty
import javafx.beans.property.Property
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.collections.FXCollections
import javafx.collections.ObservableMap
import javafx.scene.Node
import javafx.scene.control.ListCell
import javafx.scene.control.ListView
import javafx.scene.control.SelectionMode
import javafx.scene.control.TableView
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyEvent
import javafx.scene.input.MouseEvent
import javafx.util.Callback
import tornadofx.FX.IgnoreParentBuilder.No
import tornadofx.FX.IgnoreParentBuilder.Once
import kotlin.reflect.KClass
/**
* Execute action when the enter key is pressed or the mouse is clicked
* @param clickCount The number of mouse clicks to trigger the action
* @param action The runnable to execute on select
*/
fun <T> ListView<T>.onUserSelect(clickCount: Int = 2, action: (T) -> Unit) {
addEventFilter(MouseEvent.MOUSE_CLICKED) { event ->
val selectedItem = this.selectedItem
if (event.clickCount == clickCount && selectedItem != null && event.target.isInsideRow())
action(selectedItem)
}
addEventFilter(KeyEvent.KEY_PRESSED) { event ->
val selectedItem = this.selectedItem
if (event.code == KeyCode.ENTER && !event.isMetaDown && selectedItem != null)
action(selectedItem)
}
}
val <T> ListView<T>.selectedItem: T?
get() = selectionModel.selectedItem
fun <T> ListView<T>.asyncItems(func: () -> Collection<T>) =
task { func() } success { if (items == null) items = FXCollections.observableArrayList(it) else items.setAll(it) }
fun <T> ListView<T>.onUserDelete(action: (T) -> Unit) {
addEventFilter(KeyEvent.KEY_PRESSED) { event ->
val selectedItem = this.selectedItem
if (event.code == KeyCode.BACK_SPACE && selectedItem != null)
action(selectedItem)
}
}
class ListCellCache<T>(private val cacheProvider: (T) -> Node) {
private val store = mutableMapOf<T, Node>()
fun getOrCreateNode(value: T) = store.getOrPut(value, { cacheProvider(value) })
}
abstract class ItemFragment<T> : Fragment() {
val itemProperty: ObjectProperty<T> = SimpleObjectProperty(this, "item")
val item by itemProperty
}
abstract class RowItemFragment<S, T> : ItemFragment<T>() {
val rowItemProperty: ObjectProperty<S> = SimpleObjectProperty(this, "rowItem")
val rowItem by rowItemProperty
}
abstract class ListCellFragment<T> : ItemFragment<T>() {
val cellProperty: ObjectProperty<ListCell<T>?> = SimpleObjectProperty()
var cell by cellProperty
val editingProperty = SimpleBooleanProperty(false)
val editing by editingProperty
open fun startEdit() {
cell?.startEdit()
}
open fun commitEdit(newValue: T) {
cell?.commitEdit(newValue)
}
open fun cancelEdit() {
cell?.cancelEdit()
}
open fun onEdit(op: () -> Unit) {
editingProperty.onChange { if (it) op() }
}
}
@Suppress("UNCHECKED_CAST")
open class SmartListCell<T>(val scope: Scope = DefaultScope, listView: ListView<T>?, properties: Map<Any,Any>? = null) : ListCell<T>() {
/**
* A convenience constructor allowing to omit `listView` completely, if needed.
*/
constructor(scope: Scope = DefaultScope, properties : Map<Any,Any>? = null) : this(scope, null, properties)
private val smartProperties: ObservableMap<Any,Any> = listView?.properties ?: HashMap(properties.orEmpty()).observable()
private val editSupport: (ListCell<T>.(EditEventType, T?) -> Unit)? get() = smartProperties["tornadofx.editSupport"] as (ListCell<T>.(EditEventType, T?) -> Unit)?
private val cellFormat: (ListCell<T>.(T) -> Unit)? get() = smartProperties["tornadofx.cellFormat"] as (ListCell<T>.(T) -> Unit)?
private val cellCache: ListCellCache<T>? get() = smartProperties["tornadofx.cellCache"] as ListCellCache<T>?
private var cellFragment: ListCellFragment<T>? = null
private var fresh = true
init {
if (listView != null) {
properties?.let { listView.properties?.putAll(it) }
listView.properties["tornadofx.cellFormatCapable"] = true
listView.properties["tornadofx.cellCacheCapable"] = true
listView.properties["tornadofx.editCapable"] = true
}
indexProperty().onChange {
if (it == -1) clearCellFragment()
}
}
override fun startEdit() {
super.startEdit()
editSupport?.invoke(this, EditEventType.StartEdit, null)
}
override fun commitEdit(newValue: T) {
super.commitEdit(newValue)
editSupport?.invoke(this, EditEventType.CommitEdit, newValue)
}
override fun cancelEdit() {
super.cancelEdit()
editSupport?.invoke(this, EditEventType.CancelEdit, null)
}
override fun updateItem(item: T, empty: Boolean) {
super.updateItem(item, empty)
if (item == null || empty) {
textProperty().unbind()
graphicProperty().unbind()
text = null
graphic = null
clearCellFragment()
} else {
FX.ignoreParentBuilder = Once
try {
cellCache?.apply { graphic = getOrCreateNode(item) }
} finally {
FX.ignoreParentBuilder = No
}
if (fresh) {
val cellFragmentType = smartProperties["tornadofx.cellFragment"] as KClass<ListCellFragment<T>>?
cellFragment = if (cellFragmentType != null) find(cellFragmentType, scope) else null
fresh = false
}
cellFragment?.apply {
editingProperty.cleanBind(editingProperty())
itemProperty.value = item
cellProperty.value = this@SmartListCell
graphic = root
}
cellFormat?.invoke(this, item)
}
}
private fun clearCellFragment() {
cellFragment?.apply {
cellProperty.value = null
itemProperty.value = null
editingProperty.unbind()
editingProperty.value = false
}
}
}
fun <T> ListView<T>.bindSelected(property: Property<T>) {
selectionModel.selectedItemProperty().onChange {
property.value = it
}
}
fun <T> ListView<T>.bindSelected(model: ItemViewModel<T>) = this.bindSelected(model.itemProperty)
fun <T, F : ListCellFragment<T>> ListView<T>.cellFragment(scope: Scope = DefaultScope, fragment: KClass<F>) {
properties["tornadofx.cellFragment"] = fragment
if (properties["tornadofx.cellFormatCapable"] != true)
cellFactory = Callback { SmartListCell(scope, it) }
}
@Suppress("UNCHECKED_CAST")
fun <T> ListView<T>.cellFormat(scope: Scope = DefaultScope, formatter: (ListCell<T>.(T) -> Unit)) {
properties["tornadofx.cellFormat"] = formatter
if (properties["tornadofx.cellFormatCapable"] != true)
cellFactory = Callback { SmartListCell(scope, it) }
}
fun <T> ListView<T>.onEdit(scope: Scope = DefaultScope, eventListener: ListCell<T>.(EditEventType, T?) -> Unit) {
isEditable = true
properties["tornadofx.editSupport"] = eventListener
// Install a edit capable cellFactory it none is present. The default cellFormat factory will do.
if (properties["tornadofx.editCapable"] != true) cellFormat(scope) { }
}
/**
* Calculate a unique Node per item and set this Node as the graphic of the ListCell.
*
* To support this feature, a custom cellFactory is automatically installed, unless an already
* compatible cellFactory is found. The cellFactories installed via #cellFormat already knows
* how to retrieve cached values.
*/
fun <T> ListView<T>.cellCache(scope: Scope = DefaultScope, cachedGraphicProvider: (T) -> Node) {
properties["tornadofx.cellCache"] = ListCellCache(cachedGraphicProvider)
// Install a cache capable cellFactory it none is present. The default cellFormat factory will do.
if (properties["tornadofx.cellCacheCapable"] != true) {
cellFormat(scope) { }
}
}
fun <T> ListView<T>.multiSelect(enable: Boolean = true) {
selectionModel.selectionMode = if (enable) SelectionMode.MULTIPLE else SelectionMode.SINGLE
}
| apache-2.0 | ce3984268d0e36bc263fd64a9ce9b647 | 36.414414 | 166 | 0.672526 | 4.51413 | false | false | false | false |
oleksiyp/mockk | mockk/jvm/src/main/kotlin/io/mockk/impl/platform/JvmWeakConcurrentMap.kt | 1 | 3238 | package io.mockk.impl.platform
import java.lang.ref.ReferenceQueue
import java.lang.ref.WeakReference
import java.util.concurrent.ConcurrentHashMap
class JvmWeakConcurrentMap<K, V>() : MutableMap<K, V> {
private val map = ConcurrentHashMap<Any, V>()
private val queue = ReferenceQueue<K>()
override fun get(key: K): V? {
return map[StrongKey(key)]
}
override fun put(key: K, value: V): V? {
expunge()
return map.put(WeakKey(key, queue), value)
}
override fun remove(key: K): V? {
expunge()
return map.remove(StrongKey(key))
}
private fun expunge() {
var ref = queue.poll()
while (ref != null) {
val value = map.remove(ref)
if (value is Disposable) {
value.dispose()
}
ref = queue.poll()
}
}
private class WeakKey<K>(key: K, queue: ReferenceQueue<K>) : WeakReference<K>(key, queue) {
private val hashCode: Int
init {
hashCode = System.identityHashCode(key)
}
override fun equals(other: Any?): Boolean {
if (other === this) {
return true
} else {
val key = get()
if (key != null) {
if (other is WeakKey<*>) {
return key === other.get()
} else if (other is StrongKey<*>) {
return key === other.get()
}
}
}
return false
}
override fun hashCode(): Int {
return hashCode
}
}
private class StrongKey<K>(private val key: K) {
private val hashCode: Int
init {
hashCode = System.identityHashCode(key)
}
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
} else {
val key = get()
if (key != null) {
if (other is WeakKey<*>) {
return key === other.get()
} else if (other is StrongKey<*>) {
return key === other.get()
}
}
}
return false
}
override fun hashCode(): Int {
return hashCode
}
fun get(): K? {
return key
}
}
override val size
get() = map.size
override fun isEmpty(): Boolean {
return map.isEmpty()
}
override fun containsKey(key: K): Boolean {
return get(key) != null
}
override fun containsValue(value: V): Boolean {
return map.containsValue(value)
}
override fun putAll(from: Map<out K, V>) {
throw UnsupportedOperationException("putAll")
}
override fun clear() {
map.clear()
}
override val entries: MutableSet<MutableMap.MutableEntry<K, V>>
get() = throw UnsupportedOperationException("entries")
override val keys: MutableSet<K>
get() = throw UnsupportedOperationException("entries")
override val values: MutableCollection<V>
get() = map.values
} | apache-2.0 | e847e2f2eb97834ea8db5aa42bf033d7 | 24.503937 | 95 | 0.495676 | 4.727007 | false | false | false | false |
mgouline/slack-uploader | src/main/java/net/gouline/slackuploader/app.kt | 1 | 3417 | package net.gouline.slackuploader
import com.beust.jcommander.JCommander
import com.beust.jcommander.Parameter
import com.beust.jcommander.ParameterException
import okhttp3.*
import java.io.File
import java.util.*
import kotlin.system.exitProcess
fun main(args: Array<String>) {
val cmd = Commands()
val commander = JCommander(cmd)
commander.setProgramName("slack-uploader")
try {
commander.parse(*args)
} catch (e: ParameterException) {
error(e.message)
}
if (cmd.help) {
commander.usage()
} else if (cmd.token == null) {
error("No token provided.")
} else if (cmd.title == null) {
error("No title provided.")
} else if (cmd.channels.isEmpty()) {
error("No channels provided.")
} else if (cmd.files.isEmpty()) {
error("No files provided.")
} else {
val file = File(cmd.files.first())
if (!file.exists()) {
error("File not found.")
} else {
SlackClient(cmd.token!!).upload(file, cmd.title!!, cmd.channels)
}
}
}
/**
* Minimal Slack client.
*/
class SlackClient(val token: String) {
companion object {
private const val BASE_URL = "https://slack.com/api"
private const val FILES_UPLOAD_URL = "$BASE_URL/files.upload"
}
private val client = OkHttpClient()
/**
* Uploads file to channels.
*/
fun upload(file: File, title: String, channels: List<String>) {
val response = execute(FILES_UPLOAD_URL, {
it.addFormDataPart("title", title)
.addFormDataPart("channels", channels.joinToString(","))
.addFormDataPart("file", file.name, RequestBody.create(null, file))
})
if (response.isSuccessful) {
success(response.body().string())
} else {
error("Request failed: $response")
}
}
private inline fun execute(url: String, f: (MultipartBody.Builder) -> Unit): Response {
val body = MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("token", token)
.apply { f(this) }
.build()
val request = Request.Builder()
.url(url)
.post(body)
.build()
return client.newCall(request).execute()
}
}
/**
* CLI input commands.
*/
class Commands {
@Parameter(names = arrayOf("--help", "-h"), description = "Displays this usage.", help = true)
var help = false
@field:Parameter(names = arrayOf("--token", "-a"), description = "Authentication token (requires scope 'files:write:user').", required = true)
var token: String? = null
@field:Parameter(names = arrayOf("--title", "-t"), description = "Title of file.", required = true)
var title: String? = null
@field:Parameter(names = arrayOf("--channel", "-c"), description = "Channel names or IDs where the file will be shared.", required = true)
var channels: List<String> = ArrayList()
@field:Parameter(description = "FILE", required = true)
var files: List<String> = ArrayList()
}
/**
* Prints success message.
*/
private fun success(message: String?) {
println("SUCCESS: $message")
exitProcess(0)
}
/**
* Prints error message and quits.
*/
private fun error(message: String?) {
println("ERROR: $message")
exitProcess(1)
}
| mit | c2eb26ef4683b2d0c1e96e3470801bb5 | 27.714286 | 146 | 0.59643 | 4.111913 | false | false | false | false |
jvalduvieco/blok | lib/Domain/src/main/kotlin/com/blok/post/Infrastructure/PostgresPostRepository.kt | 1 | 5418 | package com.blok.post.Infrastructure
import com.blok.common.DatabaseSetup
import com.blok.model.*
import com.github.andrewoma.kwery.core.DefaultSession
import com.github.andrewoma.kwery.core.Row
import com.github.andrewoma.kwery.core.dialect.PostgresDialect
import java.sql.Connection
import java.sql.DriverManager
import java.sql.Timestamp
fun Post.toMap(): Map<String, Any?> = mapOf(
"id" to this.id(),
"title" to this.title,
"content" to this.content,
"publishing_date" to Timestamp.valueOf(this.publishingDate)
)
fun Comment.toMap(): Map<String, Any?> = mapOf(
"id" to this.id(),
"content" to this.content,
"author" to this.author,
"post_id" to this.post_id(),
"approved" to this.approved,
"submission_date" to Timestamp.valueOf(this.submissionDate)
)
open class PostgresPostRepository(dbSetup: DatabaseSetup) : PostRepository {
val postMapper: (Row) -> Post = { row ->
Post(PostId(row.string("id")),
row.string("title"),
row.string("content"),
row.timestamp("publishing_date").toLocalDateTime(),
row.stringOrNull("categories")?.split(',')?:listOf()
)
}
val commentMapper: (Row) -> Comment = {row ->
Comment(CommentId(row.string("id")),
PostId(row.string("post_id")),
row.string("author"),
row.string("content"),
row.timestamp("submission_date").toLocalDateTime(),
row.boolean("approved")
)
}
protected val session: DefaultSession
init {
Class.forName( "org.postgresql.Driver" )
val connection: Connection = DriverManager.getConnection(
"jdbc:postgresql://${dbSetup.host}:${dbSetup.port}/${dbSetup.name}?", dbSetup.username, dbSetup.password)
session = DefaultSession(connection, PostgresDialect())
}
override fun save(post: Post): PostId {
session.transaction {
val sql = "INSERT INTO " +
"posts (id, title, content, publishing_date) " +
"VALUES (:id, :title, :content, :publishing_date) ON CONFLICT (id) " +
"DO UPDATE SET (title, content, publishing_date) = (:title, :content, :publishing_date) " +
"WHERE posts.id = :id"
session.update(sql, post.toMap())
session.update("DELETE FROM posts_categories WHERE id = :id", mapOf("id" to post.id()))
val sqlCategories = "INSERT INTO " +
"posts_categories(id, category) " +
"VALUES (:id, :category)"
post.categories.forEach {
category ->
session.update(sqlCategories, mapOf("id" to post.id(), "category" to category))
}
}
return post.id
}
override fun save(comment: Comment): CommentId {
val sql = "INSERT INTO " +
"comments " +
"(id, post_id, author, content, approved, submission_date) " +
"VALUES " +
"(:id, :post_id, :author, :content, :approved, :submission_date)"
session.update(sql, comment.toMap())
return comment.id
}
override fun update(post: Post) {
save(post)
}
override fun listAllPosts(): List<Post> {
return session.select(
"SELECT p.id, p.title, p.content, p.publishing_date,string_agg(pc.category,',') AS categories " +
"FROM posts AS p LEFT JOIN posts_categories AS pc ON p.id = pc.id " +
"GROUP BY p.id", mapper = postMapper)
}
override fun getAllCommentsOn(id: PostId): List<Comment> {
if (!existPost(id)) throw PostRepository.PostNotFound(id)
return session.select(
"SELECT * " +
"FROM comments " +
"WHERE post_id=:post_id",
hashMapOf("post_id" to id()),
mapper = commentMapper
)
}
override fun existPost(id: PostId): Boolean {
return session.select("SELECT " +
"FROM posts " +
"WHERE id=:post_id",
hashMapOf("post_id" to id()),
mapper = {}
).count() == 1
}
override fun getPost(id: PostId): Post {
return session.select(
"SELECT p.id, p.title, p.content, p.publishing_date,string_agg(pc.category,',') AS categories " +
"FROM posts AS p LEFT JOIN posts_categories AS pc ON p.id = pc.id " +
"WHERE p.id=:post_id " +
"GROUP BY p.id",
hashMapOf("post_id" to id()),
mapper = postMapper
).firstOrNull()?: throw PostRepository.PostNotFound(id)
}
override fun deletePost(id: PostId) {
if (!existPost(id)) throw PostRepository.PostNotFound(id)
session.update("DELETE FROM posts WHERE id=:post_id", hashMapOf("post_id" to id()))
}
override fun deleteComment(id: CommentId) {
session.update("DELETE FROM comments WHERE id=:comment_id", hashMapOf("comment_id" to id()))
}
}
class PostgresPostRepositoryForTesting(dbSetup: DatabaseSetup) : PostgresPostRepository(dbSetup), PostRepositoryForTesting, PostRepository {
override fun cleanDatabase() {
session.update("TRUNCATE posts CASCADE")
}
} | mit | 1dfc63c75d27038752fa17d730ff8ec1 | 40.684615 | 140 | 0.570506 | 4.269504 | false | false | false | false |
jeremymailen/kotlinter-gradle | src/main/kotlin/org/jmailen/gradle/kotlinter/support/SortedThreadSafeReporterWrapper.kt | 1 | 2426 | package org.jmailen.gradle.kotlinter.support
import com.pinterest.ktlint.core.LintError
import com.pinterest.ktlint.core.Reporter
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
import java.util.concurrent.ConcurrentSkipListSet
/**
* A wrapper for a Reporter that guarantees thread safety and consistent ordering of all the calls to the reporter.
* As a downside, the calls to the wrapped reporter are delayed until the end of the execution.
*/
class SortedThreadSafeReporterWrapper(
private val wrapped: Reporter,
) : Reporter {
private val callsToBefore: ConcurrentMap<String, Unit> = ConcurrentHashMap()
private val lintErrorReports: ConcurrentMap<String, ConcurrentSkipListSet<LintErrorReport>> = ConcurrentHashMap()
private val callsToAfter: ConcurrentMap<String, Unit> = ConcurrentHashMap()
override fun beforeAll() {
wrapped.beforeAll()
}
override fun before(file: String) {
callsToBefore[file] = Unit
}
override fun onLintError(file: String, err: LintError, corrected: Boolean) {
lintErrorReports.putIfAbsent(file, ConcurrentSkipListSet())
lintErrorReports[file]!!.add(LintErrorReport(err, corrected))
}
override fun after(file: String) {
callsToAfter[file] = Unit
}
override fun afterAll() {
(callsToBefore.keys + lintErrorReports.keys + callsToAfter.keys)
.sorted()
.forEach { fileName ->
if (callsToBefore.contains(fileName)) {
wrapped.before(fileName)
}
lintErrorReports[fileName]?.let { lintErrorReports ->
lintErrorReports.forEach {
wrapped.onLintError(fileName, it.lintError, it.corrected)
}
}
if (callsToAfter.contains(fileName)) {
wrapped.after(fileName)
}
}
wrapped.afterAll()
}
fun unwrap() = wrapped
private data class LintErrorReport(
val lintError: LintError,
val corrected: Boolean,
) : Comparable<LintErrorReport> {
override fun compareTo(other: LintErrorReport) = when (lintError.line == other.lintError.line) {
true -> lintError.col.compareTo(other.lintError.col)
false -> lintError.line.compareTo(other.lintError.line)
}
}
}
| apache-2.0 | d89846e91a63a8a6b452ea798a65422d | 34.15942 | 117 | 0.652927 | 5.002062 | false | false | false | false |
Tvede-dk/CommonsenseAndroidKotlin | system/src/main/kotlin/com/commonsense/android/kotlin/system/permissions/PermissionsExtensions.kt | 1 | 10524 | package com.commonsense.android.kotlin.system.permissions
import android.content.*
import android.support.annotation.*
import com.commonsense.android.kotlin.base.*
import com.commonsense.android.kotlin.base.extensions.collections.*
import com.commonsense.android.kotlin.system.base.*
//region Permission enum extensions
@UiThread
fun PermissionEnum.useIfPermitted(context: Context,
usePermission: EmptyFunction,
useError: EmptyFunction) {
havePermission(context)
.ifTrue(usePermission)
.ifFalse(useError)
}
@UiThread
inline fun PermissionEnum.usePermission(context: Context, usePermission: EmptyFunction) {
havePermission(context).ifTrue(usePermission)
}
@UiThread
fun PermissionEnum.havePermission(context: Context): Boolean =
context.havePermission(permissionValue)
//endregion
//region activity / fragment permissions extensions
//region Base activity permission enum
/**
* Asks iff necessary, for the use of the given permission
* if allowed, the usePermission callback will be called
* if not allowed the onFailed callback will be called
*/
@UiThread
fun BaseActivity.usePermissionEnum(permission: PermissionEnum,
usePermission: EmptyFunction,
onFailed: PermissionsFailedCallback? = null) {
permissionHandler.performActionForPermissionsEnum(
listOf(permission),
this,
usePermission,
onFailed)
}
@UiThread
fun BaseActivity.usePermissionEnumFull(permission: PermissionEnum,
usePermission: PermissionsSuccessCallback,
onFailed: PermissionsFailedCallback? = null) {
permissionHandler.performActionForPermissionsEnumFull(
listOf(permission),
this,
usePermission,
onFailed)
}
@UiThread
fun BaseActivity.usePermissionEnums(permissions: List<PermissionEnum>,
usePermission: EmptyFunction,
onFailed: PermissionsFailedCallback? = null) {
permissionHandler.performActionForPermissionsEnum(
permissions,
this,
usePermission,
onFailed)
}
@UiThread
fun BaseActivity.usePermissionEnumsFull(permissions: List<PermissionEnum>,
usePermission: PermissionsSuccessCallback,
onFailed: PermissionsFailedCallback? = null) {
permissionHandler.performActionForPermissionsEnumFull(
permissions,
this,
usePermission,
onFailed)
}
//endregion
//region Base activity permission string
@UiThread
fun BaseActivity.usePermission(permission: @DangerousPermissionString String,
usePermission: EmptyFunction,
onFailed: PermissionsFailedCallback? = null) {
permissionHandler.performActionForPermissions(
listOf(permission),
this,
usePermission,
onFailed)
}
@UiThread
fun BaseActivity.usePermissionFull(permission: @DangerousPermissionString String,
usePermission: PermissionsSuccessCallback,
onFailed: PermissionsFailedCallback? = null) {
permissionHandler.performActionForPermissionsFull(
listOf(permission),
this,
usePermission,
onFailed)
}
@UiThread
fun BaseActivity.usePermissions(permissions: List<@DangerousPermissionString String>,
usePermission: EmptyFunction,
onFailed: PermissionsFailedCallback? = null) {
permissionHandler.performActionForPermissions(
permissions.toList(),
this,
usePermission,
onFailed)
}
@UiThread
fun BaseActivity.usePermissionsFull(permissions: List<@DangerousPermissionString String>,
usePermission: PermissionsSuccessCallback,
onFailed: PermissionsFailedCallback? = null) {
permissionHandler.performActionForPermissionsFull(
permissions.toList(),
this,
usePermission,
onFailed)
}
//endregion
//region Base fragment use permission enum
/**
*
* NB if the activity IS NOT A BASEACTIVITY then onfailed will be called
* @receiver BaseFragment
* @param permission PermissionEnum
* @param usePermission EmptyFunction
* @param onFailed PermissionsFailedCallback?
*/
@UiThread
fun BaseFragment.usePermissionEnum(permission: PermissionEnum,
usePermission: EmptyFunction,
onFailed: PermissionsFailedCallback?) {
val baseAct = baseActivity
if (baseAct != null) {
baseAct.usePermissionEnum(
permission,
usePermission,
onFailed)
} else {
onFailed?.invoke(emptyList(), listOf(permission.permissionValue))
}
}
/**
*
* NB if the activity IS NOT A BASEACTIVITY then onfailed will be called
* @receiver BaseFragment
* @param permission PermissionEnum
* @param usePermission PermissionsSuccessCallback
* @param onFailed PermissionsFailedCallback?
*/
@UiThread
fun BaseFragment.usePermissionEnumFull(permission: PermissionEnum,
usePermission: PermissionsSuccessCallback,
onFailed: PermissionsFailedCallback?) {
val baseAct = baseActivity
if (baseAct != null) {
baseAct.usePermissionEnumFull(
permission,
usePermission,
onFailed)
} else {
onFailed?.invoke(emptyList(), listOf(permission.permissionValue))
}
}
/**
*
* NB if the activity IS NOT A BASEACTIVITY then onfailed will be called
* @receiver BaseFragment
* @param permissions List<PermissionEnum>
* @param usePermission EmptyFunction
* @param onFailed PermissionsFailedCallback?
*/
@UiThread
fun BaseFragment.usePermissionEnums(permissions: List<PermissionEnum>,
usePermission: EmptyFunction,
onFailed: PermissionsFailedCallback?) {
val baseAct = baseActivity
if (baseAct != null) {
baseAct.usePermissionEnums(
permissions,
usePermission,
onFailed)
} else {
onFailed?.invoke(emptyList(), permissions.map { it.permissionValue })
}
}
/**
*
* NB if the activity IS NOT A BASEACTIVITY then onfailed will be called
* @receiver BaseFragment
* @param permissions List<PermissionEnum>
* @param usePermission PermissionsSuccessCallback
* @param onFailed PermissionsFailedCallback?
*/
@UiThread
fun BaseFragment.usePermissionEnumsFull(permissions: List<PermissionEnum>,
usePermission: PermissionsSuccessCallback,
onFailed: PermissionsFailedCallback?) {
val baseAct = baseActivity
if (baseAct != null) {
baseAct.usePermissionEnumsFull(
permissions,
usePermission,
onFailed)
} else {
onFailed?.invoke(emptyList(), permissions.map { it.permissionValue })
}
}
//endregion
//region base fragment use permission string
/**
*
* NB if the activity IS NOT A BASEACTIVITY then onfailed will be called
* @receiver BaseFragment
* @param permission @DangerousPermissionString String
* @param usePermission EmptyFunction
* @param onFailed PermissionsFailedCallback?
*/
@UiThread
fun BaseFragment.usePermission(permission: @DangerousPermissionString String,
usePermission: EmptyFunction,
onFailed: PermissionsFailedCallback?) {
val baseAct = baseActivity
if (baseAct != null) {
baseAct.usePermission(
permission,
usePermission,
onFailed)
} else {
onFailed?.invoke(emptyList(), listOf(permission))
}
}
/**
*
* NB if the activity IS NOT A BASEACTIVITY then onfailed will be called
* @receiver BaseFragment
* @param permission @DangerousPermissionString String
* @param usePermission PermissionsSuccessCallback
* @param onFailed PermissionsFailedCallback?
*/
@UiThread
fun BaseFragment.usePermissionFull(permission: @DangerousPermissionString String,
usePermission: PermissionsSuccessCallback,
onFailed: PermissionsFailedCallback?) {
val baseAct = baseActivity
if (baseAct != null) {
baseAct.usePermissionFull(
permission,
usePermission,
onFailed)
} else {
onFailed?.invoke(emptyList(), listOf(permission))
}
}
/**
*
* NB if the activity IS NOT A BASEACTIVITY then onfailed will be called
* @receiver BaseFragment
* @param permission List<@DangerousPermissionString String>
* @param usePermission EmptyFunction
* @param onFailed PermissionsFailedCallback?
*/
@UiThread
fun BaseFragment.usePermissions(permission: List<@DangerousPermissionString String>,
usePermission: EmptyFunction,
onFailed: PermissionsFailedCallback?) {
val baseAct = baseActivity
if (baseAct != null) {
baseAct.usePermissions(
permission,
usePermission,
onFailed)
} else {
onFailed?.invoke(emptyList(), permission)
}
}
/**
*
* NB if the activity IS NOT A BASEACTIVITY then onfailed will be called
* @receiver BaseFragment
* @param permission List<@DangerousPermissionString String>
* @param usePermission PermissionsSuccessCallback
* @param onFailed PermissionsFailedCallback?
*/
@UiThread
fun BaseFragment.usePermissionsFull(permission: List<@DangerousPermissionString String>,
usePermission: PermissionsSuccessCallback,
onFailed: PermissionsFailedCallback?) {
val baseAct = baseActivity
if (baseAct != null) {
baseAct.usePermissionsFull(
permission,
usePermission,
onFailed)
} else {
onFailed?.invoke(emptyList(), permission)
}
}
//endregion
//endregion
| mit | 90cdf7fb9ffb8d04d74ed4551d744450 | 31.582043 | 89 | 0.632649 | 6.301796 | false | false | false | false |
0x1bad1d3a/Kaku | app/src/main/java/ca/fuwafuwa/kaku/Windows/WindowCoordinator.kt | 2 | 2283 | package ca.fuwafuwa.kaku.Windows
import android.content.Context
import ca.fuwafuwa.kaku.*
/**
* It seems like opening and closing a bunch of windows causes Android to start to lag pretty hard.
* Therefore, we should keep only one instance of each type of window in memory, and show()ing and
* hide()ing the window when necessary. This class is to help facilitate this communication.
*
* Edit: The lag actually might have been caused by a memory leak. But this is here now, so might
* as well keep it.
*/
class WindowCoordinator(private val context: Context)
{
val windows: MutableMap<String, Window> = mutableMapOf()
private val windowInitMap: Map<String, () -> Window> = mutableMapOf(
WINDOW_INFO to fun(): Window { return InformationWindow(context, this) },
WINDOW_EDIT to fun(): Window { return EditWindow(context, this) },
WINDOW_CAPTURE to fun(): Window { return CaptureWindow(context, this) },
WINDOW_INSTANT_KANJI to fun(): Window { return InstantKanjiWindow(context, this) },
//WINDOW_HISTORY to fun(): Window { return HistoryWindow(context, this) },
WINDOW_KANJI_CHOICE to fun(): Window { return KanjiChoiceWindow(context, this) }
)
fun getWindow(key: String) : Window
{
if (!windows.containsKey(key))
{
windows[key] = windowInitMap.getValue(key).invoke()
}
return windows[key]!!
}
fun <WindowType> getWindowOfType(key: String) : WindowType
{
return getWindow(key) as WindowType
}
/**
* Should only be called by {@link Window#stop()} - calling this outside that method may result in a memory leak
*/
fun removeWindow(window: Window)
{
var key : String? = null
windows.forEach {
if (it.value === window)
{
key = it.key
}
}
if (key != null) windows.remove(key!!)
}
fun hasWindow(key: String) : Boolean
{
return windows.containsKey(key)
}
fun reinitAllWindows()
{
windows.forEach { it.value.reInit(Window.ReinitOptions()) }
}
fun stopAllWindows()
{
val windows = windows.toList()
windows.forEach { it.second.stop() }
}
} | bsd-3-clause | 8f41658b6d5eca341b8935b804d4ede7 | 29.864865 | 116 | 0.622427 | 4.235622 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/data/elementfilter/ElementFilterExpression.kt | 1 | 1572 | package de.westnordost.streetcomplete.data.elementfilter
import de.westnordost.osmapi.map.data.Element
import de.westnordost.streetcomplete.data.elementfilter.ElementsTypeFilter.NODES
import de.westnordost.streetcomplete.data.elementfilter.ElementsTypeFilter.WAYS
import de.westnordost.streetcomplete.data.elementfilter.ElementsTypeFilter.RELATIONS
import de.westnordost.streetcomplete.data.elementfilter.filters.ElementFilter
import java.util.*
/** Represents a parse result of a string in filter syntax, i.e.
* "ways with (highway = residential or highway = tertiary) and !name" */
class ElementFilterExpression(
private val elementsTypes: EnumSet<ElementsTypeFilter>,
private val elementExprRoot: BooleanExpression<ElementFilter, Element>?
) {
/** returns whether the given element is found through (=matches) this expression */
fun matches(element: Element): Boolean =
includesElementType(element.type) && (elementExprRoot?.matches(element) ?: true)
fun includesElementType(elementType: Element.Type): Boolean = when (elementType) {
Element.Type.NODE -> elementsTypes.contains(NODES)
Element.Type.WAY -> elementsTypes.contains(WAYS)
Element.Type.RELATION -> elementsTypes.contains(RELATIONS)
else -> false
}
/** returns this expression as a Overpass query string */
fun toOverpassQLString(): String = OverpassQueryCreator(elementsTypes, elementExprRoot).create()
}
/** Enum that specifies which type(s) of elements to retrieve */
enum class ElementsTypeFilter { NODES, WAYS, RELATIONS }
| gpl-3.0 | 7e9bbfcd1e6c01108b71b9babb13b82e | 48.125 | 100 | 0.769084 | 4.556522 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/social/UserStyles.kt | 1 | 1395 | package com.habitrpg.android.habitica.models.social
import com.habitrpg.android.habitica.models.user.Authentication
import com.habitrpg.android.habitica.models.user.Flags
import com.habitrpg.android.habitica.models.user.Items
import com.habitrpg.android.habitica.models.user.Outfit
import com.habitrpg.android.habitica.models.user.Preferences
import com.habitrpg.android.habitica.models.user.Stats
import com.habitrpg.shared.habitica.models.Avatar
import io.realm.RealmObject
import io.realm.annotations.RealmClass
@RealmClass(embedded = true)
open class UserStyles : RealmObject(), Avatar {
override val currentMount: String?
get() = items?.currentMount
override val currentPet: String?
get() = items?.currentPet
override val sleep: Boolean
get() = false
override val gemCount: Int
get() = 0
override val hourglassCount: Int
get() = 0
override val costume: Outfit?
get() = items?.gear?.costume
override val equipped: Outfit?
get() = items?.gear?.equipped
override val hasClass: Boolean
get() {
return false
}
override var balance: Double = 0.0
override var authentication: Authentication? = null
override var stats: Stats? = null
override var preferences: Preferences? = null
override var flags: Flags? = null
override var items: Items? = null
}
| gpl-3.0 | 65108b46b2b551137e48dc720f3d995c | 30 | 63 | 0.712545 | 4.318885 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.