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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
stripe/stripe-android | link/src/main/java/com/stripe/android/link/ui/verification/VerificationDialog.kt | 1 | 5421 | package com.stripe.android.link.ui.verification
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.stripe.android.link.LinkPaymentLauncher
import com.stripe.android.link.LinkScreen
import com.stripe.android.link.R
import com.stripe.android.link.theme.DefaultLinkTheme
import com.stripe.android.link.theme.linkShapes
import com.stripe.android.link.ui.LinkAppBar
import com.stripe.android.link.ui.rememberLinkAppBarState
/**
* Function called when the Link verification dialog has been dismissed. The boolean returned
* indicates whether the verification succeeded.
* When called, [LinkPaymentLauncher.accountStatus] will contain the up to date account status.
*/
@Deprecated(
level = DeprecationLevel.WARNING,
message = "This interface isn't meant for public consumption.",
)
typealias LinkVerificationCallback = (success: Boolean) -> Unit
@Suppress("LongMethod")
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun LinkVerificationDialog(
linkLauncher: LinkPaymentLauncher,
onResult: (Boolean) -> Unit,
) {
// Must be inside a NavController so that the VerificationViewModel scope is destroyed when the
// dialog is dismissed, and when called again a new scope is created.
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = LinkScreen.VerificationDialog.route
) {
composable(LinkScreen.VerificationDialog.route) {
var openDialog by remember { mutableStateOf(true) }
val component = requireNotNull(linkLauncher.component)
val linkAccount = component.linkAccountManager.linkAccount.collectAsState()
val linkEventsReporter = component.linkEventsReporter
val onDismiss = {
openDialog = false
linkEventsReporter.on2FACancel()
onResult(false)
}
val backStackEntry by navController.currentBackStackEntryAsState()
linkAccount.value?.let { account ->
if (openDialog) {
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
DefaultLinkTheme {
Surface(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
shape = MaterialTheme.linkShapes.medium
) {
Column {
val appBarState = rememberLinkAppBarState(
isRootScreen = true,
currentRoute = backStackEntry?.destination?.route,
email = account.email,
accountStatus = account.accountStatus
)
LinkAppBar(
state = appBarState,
onBackPressed = onDismiss,
onLogout = {
// This can't be invoked from the verification dialog
},
showBottomSheetContent = {
// This can't be invoked from the verification dialog
}
)
VerificationBody(
headerStringResId = R.string.verification_header_prefilled,
messageStringResId = R.string.verification_message,
showChangeEmailMessage = false,
linkAccount = account,
injector = component.injector,
onVerificationCompleted = {
openDialog = false
onResult(true)
}
)
}
}
}
}
}
}
}
}
}
| mit | bf4715dbffbd6ea7effa534ae68ad59d | 43.073171 | 99 | 0.554141 | 6.370153 | false | false | false | false |
stripe/stripe-android | payments-core/src/test/java/com/stripe/android/networking/ApiRequestMatcher.kt | 1 | 763 | package com.stripe.android.networking
import com.stripe.android.core.networking.ApiRequest
import com.stripe.android.core.networking.StripeRequest
import org.mockito.ArgumentMatcher
internal class ApiRequestMatcher @JvmOverloads constructor(
private val method: StripeRequest.Method,
private val url: String,
private val options: ApiRequest.Options,
private val params: Map<String, *>? = null
) : ArgumentMatcher<ApiRequest> {
override fun matches(request: ApiRequest): Boolean {
val url = runCatching {
request.url
}.getOrNull()
return this.url == url &&
method == request.method &&
options == request.options &&
(params == null || params == request.params)
}
}
| mit | 43d206db49a655b407bc75396d23e980 | 30.791667 | 59 | 0.677588 | 4.652439 | false | false | false | false |
AndroidX/androidx | room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/ksp/synthetic/KspSyntheticReceiverParameterElement.kt | 3 | 4180 | /*
* 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.room.compiler.processing.ksp.synthetic
import androidx.room.compiler.processing.XAnnotated
import androidx.room.compiler.processing.XEquality
import androidx.room.compiler.processing.XExecutableParameterElement
import androidx.room.compiler.processing.XMemberContainer
import androidx.room.compiler.processing.XType
import androidx.room.compiler.processing.ksp.KspAnnotated
import androidx.room.compiler.processing.ksp.KspJvmTypeResolutionScope
import androidx.room.compiler.processing.ksp.KspMethodElement
import androidx.room.compiler.processing.ksp.KspProcessingEnv
import androidx.room.compiler.processing.ksp.KspType
import com.google.devtools.ksp.symbol.KSDeclaration
import com.google.devtools.ksp.symbol.KSType
import com.google.devtools.ksp.symbol.KSTypeReference
internal class KspSyntheticReceiverParameterElement(
val env: KspProcessingEnv,
override val enclosingElement: KspMethodElement,
val receiverType: KSTypeReference,
) : XExecutableParameterElement,
XEquality,
XAnnotated by KspAnnotated.create(
env = env,
delegate = null, // does not matter, this is synthetic and has no annotations.
filter = KspAnnotated.UseSiteFilter.NO_USE_SITE
) {
override val name: String by lazy {
// KAPT uses `$this$<functionName>`
"$" + "this" + "$" + enclosingElement.name
}
override val equalityItems: Array<out Any?> by lazy {
arrayOf(enclosingElement, receiverType)
}
override val hasDefaultValue: Boolean
get() = false
private fun jvmTypeResolutionScope(container: KSDeclaration?): KspJvmTypeResolutionScope {
return KspJvmTypeResolutionScope.MethodParameter(
kspExecutableElement = enclosingElement,
parameterIndex = 0, // Receiver param is the 1st one
annotated = enclosingElement.declaration,
container = container
)
}
override val type: KspType by lazy {
asMemberOf(enclosingElement.enclosingElement.type?.ksType)
}
override val fallbackLocationText: String
get() = "receiver parameter of ${enclosingElement.fallbackLocationText}"
// Not applicable
override val docComment: String? get() = null
override val closestMemberContainer: XMemberContainer by lazy {
enclosingElement.closestMemberContainer
}
override fun asMemberOf(other: XType): KspType {
if (closestMemberContainer.type?.isSameType(other) != false) {
return type
}
check(other is KspType)
return asMemberOf(other.ksType)
}
private fun asMemberOf(ksType: KSType?): KspType {
val asMemberReceiverType = receiverType.resolve().let {
if (ksType == null || it.isError) {
return@let it
}
val asMember = enclosingElement.declaration.asMemberOf(ksType)
checkNotNull(asMember.extensionReceiverType)
}
return env.wrap(
originatingReference = receiverType,
ksType = asMemberReceiverType,
).withJvmTypeResolver(
jvmTypeResolutionScope(
container = ksType?.declaration
)
)
}
override fun kindName(): String {
return "synthetic receiver parameter"
}
override fun validate(): Boolean {
return true
}
override fun equals(other: Any?): Boolean {
return XEquality.equals(this, other)
}
override fun hashCode(): Int {
return XEquality.hashCode(equalityItems)
}
}
| apache-2.0 | 7772c33b4d7bbb1978089129db789264 | 33.545455 | 94 | 0.701675 | 4.810127 | false | false | false | false |
exponent/exponent | android/expoview/src/main/java/host/exp/exponent/notifications/NotificationActionCenter.kt | 2 | 2821 | package host.exp.exponent.notifications
import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import android.os.Looper
import androidx.core.app.NotificationCompat
import androidx.core.app.RemoteInput
import com.raizlabs.android.dbflow.sql.language.SQLite
import com.raizlabs.android.dbflow.sql.language.Select
import host.exp.exponent.kernel.KernelConstants
import java.util.*
object NotificationActionCenter {
const val KEY_TEXT_REPLY = "notification_remote_input"
@Synchronized
@JvmStatic fun putCategory(categoryId: String?, actions: List<MutableMap<String?, Any?>>) {
throwExceptionIfOnMainThread()
for (i in actions.indices) {
val action = actions[i].apply {
this["categoryId"] = categoryId
}
ActionObject(action, i).save()
}
}
@Synchronized
@JvmStatic fun removeCategory(categoryId: String?) {
val actions = SQLite.select().from(ActionObject::class.java)
.where(ActionObject_Table.categoryId.eq(categoryId))
.queryList()
for (actionObject in actions) {
actionObject.delete()
}
}
@Synchronized
fun setCategory(
categoryId: String,
builder: NotificationCompat.Builder,
context: Context,
intentProvider: IntentProvider
) {
throwExceptionIfOnMainThread()
// Expo Go has a permanent notification, so we have to set max priority in order to show up buttons
builder.priority = Notification.PRIORITY_MAX
val actions = Select().from(ActionObject::class.java)
.where(ActionObject_Table.categoryId.eq(categoryId))
.orderBy(ActionObject_Table.position, true)
.queryList()
for (actionObject in actions) {
addAction(builder, actionObject, intentProvider, context)
}
}
private fun addAction(
builder: NotificationCompat.Builder,
actionObject: ActionObject,
intentProvider: IntentProvider,
context: Context
) {
val intent = intentProvider.provide().apply {
putExtra(KernelConstants.NOTIFICATION_ACTION_TYPE_KEY, actionObject.actionId)
}
val pendingIntent = PendingIntent.getActivity(
context,
UUID.randomUUID().hashCode(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val actionBuilder = NotificationCompat.Action.Builder(
0,
actionObject.buttonTitle,
pendingIntent
)
if (actionObject.isShouldShowTextInput) {
actionBuilder.addRemoteInput(
RemoteInput.Builder(KEY_TEXT_REPLY)
.setLabel(actionObject.placeholder)
.build()
)
}
builder.addAction(actionBuilder.build())
}
private fun throwExceptionIfOnMainThread() {
if (Looper.myLooper() == Looper.getMainLooper()) {
throw RuntimeException("Do not use NotificationActionCenter class on the main thread!")
}
}
}
| bsd-3-clause | dbd8fd3fd16808a3f22f9eb1e3a6f927 | 27.494949 | 103 | 0.71145 | 4.492038 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/RsApproxConstantInspection.kt | 3 | 2490 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
import org.rust.lang.core.psi.RsLitExpr
import org.rust.lang.core.psi.RsLiteralKind
import org.rust.lang.core.psi.RsVisitor
import org.rust.lang.core.psi.ext.RsElement
import org.rust.lang.core.psi.kind
import kotlin.math.*
class RsApproxConstantInspection : RsLocalInspectionTool() {
override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean): RsVisitor = object : RsVisitor() {
override fun visitLitExpr(o: RsLitExpr) {
val literal = o.kind
if (literal is RsLiteralKind.Float) {
val value = literal.value ?: return
val constant = KNOWN_CONSTS.find { it.matches(value) } ?: return
holder.registerProblem(o, literal.suffix ?: "f64", constant)
}
}
}
private companion object {
@JvmField
val KNOWN_CONSTS: List<PredefinedConstant> = listOf(
PredefinedConstant("E", Math.E, 4),
PredefinedConstant("FRAC_1_PI", 1.0 / Math.PI, 4),
PredefinedConstant("FRAC_1_SQRT_2", 1.0 / sqrt(2.0), 5),
PredefinedConstant("FRAC_2_PI", 2.0 / Math.PI, 5),
PredefinedConstant("FRAC_2_SQRT_PI", 2.0 / sqrt(Math.PI), 5),
PredefinedConstant("FRAC_PI_2", Math.PI / 2.0, 5),
PredefinedConstant("FRAC_PI_3", Math.PI / 3.0, 5),
PredefinedConstant("FRAC_PI_4", Math.PI / 4.0, 5),
PredefinedConstant("FRAC_PI_6", Math.PI / 6.0, 5),
PredefinedConstant("FRAC_PI_8", Math.PI / 8.0, 5),
PredefinedConstant("LN_10", ln(10.0), 5),
PredefinedConstant("LN_2", ln(2.0), 5),
PredefinedConstant("LOG10_E", log10(Math.E), 5),
PredefinedConstant("LOG2_E", ln(Math.E) / ln(2.0), 5),
PredefinedConstant("PI", Math.PI, 3),
PredefinedConstant("SQRT_2", sqrt(2.0), 5)
)
}
}
data class PredefinedConstant(val name: String, val value: Double, val minDigits: Int) {
private val accuracy: Double = 0.1.pow(minDigits.toDouble())
fun matches(value: Double): Boolean = abs(value - this.value) < accuracy
}
private fun RsProblemsHolder.registerProblem(element: RsElement, type: String, constant: PredefinedConstant) {
registerProblem(element, "Approximate value of `std::$type::consts::${constant.name}` found. Consider using it directly.")
}
| mit | 1c0f545434b1682b65c6f42918638cda | 41.931034 | 126 | 0.629317 | 3.635036 | false | false | false | false |
satamas/fortran-plugin | src/main/kotlin/org/jetbrains/fortran/lang/utils/FortranDiagnostic.kt | 1 | 4690 | package org.jetbrains.fortran.lang.utils
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElement
import org.jetbrains.fortran.ide.inspections.FortranTypeCheckInspection
import org.jetbrains.fortran.lang.types.ty.FortranType
import org.jetbrains.fortran.lang.types.ty.escaped
sealed class FortranDiagnostic(
val element: PsiElement,
val endElement: PsiElement? = null,
val inspectionClass: Class<*>) {
abstract fun prepare(): PreparedAnnotation
fun addToHolder(holder: ProblemsHolder) {
if (element.textOffset >= element.textRange.endOffset) return
val prepared = prepare()
val descriptor = holder.manager.createProblemDescriptor(
element,
endElement ?: element,
"<html>${prepared.header}<br>${prepared.description}</html>",
prepared.severity.toProblemHighlightType(),
holder.isOnTheFly,
*prepared.fixes.toTypedArray()
)
holder.registerProblem(descriptor)
}
class TypeError(
element: PsiElement,
private val expectedTy: FortranType,
private val actualTy: FortranType
) : FortranDiagnostic(element, inspectionClass = FortranTypeCheckInspection::class.java) {
override fun prepare(): PreparedAnnotation {
return PreparedAnnotation(
Severity.ERROR,
"mismatched types",
expectedFound(expectedTy, actualTy),
fixes = emptyList()
)
}
private fun expectedFound(expectedTy: FortranType, actualTy: FortranType): String {
return "expected `${expectedTy.escaped}`, found `${actualTy.escaped}`"
}
}
class MalformedBinaryExpression(
element: PsiElement,
private val leftArgumentType: FortranType,
private val rightArgumentType: FortranType
) : FortranDiagnostic(element, inspectionClass = FortranTypeCheckInspection::class.java) {
override fun prepare(): PreparedAnnotation {
return PreparedAnnotation(
Severity.ERROR,
"mismatched argument types", differentArgumentTypes(leftArgumentType, rightArgumentType),
fixes = emptyList()
)
}
private fun differentArgumentTypes(leftArgumentType: FortranType, rightArgumentType: FortranType): String {
return "left argument: ${leftArgumentType.escaped}, right argument: ${rightArgumentType.escaped}"
}
}
class MalformedArrayConstructor(element: PsiElement,
private val arrayBaseType: FortranType,
private val mismatchedType: FortranType
) : FortranDiagnostic(element, inspectionClass = FortranTypeCheckInspection::class.java) {
override fun prepare(): PreparedAnnotation {
return PreparedAnnotation(
Severity.ERROR,
"mismatched array constructor element type", mismatchedTypes(arrayBaseType, mismatchedType),
fixes = emptyList()
)
}
private fun mismatchedTypes(arrayBaseType: FortranType, mismatchedType: FortranType): String {
return "array base type: ${arrayBaseType.escaped}, element type: ${mismatchedType.escaped}"
}
}
class MalformedImplicitDoLoop(element: PsiElement,
private val elementType: FortranType
) : FortranDiagnostic(element, inspectionClass = FortranTypeCheckInspection::class.java) {
override fun prepare(): PreparedAnnotation {
return PreparedAnnotation(
Severity.ERROR,
"incorrect implicit do loop", mismatchedType(elementType),
fixes = emptyList()
)
}
private fun mismatchedType(elementType: FortranType): String {
return "expected: integer, got: ${elementType.escaped}"
}
}
}
class PreparedAnnotation(
val severity: Severity,
val header: String,
val description: String,
val fixes: List<LocalQuickFix> = emptyList()
)
enum class Severity {
INFO, WARN, ERROR;
fun toProblemHighlightType(): ProblemHighlightType = when (this) {
Severity.INFO -> ProblemHighlightType.INFORMATION
Severity.WARN -> ProblemHighlightType.WEAK_WARNING
Severity.ERROR -> ProblemHighlightType.GENERIC_ERROR_OR_WARNING
}
} | apache-2.0 | 13c43adf2501c799e9983ce66eeaff8c | 38.091667 | 115 | 0.638166 | 5.657419 | false | false | false | false |
brave-warrior/TravisClient_Android | app-v3/src/test/java/com/khmelenko/lab/varis/dagger/TestNetworkModule.kt | 2 | 1831 | package com.khmelenko.lab.varis.dagger
import com.khmelenko.lab.varis.log.LogsParser
import com.khmelenko.lab.varis.network.retrofit.github.GitHubRestClient
import com.khmelenko.lab.varis.network.retrofit.github.GithubApiService
import com.khmelenko.lab.varis.network.retrofit.raw.RawApiService
import com.khmelenko.lab.varis.network.retrofit.raw.RawClient
import com.khmelenko.lab.varis.network.retrofit.travis.TravisApiService
import com.khmelenko.lab.varis.network.retrofit.travis.TravisRestClient
import com.nhaarman.mockito_kotlin.whenever
import dagger.Module
import dagger.Provides
import org.mockito.Mockito.mock
import javax.inject.Singleton
/**
* NetworkModule for testing
*
* @author Dmytro Khmelenko ([email protected])
*/
@Module
class TestNetworkModule {
@Singleton
@Provides
fun provideTravisRestClient(): TravisRestClient {
val travisRestClient = mock(TravisRestClient::class.java)
val apiService = mock(TravisApiService::class.java)
whenever(travisRestClient.apiService).thenReturn(apiService)
return travisRestClient
}
@Singleton
@Provides
fun provideGitHubRestClient(): GitHubRestClient {
val gitHubRestClient = mock(GitHubRestClient::class.java)
val githubApiService = mock(GithubApiService::class.java)
whenever(gitHubRestClient.apiService).thenReturn(githubApiService)
return gitHubRestClient
}
@Singleton
@Provides
fun provideRawRestClient(): RawClient {
val rawClient = mock(RawClient::class.java)
val rawApiService = mock(RawApiService::class.java)
whenever(rawClient.apiService).thenReturn(rawApiService)
return rawClient
}
@Singleton
@Provides
fun provideLogsParser(): LogsParser {
return mock(LogsParser::class.java)
}
}
| apache-2.0 | ae59e5462647741c6ee20c7f516d274d | 31.696429 | 74 | 0.754233 | 4.268065 | false | false | false | false |
andstatus/andstatus | app/src/androidTest/kotlin/org/andstatus/app/note/NoteEditorTest.kt | 1 | 18428 | /*
* Copyright (C) 2014 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.note
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.view.View
import android.widget.EditText
import android.widget.TextView
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ReplaceTextAction
import androidx.test.espresso.assertion.ViewAssertions
import androidx.test.espresso.matcher.ViewMatchers
import org.andstatus.app.ActivityRequestCode
import org.andstatus.app.ActivityTestHelper
import org.andstatus.app.HelpActivity
import org.andstatus.app.R
import org.andstatus.app.account.MyAccount
import org.andstatus.app.activity.ActivityViewItem
import org.andstatus.app.context.DemoData
import org.andstatus.app.context.MyContextHolder
import org.andstatus.app.context.MyPreferences
import org.andstatus.app.context.TestSuite
import org.andstatus.app.data.DbUtils
import org.andstatus.app.data.DownloadStatus
import org.andstatus.app.data.MyContentType
import org.andstatus.app.data.MyQuery
import org.andstatus.app.data.OidEnum
import org.andstatus.app.data.TextMediaType
import org.andstatus.app.database.table.ActivityTable
import org.andstatus.app.database.table.NoteTable
import org.andstatus.app.net.social.Audience
import org.andstatus.app.net.social.Audience.Companion.fromNoteId
import org.andstatus.app.origin.Origin
import org.andstatus.app.service.MyServiceManager
import org.andstatus.app.timeline.ListActivityTestHelper
import org.andstatus.app.timeline.TimelineActivity
import org.andstatus.app.timeline.TimelineActivityTest
import org.andstatus.app.timeline.meta.Timeline
import org.andstatus.app.timeline.meta.TimelineType
import org.andstatus.app.util.EspressoUtils
import org.andstatus.app.util.MyHtml
import org.andstatus.app.util.MyHtmlTest
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.ScreenshotOnFailure
import org.hamcrest.CoreMatchers
import org.junit.Assert
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Test
import java.util.concurrent.atomic.AtomicInteger
import kotlin.properties.Delegates
/**
* On activity testing: http://developer.android.com/tools/testing/activity_testing.html
* @author [email protected]
*/
class NoteEditorTest : TimelineActivityTest<ActivityViewItem>() {
private var data: NoteEditorData by Delegates.notNull()
override fun getActivityIntent(): Intent {
MyLog.i(this, "setUp started")
TestSuite.initializeWithData(this)
if (editingStep.get() != 1) {
MyPreferences.setBeingEditedNoteId(0)
}
val ma: MyAccount = DemoData.demoData.getMyAccount(DemoData.demoData.conversationAccountName)
Assert.assertTrue(ma.isValid)
MyContextHolder.myContextHolder.getNow().accounts.setCurrentAccount(ma)
data = getStaticData(ma)
val timeline: Timeline =
MyContextHolder.myContextHolder.getNow().timelines.get(TimelineType.HOME, ma.actor, Origin.EMPTY)
MyLog.i(this, "setUp ended, $timeline")
return Intent(Intent.ACTION_VIEW, timeline.getUri())
}
private fun getStaticData(ma: MyAccount): NoteEditorData {
return NoteEditorData.Companion.newReplyTo(
MyQuery.oidToId(
OidEnum.NOTE_OID, ma.origin.id,
DemoData.demoData.conversationEntryNoteOid
), ma
)
.addToAudience(
MyQuery.oidToId(
OidEnum.ACTOR_OID, ma.origin.id,
DemoData.demoData.conversationEntryAuthorOid
)
)
.addMentionsToText()
.setContent(MyHtmlTest.twitterBodyTypedPlain + " " + DemoData.demoData.testRunUid, TextMediaType.PLAIN)
}
@Test
fun testEditing1() {
Assert.assertTrue("MyService is available", MyServiceManager.Companion.isServiceAvailable())
editingTester()
}
@Test
fun testEditing2() {
editingTester()
}
private fun editingTester() {
TestSuite.waitForListLoaded(activity, 2)
when (editingStep.incrementAndGet()) {
2 -> editingStep2()
else -> {
editingStep.set(1)
ActivityTestHelper.openEditor<ActivityViewItem>("default", activity)
editingStep1()
}
}
MyLog.v(this, "After step " + editingStep + " ended")
}
private fun editingStep1() {
val method = "editingStep1"
MyLog.v(this, "$method started")
val editorView: View = ActivityTestHelper.hideEditorAndSaveDraft<ActivityViewItem>(method, activity)
val editor = activity.getNoteEditor() ?: throw IllegalStateException("No editor")
getInstrumentation().runOnMainSync { editor.startEditingNote(data) }
EspressoUtils.waitForIdleSync()
ActivityTestHelper.waitViewVisible(method, editorView)
assertInitialText("Initial text")
MyLog.v(this, "$method ended")
}
private fun editingStep2() {
val method = "editingStep2"
MyLog.v(this, "$method started")
val helper = ActivityTestHelper<TimelineActivity<*>>(activity)
val editorView = activity.findViewById<View?>(R.id.note_editor)
ActivityTestHelper.waitViewVisible("$method; Restored note is visible", editorView)
assertInitialText("Note restored")
ActivityTestHelper.hideEditorAndSaveDraft(method, activity)
ActivityTestHelper.openEditor<ActivityViewItem>(method, activity)
assertTextCleared(this)
helper.clickMenuItem("$method click Discard", R.id.discardButton)
ActivityTestHelper.waitViewInvisible("$method; Editor hidden after discard", editorView)
MyLog.v(this, "$method ended")
}
@Test
fun attachOneImage() {
attachImages(this, 1, 1)
}
@Test
fun attachTwoImages() {
attachImages(this, 2, 1)
}
private fun assertInitialText(description: String) {
val editor = activity.getNoteEditor() ?: throw IllegalStateException("No editor")
val textView = activity.findViewById<TextView?>(R.id.noteBodyEditText)
ActivityTestHelper.waitTextInAView(
description, textView,
MyHtml.fromContentStored(data.getContent(), TextMediaType.PLAIN)
)
Assert.assertEquals(description, data.toTestSummary(), editor.getData().toTestSummary())
}
@Test
fun editLoadedNote() {
val method = "editLoadedNote"
TestSuite.waitForListLoaded(activity, 2)
val helper = ListActivityTestHelper<TimelineActivity<*>>(
activity,
ConversationActivity::class.java
)
val listItemId = helper.findListItemId(
"My loaded note, actorId:" + data.getMyAccount().actorId
) { item: BaseNoteViewItem<*> ->
(item.author.getActorId() == data.getMyAccount().actorId
&& item.noteStatus == DownloadStatus.LOADED)
}
val noteId = MyQuery.activityIdToLongColumnValue(ActivityTable.NOTE_ID, listItemId)
var logMsg = ("itemId=" + listItemId + ", noteId=" + noteId + " text='"
+ MyQuery.noteIdToStringColumnValue(NoteTable.CONTENT, noteId) + "'")
val invoked = helper.invokeContextMenuAction4ListItemId(
method, listItemId,
NoteContextMenuItem.EDIT, R.id.note_wrapper
)
logMsg += ";" + if (invoked) "" else " failed to invoke Edit menu item,"
Assert.assertTrue(logMsg, invoked)
ActivityTestHelper.closeContextMenu(activity)
val editorView = activity.findViewById<View?>(R.id.note_editor)
ActivityTestHelper.waitViewVisible("$method $logMsg", editorView)
Assert.assertEquals(
"Loaded note should be in DRAFT state on Edit start: $logMsg", DownloadStatus.DRAFT,
getDownloadStatus(noteId)
)
val helper2 = ActivityTestHelper<TimelineActivity<*>>(activity)
helper2.clickMenuItem("$method clicker Discard $logMsg", R.id.discardButton)
ActivityTestHelper.waitViewInvisible("$method $logMsg", editorView)
Assert.assertEquals(
"Loaded note should be unchanged after Discard: $logMsg", DownloadStatus.LOADED,
waitForDownloadStatus(noteId, DownloadStatus.LOADED)
)
}
private fun waitForDownloadStatus(noteId: Long, expected: DownloadStatus): DownloadStatus {
var downloadStatus: DownloadStatus = DownloadStatus.UNKNOWN
for (i in 0..29) {
downloadStatus = getDownloadStatus(noteId)
if (downloadStatus == expected) return downloadStatus
DbUtils.waitMs(this, 100)
}
return downloadStatus
}
private fun getDownloadStatus(noteId: Long): DownloadStatus {
return DownloadStatus.Companion.load(MyQuery.noteIdToLongColumnValue(NoteTable.NOTE_STATUS, noteId))
}
@Test
fun replying() {
val method = "replying"
TestSuite.waitForListLoaded(activity, 2)
val editorView: View = ActivityTestHelper.hideEditorAndSaveDraft<ActivityViewItem>(method, activity)
val helper = ListActivityTestHelper<TimelineActivity<*>>(
activity,
ConversationActivity::class.java
)
val viewItem = helper.findListItem(
"Some others loaded note"
) { item: BaseNoteViewItem<*> ->
(item.author.getActorId() != data.getMyAccount().actorId
&& item.noteStatus == DownloadStatus.LOADED)
} as ActivityViewItem
val listItemId = viewItem.getId()
val noteId = MyQuery.activityIdToLongColumnValue(ActivityTable.NOTE_ID, listItemId)
var logMsg = ("itemId=" + listItemId + ", noteId=" + noteId + " text='"
+ MyQuery.noteIdToStringColumnValue(NoteTable.CONTENT, noteId) + "'")
Assert.assertEquals(logMsg, viewItem.noteViewItem.getId(), noteId)
val invoked = helper.invokeContextMenuAction4ListItemId(
method, listItemId,
NoteContextMenuItem.REPLY, R.id.note_wrapper
)
logMsg += ";" + if (invoked) "" else " failed to invoke Reply menu item,"
Assert.assertTrue(logMsg, invoked)
ActivityTestHelper.closeContextMenu(activity)
ActivityTestHelper.waitViewVisible("$method $logMsg", editorView)
onView(ViewMatchers.withId(R.id.noteBodyEditText))
.check(ViewAssertions.matches(ViewMatchers.withText(CoreMatchers.startsWith("@"))))
EspressoUtils.waitForIdleSync()
val content = "Replying to you during " + DemoData.demoData.testRunUid
val bodyText = editorView.findViewById<EditText?>(R.id.noteBodyEditText)
// Espresso types in the centre, unfortunately, so we need to retype text
onView(ViewMatchers.withId(R.id.noteBodyEditText))
.perform(ReplaceTextAction(bodyText.text.toString().trim { it <= ' ' }
+ " " + content))
EspressoUtils.waitForIdleSync()
ActivityTestHelper.hideEditorAndSaveDraft<ActivityViewItem>("$method Save draft $logMsg", activity)
val draftNoteId: Long = ActivityTestHelper.waitAndGetIdOfStoredNote("$method $logMsg", content)
Assert.assertEquals(
"Saved note should be in DRAFT state: $logMsg", DownloadStatus.DRAFT,
getDownloadStatus(draftNoteId)
)
Assert.assertEquals(
"Wrong id of inReplyTo note of '$content': $logMsg", noteId,
MyQuery.noteIdToLongColumnValue(NoteTable.IN_REPLY_TO_NOTE_ID, draftNoteId)
)
val audience: Audience = fromNoteId(data.getMyAccount().origin, draftNoteId)
Assert.assertTrue(
"Audience of a reply to $viewItem\n $audience",
audience.findSame(viewItem.noteViewItem.author.actor).isSuccess
)
}
companion object {
private val editingStep: AtomicInteger = AtomicInteger()
fun attachImages(test: TimelineActivityTest<ActivityViewItem>, toAdd: Int, toExpect: Int) {
ScreenshotOnFailure.screenshotWrapper(test.activity) {
attachImagesInternal(test, toAdd, toExpect)
}
}
private fun attachImagesInternal(test: TimelineActivityTest<ActivityViewItem>, toAdd: Int, toExpect: Int) {
val method = "attachImages$toAdd"
MyLog.v(test, "$method started")
ActivityTestHelper.hideEditorAndSaveDraft(method, test.activity)
val editorView: View = ActivityTestHelper.openEditor(method, test.activity)
assertTextCleared(test)
EspressoUtils.waitForEditorUnlocked()
val noteName = "A note " + toAdd + " " + test::class.simpleName + " can have a title (name)"
val content = "Note with " + toExpect + " attachment" +
(if (toExpect == 1) "" else "s") + " " +
DemoData.demoData.testRunUid
onView(ViewMatchers.withId(R.id.note_name_edit)).perform(ReplaceTextAction(noteName))
onView(ViewMatchers.withId(R.id.noteBodyEditText)).perform(ReplaceTextAction(content))
onView(ViewMatchers.withId(R.id.note_name_edit)).check(ViewAssertions.matches(ViewMatchers.withText(noteName)))
onView(ViewMatchers.withId(R.id.noteBodyEditText)).check(
ViewAssertions.matches(
ViewMatchers.withText(
content
)
)
)
attachImage(test, editorView, DemoData.demoData.localImageTestUri2)
if (toAdd > 1) {
attachImage(test, editorView, DemoData.demoData.localGifTestUri)
}
val editor = test.activity.getNoteEditor() ?: throw IllegalStateException("No editor")
Assert.assertEquals(
"All image attached " + editor.getData().getAttachedImageFiles(), toExpect.toLong(),
editor.getData().getAttachedImageFiles().list.size.toLong()
)
if (toAdd > 1) {
val mediaFile = editor.getData().getAttachedImageFiles().list[if (toExpect == 1) 0 else 1]
Assert.assertEquals(
"Should be animated $mediaFile",
MyContentType.ANIMATED_IMAGE,
mediaFile.contentType
)
}
onView(ViewMatchers.withId(R.id.noteBodyEditText)).check(ViewAssertions.matches(ViewMatchers.withText("$content ")))
onView(ViewMatchers.withId(R.id.note_name_edit)).check(ViewAssertions.matches(ViewMatchers.withText(noteName)))
ActivityTestHelper.hideEditorAndSaveDraft(method, test.activity)
EspressoUtils.waitForIdleSync()
MyLog.v(test, "$method ended")
}
private fun attachImage(test: TimelineActivityTest<ActivityViewItem>, editorView: View, imageUri: Uri) {
val method = "attachImage"
EspressoUtils.waitForEditorUnlocked()
val helper = ActivityTestHelper<TimelineActivity<*>>(test.activity)
test.activity.setSelectorActivityStub(helper)
helper.clickMenuItem("$method clicker attach_menu_id", R.id.attach_menu_id)
assertNotNull(helper.waitForSelectorStart(method, ActivityRequestCode.ATTACH.id))
test.activity.setSelectorActivityStub(null)
val activityMonitor = test.getInstrumentation()
.addMonitor(HelpActivity::class.java.name, null, false)
val intent1 = Intent(test.activity, HelpActivity::class.java)
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
test.activity.applicationContext.startActivity(intent1)
val selectorActivity = test.getInstrumentation().waitForMonitorWithTimeout(activityMonitor, 25000)
assertTrue(selectorActivity != null)
ActivityTestHelper.waitViewInvisible(method, editorView)
EspressoUtils.waitForEditorUnlocked()
selectorActivity.finish()
EspressoUtils.waitForEditorUnlocked()
MyLog.i(method, "Callback from a selector")
val intent2 = Intent()
intent2.setDataAndType(
imageUri, MyContentType.Companion.uri2MimeType(
test.activity.contentResolver, imageUri,
MyContentType.IMAGE.generalMimeType
)
)
test.activity.runOnUiThread {
test.activity.onActivityResult(
ActivityRequestCode.ATTACH.id,
Activity.RESULT_OK,
intent2
)
}
val editor = test.activity.getNoteEditor() ?: throw IllegalStateException("No editor")
for (attempt in 0..3) {
ActivityTestHelper.waitViewVisible(method, editorView)
// Due to a race the editor may open before this change first.
if (editor.getData().getAttachedImageFiles().forUri(imageUri).isPresent) {
break
}
}
EspressoUtils.waitForEditorUnlocked()
Assert.assertTrue(
"Image attached", editor.getData().getAttachedImageFiles()
.forUri(imageUri).isPresent
)
}
private fun assertTextCleared(test: TimelineActivityTest<ActivityViewItem>) {
val editor = test.activity.getNoteEditor()
Assert.assertTrue("Editor is not null", editor != null)
Assert.assertEquals("Editor data should be cleared",
NoteEditorData.Companion.newEmpty(
test.activity.myContext.accounts.currentAccount
).toTestSummary(),
editor?.getData()?.toTestSummary()
)
}
}
}
| apache-2.0 | 2f5ff25f14e4ec857bfa215f84f7bf96 | 44.955112 | 128 | 0.664261 | 4.899761 | false | true | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/adventure/AdventureConstants.kt | 1 | 569 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.adventure
object AdventureConstants {
const val GROUP_ID = "net.kyori"
const val API_ARTIFACT_ID = "adventure-api"
const val API_MODULE_ID = "net.kyori.adventure"
const val API_SPECIFICATION_TITLE = "net.kyori.adventure"
const val NAMED_TEXT_COLOR_CLASS = "net.kyori.adventure.text.format.NamedTextColor"
const val TEXT_COLOR_CLASS = "net.kyori.adventure.text.format.TextColor"
}
| mit | d67437783347d36ae211e3c279cf8367 | 24.863636 | 87 | 0.71529 | 3.512346 | false | false | false | false |
handstandsam/ShoppingApp | app/src/main/java/com/handstandsam/shoppingapp/features/home/ShoppingAppViewModelFactory.kt | 1 | 1646 | package com.handstandsam.shoppingapp.features.home
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.handstandsam.shoppingapp.cart.ShoppingCart
import com.handstandsam.shoppingapp.features.category.CategoryViewModel
import com.handstandsam.shoppingapp.features.checkout.ShoppingCartViewModel
import com.handstandsam.shoppingapp.repository.CategoryRepo
import com.handstandsam.shoppingapp.repository.ItemRepo
import com.handstandsam.shoppingapp.repository.SessionManager
import kotlinx.coroutines.CoroutineScope
class ShoppingAppViewModelFactory(
private val scope: CoroutineScope,
private val sessionManager: SessionManager,
private val categoryRepo: CategoryRepo,
private val shoppingCart: ShoppingCart,
private val itemRepo: ItemRepo
) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(HomeViewModel::class.java)) {
return HomeViewModel(
scope = scope,
sessionManager = sessionManager,
categoryRepo = categoryRepo
) as T
} else if (modelClass.isAssignableFrom(CategoryViewModel::class.java)) {
return CategoryViewModel(
scope = scope,
itemRepo = itemRepo
) as T
}else if (modelClass.isAssignableFrom(ShoppingCartViewModel::class.java)) {
return ShoppingCartViewModel(
scope = scope,
cart = shoppingCart
) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
} | apache-2.0 | b16e564ffe23a8d583ecd39256c91721 | 40.175 | 83 | 0.710207 | 5.414474 | false | false | false | false |
stfalcon-studio/uaroads_android | app/src/main/java/com/stfalcon/new_uaroads_android/repos/tracks/TracksRepoImpl.kt | 1 | 3124 | /*
* Copyright (c) 2017 stfalcon.com
*
* 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.stfalcon.new_uaroads_android.repos.tracks
import android.content.Context
import android.os.Build
import com.stfalcon.new_uaroads_android.BuildConfig
import com.stfalcon.new_uaroads_android.common.network.services.TracksService
import com.stfalcon.new_uaroads_android.features.record.managers.Point
import com.stfalcon.new_uaroads_android.utils.DataUtils
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
/*
* Created by Anton Bevza on 4/28/17.
*/
class TracksRepoImpl(val service: TracksService, val dataUtils: DataUtils,
val context: Context) : TracksRepo {
override fun sendTrack(userId: String, points: List<Point>, routeId: String,
comment: String, date: String, autoRecord: Int): Completable {
val file = File.createTempFile(System.currentTimeMillis().toString(), null, context.filesDir)
val outputStream = context.openFileOutput(file.name, Context.MODE_PRIVATE)
return Observable.fromIterable(points)
.subscribeOn(Schedulers.io())
.buffer(1000)
.map { outputStream.write(dataUtils.buildString(it).toByteArray()) }
.flatMapCompletable {
val fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file)
val userIdBody = RequestBody.create(MultipartBody.FORM, userId)
val routeIdBody = RequestBody.create(MultipartBody.FORM, routeId)
val commentBody = RequestBody.create(MultipartBody.FORM, comment)
val verBody = RequestBody.create(MultipartBody.FORM, BuildConfig.VERSION_NAME)
val autoRecordBody = RequestBody.create(MultipartBody.FORM, autoRecord.toString())
val partData = MultipartBody.Part.createFormData("data", "file", fileBody)
service.sendTrack(partData, userIdBody, commentBody, verBody, routeIdBody, autoRecordBody)
}
}
override fun sendDeviceInfo(email: String, sensorInfo: String, uid: String): Completable {
return service.sendDeviceInfo(email, Build.DEVICE + " " + Build.MODEL,
"android", BuildConfig.VERSION_NAME, Build.VERSION.SDK_INT.toString(),
sensorInfo, uid)
.subscribeOn(Schedulers.io())
}
} | apache-2.0 | eaae2e7f637f0b76cdc8cd434d7bb4f5 | 47.076923 | 110 | 0.68854 | 4.494964 | false | false | false | false |
saki4510t/libcommon | app/src/main/java/com/serenegiant/libcommon/PermissionFragment.kt | 1 | 7775 | package com.serenegiant.libcommon
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2022 saki [email protected]
*
* 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.
*/
import android.Manifest
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.serenegiant.dialog.RationalDialogV4
import com.serenegiant.system.BuildCheck
import com.serenegiant.system.PermissionUtils
import com.serenegiant.system.PermissionUtils.PermissionCallback
import java.util.*
class PermissionFragment : BaseFragment(), RationalDialogV4.DialogResultListener {
private var mPermissions: PermissionUtils? = null
override fun onAttach(context: Context) {
super.onAttach(context)
// パーミッション要求の準備
mPermissions = PermissionUtils(this, mCallback)
.prepare(this, LOCATION_PERMISSIONS)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_permission, container, false)
}
override fun internalOnResume() {
super.internalOnResume()
if (DEBUG) Log.v(TAG, "internalOnResume:")
requestPermissionsAll()
}
override fun internalOnPause() {
if (DEBUG) Log.v(TAG, "internalOnPause:")
super.internalOnPause()
}
private fun requestPermissionsAll() {
if (DEBUG) Log.v(TAG, "requestPermissionsAll:")
runOnUiThread({
if (!checkPermissionWriteExternalStorage()) {
return@runOnUiThread
}
if (!checkPermissionCamera()) {
return@runOnUiThread
}
if (!checkPermissionAudio()) {
return@runOnUiThread
}
if (DEBUG) Log.v(TAG, "requestPermissionsAll:has all permissions")
})
}
/**
* check permission to access external storage
* and request to show detail dialog to request permission
*
* @return true already have permission to access external storage
*/
private fun checkPermissionWriteExternalStorage(): Boolean {
if (DEBUG) Log.v(TAG, "checkPermissionWriteExternalStorage:")
// API29以降は対象範囲別ストレージ&MediaStoreを使うのでWRITE_EXTERNAL_STORAGEパーミッションは不要
return (BuildCheck.isAPI29()
|| ((mPermissions != null)
&& mPermissions!!.requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, true)))
}
/**
* check permission to access external storage
* and request to show detail dialog to request permission
*
* @return true already have permission to access external storage
*/
private fun checkPermissionCamera(): Boolean {
if (DEBUG) Log.v(TAG, "checkPermissionCamera:")
return ((mPermissions != null)
&& mPermissions!!.requestPermission(Manifest.permission.CAMERA, true))
}
/**
* check permission to record audio
* and request to show detail dialog to request permission
*
* @return true already have permission to record audio
*/
private fun checkPermissionAudio(): Boolean {
if (DEBUG) Log.v(TAG, "checkPermissionAudio:")
return ((mPermissions != null)
&& mPermissions!!.requestPermission(Manifest.permission.RECORD_AUDIO, true))
}
/**
* check permission to access location info
* and request to show detail dialog to request permission
* @return true already have permission to access location
*/
private fun checkPermissionLocation(): Boolean {
return ((mPermissions != null)
&& mPermissions!!.requestPermission(LOCATION_PERMISSIONS, true))
}
private val mCallback: PermissionCallback = object : PermissionCallback {
override fun onPermissionShowRational(permission: String) {
if (DEBUG) Log.v(TAG, "onPermissionShowRational:$permission")
val dialog = RationalDialogV4.showDialog(this@PermissionFragment, permission)
if (dialog == null) {
if (DEBUG) Log.v(TAG, "onPermissionShowRational:" +
"デフォルトのダイアログ表示ができなかったので自前で表示しないといけない," + permission)
if (Manifest.permission.INTERNET == permission) {
RationalDialogV4.showDialog(this@PermissionFragment,
R.string.permission_title,
R.string.permission_network_request,
arrayOf(Manifest.permission.INTERNET))
} else if ((Manifest.permission.ACCESS_FINE_LOCATION == permission)
|| (Manifest.permission.ACCESS_COARSE_LOCATION == permission)) {
RationalDialogV4.showDialog(this@PermissionFragment,
R.string.permission_title,
R.string.permission_location_request,
LOCATION_PERMISSIONS
)
}
}
}
override fun onPermissionShowRational(permissions: Array<String>) {
if (DEBUG) Log.v(TAG, "onPermissionShowRational:" + permissions.contentToString())
// 複数パーミッションの一括要求時はデフォルトのダイアログ表示がないので自前で実装する
if (LOCATION_PERMISSIONS.contentEquals(permissions)) {
RationalDialogV4.showDialog(
this@PermissionFragment,
R.string.permission_title,
R.string.permission_location_request,
LOCATION_PERMISSIONS
)
}
}
override fun onPermissionDenied(permission: String) {
if (DEBUG) Log.v(TAG, "onPermissionDenied:$permission")
// ユーザーがパーミッション要求を拒否したときの処理
requestPermissionsAll()
}
override fun onPermission(permission: String) {
if (DEBUG) Log.v(TAG, "onPermission:$permission")
// ユーザーがパーミッション要求を承認したときの処理
requestPermissionsAll()
}
override fun onPermissionNeverAskAgain(permission: String) {
if (DEBUG) Log.v(TAG, "onPermissionNeverAskAgain:$permission")
// 端末のアプリ設定画面を開くためのボタンを配置した画面へ遷移させる
parentFragmentManager
.beginTransaction()
.addToBackStack(null)
.replace(R.id.container, SettingsLinkFragment.newInstance())
.commit()
}
override fun onPermissionNeverAskAgain(permissions: Array<String>) {
if (DEBUG) Log.v(TAG, "onPermissionNeverAskAgain:" + permissions.contentToString())
// 端末のアプリ設定画面を開くためのボタンを配置した画面へ遷移させる
parentFragmentManager
.beginTransaction()
.addToBackStack(null)
.replace(R.id.container, SettingsLinkFragment.newInstance())
.commit()
}
}
override fun onDialogResult(
dialog: RationalDialogV4,
permissions: Array<String>, result: Boolean) {
if (DEBUG) Log.v(TAG, "onDialogResult:${result}," + permissions.contentToString())
if (result) { // メッセージダイアログでOKを押された時はパーミッション要求する
if (BuildCheck.isMarshmallow()) {
if (mPermissions != null) {
mPermissions!!.requestPermission(permissions, false)
return
}
}
}
requestPermissionsAll()
}
companion object {
private const val DEBUG = true // set false on production
private val TAG = PermissionFragment::class.java.simpleName
private val LOCATION_PERMISSIONS = arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
)
fun newInstance(): PermissionFragment {
val fragment = PermissionFragment()
val args = Bundle()
fragment.arguments = args
return fragment
}
}
} | apache-2.0 | 135411364dbde1379ddfc496462cf160 | 31.410714 | 91 | 0.740598 | 3.739825 | false | false | false | false |
ZieIony/Carbon | samples/src/main/java/tk/zielony/carbonsamples/component/RegisterActivity.kt | 1 | 1689 | package tk.zielony.carbonsamples.component
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import carbon.component.*
import carbon.drawable.VectorDrawable
import carbon.recycler.RowListAdapter
import kotlinx.android.synthetic.main.activity_register.*
import tk.zielony.carbonsamples.R
import tk.zielony.carbonsamples.SampleAnnotation
import tk.zielony.carbonsamples.ThemedActivity
import java.io.Serializable
@SampleAnnotation(layoutId = R.layout.activity_register, titleId = R.string.registerActivity_title)
class RegisterActivity : ThemedActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initToolbar()
val adapter = RowListAdapter<Serializable>().apply {
putFactory(DefaultIconEditTextItem::class.java, { IconEditTextRow(it) })
putFactory(DefaultIconPasswordItem::class.java, { IconPasswordRow(it) })
putFactory(DefaultIconDropDownItem::class.java, { IconDropDownRow<DefaultIconDropDownItem<*>, String>(it) })
}
adapter.items = listOf(
DefaultIconEditTextItem(VectorDrawable(resources, R.raw.profile), "login", ""),
DefaultIconEditTextItem(VectorDrawable(resources, R.raw.email), "email", ""),
DefaultIconPasswordItem(VectorDrawable(resources, R.raw.lock), "password", ""),
DefaultIconPasswordItem(null, "retype password", ""),
DefaultIconDropDownItem(VectorDrawable(resources, R.raw.gender), "sex", arrayOf("Male", "Female"), "Male"))
recycler.layoutManager = LinearLayoutManager(this)
recycler.adapter = adapter
}
} | apache-2.0 | eeff98ee341e4f1c48eb4d723f6e8bfe | 44.675676 | 123 | 0.725281 | 4.717877 | false | false | false | false |
google/private-compute-services | src/com/google/android/as/oss/assets/federatedcompute/PecanLatencyAnalyticsEventPolicy_FederatedCompute.kt | 1 | 2043 | /*
* Copyright 2021 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.policies.federatedcompute
/** Data policy. */
val PecanLatencyAnalyticsEventPolicy_FederatedCompute =
flavoredPolicies(
name = "PecanLatencyAnalyticsEventPolicy_FederatedCompute",
policyType = MonitorOrImproveUserExperienceWithFederatedCompute,
) {
description =
"""
Monitor latency statistics for People and Conversations. Latency statistics will help improve
the performance of People and Conversations infrastructure.
ALLOWED EGRESSES: FederatedCompute.
ALLOWED USAGES: Federated analytics, federated learning.
"""
.trimIndent()
flavors(Flavor.ASI_PROD) { minRoundSize(minRoundSize = 1000, minSecAggRoundSize = 0) }
consentRequiredForCollectionOrStorage(Consent.UsageAndDiagnosticsCheckbox)
presubmitReviewRequired(OwnersApprovalOnly)
checkpointMaxTtlDays(720)
target(PECAN_LATENCY_ANALYTICS_EVENT_GENERATED_DTD, Duration.ofDays(7)) {
retention(StorageMedium.RAM)
retention(StorageMedium.DISK)
"eventId" { rawUsage(UsageType.JOIN) }
"packageName" {
conditionalUsage("top2000PackageNamesWith2000Wau", UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"timestamp" {
conditionalUsage("truncatedToDays", UsageType.ANY)
rawUsage(UsageType.JOIN)
}
"processingTimeMillis" { rawUsage(UsageType.ANY) }
"className" { rawUsage(UsageType.ANY) }
}
}
| apache-2.0 | e78ecc5541585cc4b07943a714cf1d9a | 36.145455 | 99 | 0.729809 | 4.441304 | false | false | false | false |
finn-no/capturandro | library/src/main/java/no/finntech/capturandro/OrientationUtil.kt | 1 | 2578 | package no.finntech.capturandro
import android.content.ContentResolver
import android.net.Uri
import android.provider.MediaStore
import android.util.Log
import androidx.exifinterface.media.ExifInterface
import java.io.File
import java.io.IOException
object OrientationUtil {
@JvmStatic
fun getOrientation(photoUri: Uri, contentResolver: ContentResolver): Int {
val exif = readExif(photoUri, contentResolver)
if (exif != null) {
return getOrientation(exif)
} else {
val projection = arrayOf(MediaStore.Images.ImageColumns.ORIENTATION)
val cursor = contentResolver.query(photoUri, projection, null, null, null)
if (cursor != null) {
if (cursor.moveToFirst() && cursor.columnCount > 0) {
return cursor.getInt(0)
}
cursor.close()
}
}
return ExifInterface.ORIENTATION_UNDEFINED
}
@JvmStatic
fun getOrientation(exif: ExifInterface?): Int {
return exif?.let {
val orientation = it.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED
)
return when (orientation) {
ExifInterface.ORIENTATION_ROTATE_180 -> 180
ExifInterface.ORIENTATION_ROTATE_90 -> 90
ExifInterface.ORIENTATION_ROTATE_270 -> 270
else -> 0
}
} ?: ExifInterface.ORIENTATION_UNDEFINED
}
private fun readExif(photoUri: Uri, contentResolver: ContentResolver): ExifInterface? {
return if (photoUri.scheme == "file") {
readExifFromFile(File(photoUri.toString()))
} else {
readExifFromContent(contentResolver, photoUri)
}
}
@JvmStatic
fun readExifFromFile(file: File): ExifInterface? {
try {
return ExifInterface(file.path)
} catch (e: IOException) {
}
Log.i("Capturandro", "Unable to read exif data from file: ${file.path}")
return null
}
private fun readExifFromContent(contentResolver: ContentResolver, photoUri: Uri): ExifInterface? {
try {
contentResolver.openInputStream(photoUri).use { inputStream ->
if (inputStream != null) {
return ExifInterface(inputStream)
}
}
} catch (e: IOException) {
}
Log.i("Capturandro", "Unable to read exif data from uri: $photoUri")
return null
}
} | apache-2.0 | 8af295841e90db55f0874e0b3a00756d | 32.493506 | 102 | 0.595035 | 4.98646 | false | false | false | false |
marius-m/racer_test | core/src/main/java/lt/markmerkk/app/box2d/BoxProperty.kt | 1 | 817 | package lt.markmerkk.app.box2d
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.physics.box2d.*
/**
* @author mariusmerkevicius
* @since 2016-06-04
*
* Building block for the box2d
*/
class BoxProperty(
val world: World,
val width: Float,
val height: Float,
val position: Vector2
) {
val body: Body
init {
val bodyDef = BodyDef()
bodyDef.position.set(position)
bodyDef.angle = 0f
bodyDef.fixedRotation = true
body = world.createBody(bodyDef)
val fixtureDef = FixtureDef()
val boxShape = PolygonShape()
boxShape.setAsBox(width / 2, height / 2)
fixtureDef.shape = boxShape
fixtureDef.restitution = 0.7f
body.createFixture(fixtureDef)
boxShape.dispose()
}
} | apache-2.0 | f3ba930c6aba5a24cd5f1ad0f6f9b7e7 | 21.108108 | 48 | 0.623011 | 3.747706 | false | false | false | false |
jiaminglu/kotlin-native | runtime/src/main/kotlin/kotlin/Char.kt | 2 | 5220 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin
/**
* Represents a 16-bit Unicode character.
* On the JVM, non-nullable values of this type are represented as values of the primitive type `char`.
*/
public final class Char : Comparable<Char> {
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if its less than other,
* or a positive number if its greater than other.
*/
@SymbolName("Kotlin_Char_compareTo_Char")
external public override fun compareTo(other: Char): Int
/** Adds the other Int value to this value resulting a Char. */
@SymbolName("Kotlin_Char_plus_Int")
external public operator fun plus(other: Int): Char
/** Subtracts the other Char value from this value resulting an Int. */
@SymbolName("Kotlin_Char_minus_Char")
external public operator fun minus(other: Char): Int
/** Subtracts the other Int value from this value resulting a Char. */
@SymbolName("Kotlin_Char_minus_Int")
external public operator fun minus(other: Int): Char
/** Increments this value. */
@SymbolName("Kotlin_Char_inc")
external public operator fun inc(): Char
/** Decrements this value. */
@SymbolName("Kotlin_Char_dec")
external public operator fun dec(): Char
/** Creates a range from this value to the specified [other] value. */
public operator fun rangeTo(other: Char): CharRange {
return CharRange(this, other)
}
/** Returns the value of this character as a `Byte`. */
@SymbolName("Kotlin_Char_toByte")
external public fun toByte(): Byte
/** Returns the value of this character as a `Char`. */
@SymbolName("Kotlin_Char_toChar")
external public fun toChar(): Char
/** Returns the value of this character as a `Short`. */
@SymbolName("Kotlin_Char_toShort")
external public fun toShort(): Short
/** Returns the value of this character as a `Int`. */
@SymbolName("Kotlin_Char_toInt")
external public fun toInt(): Int
/** Returns the value of this character as a `Long`. */
@SymbolName("Kotlin_Char_toLong")
external public fun toLong(): Long
/** Returns the value of this character as a `Float`. */
@SymbolName("Kotlin_Char_toFloat")
external public fun toFloat(): Float
/** Returns the value of this character as a `Double`. */
@SymbolName("Kotlin_Char_toDouble")
external public fun toDouble(): Double
companion object {
/**
* The minimum value of a Unicode high-surrogate code unit.
*/
public const val MIN_HIGH_SURROGATE: Char = '\uD800'
/**
* The maximum value of a Unicode high-surrogate code unit.
*/
public const val MAX_HIGH_SURROGATE: Char = '\uDBFF'
/**
* The minimum value of a Unicode low-surrogate code unit.
*/
public const val MIN_LOW_SURROGATE: Char = '\uDC00'
/**
* The maximum value of a Unicode low-surrogate code unit.
*/
public const val MAX_LOW_SURROGATE: Char = '\uDFFF'
/**
* The minimum value of a Unicode surrogate code unit.
*/
public const val MIN_SURROGATE: Char = MIN_HIGH_SURROGATE
/**
* The maximum value of a Unicode surrogate code unit.
*/
public const val MAX_SURROGATE: Char = MAX_LOW_SURROGATE
/**
* The minimum value of a supplementary code point, `\u0x10000`. Kotlin/Native specific.
*/
public const val MIN_SUPPLEMENTARY_CODE_POINT: Int = 0x10000
/**
* The minimum value of a Unicode code point. Kotlin/Native specific.
*/
public const val MIN_CODE_POINT = 0x000000
/**
* The maximum value of a Unicode code point. Kotlin/Native specific.
*/
public const val MAX_CODE_POINT = 0X10FFFF
/**
* The minimum radix available for conversion to and from strings.
*/
public const val MIN_RADIX: Int = 2
/**
* The minimum radix available for conversion to and from strings.
*/
public const val MAX_RADIX: Int = 36
}
// Konan-specific.
public fun equals(other: Char): Boolean = konan.internal.areEqualByValue(this, other)
public override fun equals(other: Any?): Boolean =
other is Char && konan.internal.areEqualByValue(this, other)
@SymbolName("Kotlin_Char_toString")
external public override fun toString(): String
public override fun hashCode(): Int {
return this.toInt();
}
}
| apache-2.0 | 4595a7dbe8a68e0ae568ebd3c742f877 | 34.27027 | 114 | 0.645977 | 4.368201 | false | false | false | false |
GLodi/GitNav | app/src/main/java/giuliolodi/gitnav/ui/repository/RepoCommitsFragment.kt | 1 | 5361 | /*
* Copyright 2017 GLodi
*
* 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 giuliolodi.gitnav.ui.repository
import android.os.Bundle
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration
import es.dmoral.toasty.Toasty
import giuliolodi.gitnav.R
import giuliolodi.gitnav.ui.adapters.RepoCommitAdapter
import giuliolodi.gitnav.ui.base.BaseFragment
import giuliolodi.gitnav.ui.commit.CommitActivity
import giuliolodi.gitnav.ui.user.UserActivity
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.repo_commits_fragment.*
import org.eclipse.egit.github.core.Commit
import org.eclipse.egit.github.core.RepositoryCommit
import javax.inject.Inject
/**
* Created by giulio on 11/07/2017.
*/
class RepoCommitsFragment : BaseFragment(), RepoCommitsContract.View {
@Inject lateinit var mPresenter: RepoCommitsContract.Presenter<RepoCommitsContract.View>
private var mOwner: String? = null
private var mName: String? = null
companion object {
fun newInstance(owner: String, name: String): RepoCommitsFragment {
val repoCommitsFragment: RepoCommitsFragment = RepoCommitsFragment()
val bundle: Bundle = Bundle()
bundle.putString("owner", owner)
bundle.putString("name", name)
repoCommitsFragment.arguments = bundle
return repoCommitsFragment
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
retainInstance = true
getActivityComponent()?.inject(this)
mOwner = arguments.getString("owner")
mName = arguments.getString("name")
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.repo_commits_fragment, container, false)
}
override fun initLayout(view: View?, savedInstanceState: Bundle?) {
mPresenter.onAttach(this)
val llm = LinearLayoutManager(context)
llm.orientation = LinearLayoutManager.VERTICAL
repo_commits_fragment_rv.layoutManager = llm
repo_commits_fragment_rv.addItemDecoration(HorizontalDividerItemDecoration.Builder(context).showLastDivider().build())
repo_commits_fragment_rv.itemAnimator = DefaultItemAnimator()
repo_commits_fragment_rv.adapter = RepoCommitAdapter()
(repo_commits_fragment_rv.adapter as RepoCommitAdapter).getImageClicks()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { username -> mPresenter.onUserClick(username) }
(repo_commits_fragment_rv.adapter as RepoCommitAdapter).getCommitClicks()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { repoCommit -> mPresenter.onRepoCommitClick(repoCommit) }
mPresenter.subscribe(isNetworkAvailable(), mOwner, mName)
}
override fun showRepoCommitList(repoCommitList: List<RepositoryCommit>) {
(repo_commits_fragment_rv.adapter as RepoCommitAdapter).addRepoCommits(repoCommitList)
}
override fun showLoading() {
repo_commits_fragment_progressbar.visibility = View.VISIBLE
}
override fun hideLoading() {
repo_commits_fragment_progressbar.visibility = View.GONE
}
override fun showNoCommits() {
repo_commits_fragment_nocommits.visibility = View.VISIBLE
}
override fun showError(error: String) {
Toasty.error(context, error, Toast.LENGTH_LONG).show()
}
override fun showNoConnectionError() {
Toasty.warning(context, getString(R.string.network_error), Toast.LENGTH_LONG).show()
}
override fun intentToUserActivity(username: String) {
startActivity(UserActivity.getIntent(context).putExtra("username", username))
activity.overridePendingTransition(0,0)
}
override fun intentToCommitActivity(repoCommit: RepositoryCommit) {
startActivity(CommitActivity.getIntent(context)
.putExtra("owner", mOwner)
.putExtra("name", mName)
.putExtra("sha", repoCommit.sha)
.putExtra("commit_title", repoCommit.commit.message))
activity.overridePendingTransition(0,0)
}
override fun onDestroyView() {
mPresenter.onDetachView()
super.onDestroyView()
}
override fun onDestroy() {
mPresenter.onDetach()
super.onDestroy()
}
} | apache-2.0 | c0acb31a91f6844fb529d3783805b696 | 36.236111 | 126 | 0.714046 | 4.657689 | false | false | false | false |
Bios-Marcel/ServerBrowser | src/main/kotlin/com/msc/serverbrowser/util/basic/FileUtility.kt | 1 | 8734 | package com.msc.serverbrowser.util.basic
import com.msc.serverbrowser.warn
import javafx.application.Platform
import javafx.beans.property.DoubleProperty
import java.io.File
import java.io.File.separator
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.nio.channels.Channels
import java.nio.charset.Charset
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.security.NoSuchAlgorithmException
import java.util.zip.ZipFile
/**
* Util methods for dealing with downloading and unzipping files.
*
* @author oliver
* @author Marcel
* @since 01.07.2017
*/
object FileUtility {
/**
* Downloads a file and saves it to the given location.
*
* @param url the url to isDownload from
* @param outputPath the path where to save the downloaded file
* @return the downloaded file
* @throws IOException if an errors occurs while writing the file or opening the stream
*/
@Throws(IOException::class)
fun downloadFile(url: String, outputPath: String): File {
Channels.newChannel(URL(url).openStream()).use { readableByteChannel ->
FileOutputStream(outputPath).use { fileOutputStream ->
fileOutputStream.channel.transferFrom(readableByteChannel, 0, java.lang.Long.MAX_VALUE)
return File(outputPath)
}
}
}
/**
* Copies a file overwriting the target if existent
*
* @param source source file
* @param target target file/location
* @throws IOException if there was an severe during the copy action
*/
@Throws(IOException::class)
fun copyOverwrite(source: String, target: String) {
Files.newInputStream(Paths.get(source)).use { fileInputStream -> Channels.newChannel(fileInputStream).use { readableByteChannel -> FileOutputStream(target).use { fileOutputStream -> fileOutputStream.channel.transferFrom(readableByteChannel, 0, java.lang.Long.MAX_VALUE) } } }
}
/**
* Downloads a file and saves it at the given location.
*
* @param url the url to isDownload from
* @param outputPath the path where to save the downloaded file
* @param progressProperty a property that will contain the current isDownload process from 0.0 to
* 1.0
* @param fileLength length of the file
* @return the downloaded file
* @throws IOException if an errors occurs while writing the file or opening the stream
*/
@Throws(IOException::class)
fun downloadFile(url: URL, outputPath: String, progressProperty: DoubleProperty, fileLength: Double): File {
url.openStream().use { input ->
Files.newOutputStream(Paths.get(outputPath)).use { fileOutputStream ->
val currentProgress = progressProperty.get().toInt().toDouble()
val buffer = ByteArray(10000)
while (true) {
val length = input.read(buffer).toDouble()
if (length <= 0) {
break
}
/*
* Setting the progress property inside of a run later in order to avoid a crash,
* since this function is usually used inside of a different thread than the ui
* thread.
*/
Platform.runLater {
val additional = length / fileLength * (1.0 - currentProgress)
progressProperty.set(progressProperty.get() + additional)
}
fileOutputStream.write(buffer, 0, length.toInt())
}
return File(outputPath)
}
}
}
/**
* Retrieving the size of a file that lies somewhere on the web. The file size is retrieved via
* the http header. It shall be noted, that this method won't work in all cases.
*
* @param url the files [URL]
* @return the retrieved filesize
* @throws IOException if there was an severe during the web request
*/
@Throws(IOException::class)
fun getOnlineFileSize(url: URL): Int {
var connection: HttpURLConnection? = null
try {
connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "HEAD"
connection.inputStream
return connection.contentLength
} finally {
connection?.disconnect()
}
}
/**
* Unzips a file, placing its contents in the given output location.
*
* @param zipFilePath input zip file
* @param outputLocation zip file output folder
* @throws IOException if there was an severe reading the zip file or writing the unzipped data
*/
@JvmStatic
@Throws(IOException::class)
fun unzip(zipFilePath: String, outputLocation: String) {
// Open the zip file
ZipFile(zipFilePath).use { zipFile ->
val enu = zipFile.entries()
while (enu.hasMoreElements()) {
val zipEntry = enu.nextElement()
val name = zipEntry.name
val outputFile = File(outputLocation + separator + name)
if (name[name.length - 1] == '/') {
outputFile.mkdirs()
continue
}
val parent = outputFile.parentFile
parent?.mkdirs()
// Extract the file
zipFile.getInputStream(zipEntry).use { inputStream ->
Files.newOutputStream(Paths.get(outputFile.toURI())).use { outputStream ->
/*
* The buffer is the max amount of bytes kept in RAM during any given time while
* unzipping. Since most windows disks are aligned to 4096 or 8192, we use a
* multiple of those values for best performance.
*/
val bytes = ByteArray(8192)
while (inputStream.available() > 0) {
val length = inputStream.read(bytes)
outputStream.write(bytes, 0, length)
}
}
}
}
}
}
/**
* Validates a [File] against a SHA-256 checksum.
*
* @param file the file that has to be validated
* @param sha256Checksum the checksum to validate against
* @return true if the file was valid, otherwise false
*/
fun validateFile(file: File, sha256Checksum: String): Boolean {
try {
return HashingUtility.generateChecksum(file.absolutePath).equals(sha256Checksum, ignoreCase = true)
} catch (exception: NoSuchAlgorithmException) {
warn("File invalid: " + file.absolutePath, exception)
return false
} catch (exception: IOException) {
warn("File invalid: " + file.absolutePath, exception)
return false
}
}
/**
* Deletes a given [File]. In case the file is a directory, it will recursively delete all
* its containments. If at any step during the deletion of files an exception is throwing, there
* won't be any rollback, therefore all deleted files will be gone.
*
* @param file the file that is to be deleted
* @return true if successful, otherwise false
*/
fun deleteRecursively(file: File): Boolean {
if (file.isDirectory) {
val files = file.listFiles() ?: return false
for (fileOrFolder in files) {
if (!deleteRecursively(fileOrFolder)) {
return false
}
}
}
return file.delete()
}
/**
* Tries reading a file with all given charsets until it works.
*
* @param path the [Path] to read from
* @param charsets the [Charset]s to try when reading
* @return A [List] of all lines within the file
* @throws IOException if none of the read-attempts was successful
*/
@Throws(IOException::class)
fun readAllLinesTryEncodings(path: Path, vararg charsets: Charset): List<String> {
if (!Files.exists(path)) {
throw FileNotFoundException("The file at $path doesn't exist.")
}
for (charset in charsets) {
try {
return Files.readAllLines(path, charset)
} catch (exception: IOException) {
warn("Error loading $path with encoding $charset")
}
}
throw IOException("Couldn't load file $path using any of the given encodings.")
}
}
| mpl-2.0 | b82888a294bb9e0f923522bb32848d65 | 36.008475 | 283 | 0.601672 | 4.948442 | false | false | false | false |
LWJGL/lwjgl3 | modules/lwjgl/harfbuzz/src/templates/kotlin/harfbuzz/templates/AAT.kt | 1 | 20315 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package harfbuzz.templates
import org.lwjgl.generator.*
import harfbuzz.*
val hb_aat = "AAT".nativeClass(Module.HARFBUZZ, prefix = "HB_ATT", prefixMethod = "hb_att_", binding = HARFBUZZ_BINDING_DELEGATE) {
documentation =
"Native bindings to the Apple Advanced Typography Layout API of the ${url("https://harfbuzz.github.io/", "HarfBuzz")} library."
EnumConstant(
"""
The possible feature types defined for AAT shaping, from Apple ${url(
"https://developer.apple.com/fonts/TrueType-Reference-Manual/RM09/AppendixF.html",
"Font Feature Registry"
)}. ({@code hb_aat_layout_feature_type_t})
""",
"LAYOUT_FEATURE_TYPE_INVALID".enum("", "0xFFFF"),
"LAYOUT_FEATURE_TYPE_ALL_TYPOGRAPHIC".enum("", "0"),
"LAYOUT_FEATURE_TYPE_LIGATURES".enum,
"LAYOUT_FEATURE_TYPE_CURISVE_CONNECTION".enum,
"LAYOUT_FEATURE_TYPE_LETTER_CASE".enum,
"LAYOUT_FEATURE_TYPE_VERTICAL_SUBSTITUTION".enum,
"LAYOUT_FEATURE_TYPE_LINGUISTIC_REARRANGEMENT".enum,
"LAYOUT_FEATURE_TYPE_NUMBER_SPACING".enum,
"LAYOUT_FEATURE_TYPE_SMART_SWASH_TYPE".enum("", "8"),
"LAYOUT_FEATURE_TYPE_DIACRITICS_TYPE".enum,
"LAYOUT_FEATURE_TYPE_VERTICAL_POSITION".enum,
"LAYOUT_FEATURE_TYPE_FRACTIONS".enum,
"LAYOUT_FEATURE_TYPE_OVERLAPPING_CHARACTERS_TYPE".enum("", "13"),
"LAYOUT_FEATURE_TYPE_TYPOGRAPHIC_EXTRAS".enum,
"LAYOUT_FEATURE_TYPE_MATHEMATICAL_EXTRAS".enum,
"LAYOUT_FEATURE_TYPE_ORNAMENT_SETS_TYPE".enum,
"LAYOUT_FEATURE_TYPE_CHARACTER_ALTERNATIVES".enum,
"LAYOUT_FEATURE_TYPE_DESIGN_COMPLEXITY_TYPE".enum,
"LAYOUT_FEATURE_TYPE_STYLE_OPTIONS".enum,
"LAYOUT_FEATURE_TYPE_CHARACTER_SHAPE".enum,
"LAYOUT_FEATURE_TYPE_NUMBER_CASE".enum,
"LAYOUT_FEATURE_TYPE_TEXT_SPACING".enum,
"LAYOUT_FEATURE_TYPE_TRANSLITERATION".enum,
"LAYOUT_FEATURE_TYPE_ANNOTATION_TYPE".enum,
"LAYOUT_FEATURE_TYPE_KANA_SPACING_TYPE".enum,
"LAYOUT_FEATURE_TYPE_IDEOGRAPHIC_SPACING_TYPE".enum,
"LAYOUT_FEATURE_TYPE_UNICODE_DECOMPOSITION_TYPE".enum,
"LAYOUT_FEATURE_TYPE_RUBY_KANA".enum,
"LAYOUT_FEATURE_TYPE_CJK_SYMBOL_ALTERNATIVES_TYPE".enum,
"LAYOUT_FEATURE_TYPE_IDEOGRAPHIC_ALTERNATIVES_TYPE".enum,
"LAYOUT_FEATURE_TYPE_CJK_VERTICAL_ROMAN_PLACEMENT_TYPE".enum,
"LAYOUT_FEATURE_TYPE_ITALIC_CJK_ROMAN".enum,
"LAYOUT_FEATURE_TYPE_CASE_SENSITIVE_LAYOUT".enum,
"LAYOUT_FEATURE_TYPE_ALTERNATE_KANA".enum,
"LAYOUT_FEATURE_TYPE_STYLISTIC_ALTERNATIVES".enum,
"LAYOUT_FEATURE_TYPE_CONTEXTUAL_ALTERNATIVES".enum,
"LAYOUT_FEATURE_TYPE_LOWER_CASE".enum,
"LAYOUT_FEATURE_TYPE_UPPER_CASE".enum,
"LAYOUT_FEATURE_TYPE_LANGUAGE_TAG_TYPE".enum,
"LAYOUT_FEATURE_TYPE_CJK_ROMAN_SPACING_TYPE".enum("", "103")
).noPrefix()
EnumConstant(
"The selectors defined for specifying AAT feature settings. ({@code hb_aat_layout_feature_selector_t})",
"LAYOUT_FEATURE_SELECTOR_INVALID".enum("", "0xFFFF"),
"LAYOUT_FEATURE_SELECTOR_ALL_TYPE_FEATURES_ON".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_ALL_TYPE_FEATURES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_REQUIRED_LIGATURES_ON".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_REQUIRED_LIGATURES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_COMMON_LIGATURES_ON".enum,
"LAYOUT_FEATURE_SELECTOR_COMMON_LIGATURES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_RARE_LIGATURES_ON".enum,
"LAYOUT_FEATURE_SELECTOR_RARE_LIGATURES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_LOGOS_ON".enum,
"LAYOUT_FEATURE_SELECTOR_LOGOS_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_REBUS_PICTURES_ON".enum,
"LAYOUT_FEATURE_SELECTOR_REBUS_PICTURES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_DIPHTHONG_LIGATURES_ON".enum,
"LAYOUT_FEATURE_SELECTOR_DIPHTHONG_LIGATURES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_SQUARED_LIGATURES_ON".enum,
"LAYOUT_FEATURE_SELECTOR_SQUARED_LIGATURES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_ABBREV_SQUARED_LIGATURES_ON".enum,
"LAYOUT_FEATURE_SELECTOR_ABBREV_SQUARED_LIGATURES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_SYMBOL_LIGATURES_ON".enum,
"LAYOUT_FEATURE_SELECTOR_SYMBOL_LIGATURES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_CONTEXTUAL_LIGATURES_ON".enum,
"LAYOUT_FEATURE_SELECTOR_CONTEXTUAL_LIGATURES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_HISTORICAL_LIGATURES_ON".enum,
"LAYOUT_FEATURE_SELECTOR_HISTORICAL_LIGATURES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_UNCONNECTED".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_PARTIALLY_CONNECTED".enum,
"LAYOUT_FEATURE_SELECTOR_CURSIVE".enum,
"LAYOUT_FEATURE_SELECTOR_UPPER_AND_LOWER_CASE".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_ALL_CAPS".enum,
"LAYOUT_FEATURE_SELECTOR_ALL_LOWER_CASE".enum,
"LAYOUT_FEATURE_SELECTOR_SMALL_CAPS".enum,
"LAYOUT_FEATURE_SELECTOR_INITIAL_CAPS".enum,
"LAYOUT_FEATURE_SELECTOR_INITIAL_CAPS_AND_SMALL_CAPS".enum,
"LAYOUT_FEATURE_SELECTOR_SUBSTITUTE_VERTICAL_FORMS_ON".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_SUBSTITUTE_VERTICAL_FORMS_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_LINGUISTIC_REARRANGEMENT_ON".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_LINGUISTIC_REARRANGEMENT_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_MONOSPACED_NUMBERS".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_PROPORTIONAL_NUMBERS".enum,
"LAYOUT_FEATURE_SELECTOR_THIRD_WIDTH_NUMBERS".enum,
"LAYOUT_FEATURE_SELECTOR_QUARTER_WIDTH_NUMBERS".enum,
"LAYOUT_FEATURE_SELECTOR_WORD_INITIAL_SWASHES_ON".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_WORD_INITIAL_SWASHES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_WORD_FINAL_SWASHES_ON".enum,
"LAYOUT_FEATURE_SELECTOR_WORD_FINAL_SWASHES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_LINE_INITIAL_SWASHES_ON".enum,
"LAYOUT_FEATURE_SELECTOR_LINE_INITIAL_SWASHES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_LINE_FINAL_SWASHES_ON".enum,
"LAYOUT_FEATURE_SELECTOR_LINE_FINAL_SWASHES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_NON_FINAL_SWASHES_ON".enum,
"LAYOUT_FEATURE_SELECTOR_NON_FINAL_SWASHES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_SHOW_DIACRITICS".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_HIDE_DIACRITICS".enum,
"LAYOUT_FEATURE_SELECTOR_DECOMPOSE_DIACRITICS".enum,
"LAYOUT_FEATURE_SELECTOR_NORMAL_POSITION".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_SUPERIORS".enum,
"LAYOUT_FEATURE_SELECTOR_INFERIORS".enum,
"LAYOUT_FEATURE_SELECTOR_ORDINALS".enum,
"LAYOUT_FEATURE_SELECTOR_SCIENTIFIC_INFERIORS".enum,
"LAYOUT_FEATURE_SELECTOR_NO_FRACTIONS".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_VERTICAL_FRACTIONS".enum,
"LAYOUT_FEATURE_SELECTOR_DIAGONAL_FRACTIONS".enum,
"LAYOUT_FEATURE_SELECTOR_PREVENT_OVERLAP_ON".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_PREVENT_OVERLAP_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_HYPHENS_TO_EM_DASH_ON".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_HYPHENS_TO_EM_DASH_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_HYPHEN_TO_EN_DASH_ON".enum,
"LAYOUT_FEATURE_SELECTOR_HYPHEN_TO_EN_DASH_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_SLASHED_ZERO_ON".enum,
"LAYOUT_FEATURE_SELECTOR_SLASHED_ZERO_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_FORM_INTERROBANG_ON".enum,
"LAYOUT_FEATURE_SELECTOR_FORM_INTERROBANG_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_SMART_QUOTES_ON".enum,
"LAYOUT_FEATURE_SELECTOR_SMART_QUOTES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_PERIODS_TO_ELLIPSIS_ON".enum,
"LAYOUT_FEATURE_SELECTOR_PERIODS_TO_ELLIPSIS_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_HYPHEN_TO_MINUS_ON".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_HYPHEN_TO_MINUS_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_ASTERISK_TO_MULTIPLY_ON".enum,
"LAYOUT_FEATURE_SELECTOR_ASTERISK_TO_MULTIPLY_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_SLASH_TO_DIVIDE_ON".enum,
"LAYOUT_FEATURE_SELECTOR_SLASH_TO_DIVIDE_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_INEQUALITY_LIGATURES_ON".enum,
"LAYOUT_FEATURE_SELECTOR_INEQUALITY_LIGATURES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_EXPONENTS_ON".enum,
"LAYOUT_FEATURE_SELECTOR_EXPONENTS_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_MATHEMATICAL_GREEK_ON".enum,
"LAYOUT_FEATURE_SELECTOR_MATHEMATICAL_GREEK_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_NO_ORNAMENTS".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_DINGBATS".enum,
"LAYOUT_FEATURE_SELECTOR_PI_CHARACTERS".enum,
"LAYOUT_FEATURE_SELECTOR_FLEURONS".enum,
"LAYOUT_FEATURE_SELECTOR_DECORATIVE_BORDERS".enum,
"LAYOUT_FEATURE_SELECTOR_INTERNATIONAL_SYMBOLS".enum,
"LAYOUT_FEATURE_SELECTOR_MATH_SYMBOLS".enum,
"LAYOUT_FEATURE_SELECTOR_NO_ALTERNATES".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_DESIGN_LEVEL1".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_DESIGN_LEVEL2".enum,
"LAYOUT_FEATURE_SELECTOR_DESIGN_LEVEL3".enum,
"LAYOUT_FEATURE_SELECTOR_DESIGN_LEVEL4".enum,
"LAYOUT_FEATURE_SELECTOR_DESIGN_LEVEL5".enum,
"LAYOUT_FEATURE_SELECTOR_NO_STYLE_OPTIONS".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_DISPLAY_TEXT".enum,
"LAYOUT_FEATURE_SELECTOR_ENGRAVED_TEXT".enum,
"LAYOUT_FEATURE_SELECTOR_ILLUMINATED_CAPS".enum,
"LAYOUT_FEATURE_SELECTOR_TITLING_CAPS".enum,
"LAYOUT_FEATURE_SELECTOR_TALL_CAPS".enum,
"LAYOUT_FEATURE_SELECTOR_TRADITIONAL_CHARACTERS".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_SIMPLIFIED_CHARACTERS".enum,
"LAYOUT_FEATURE_SELECTOR_JIS1978_CHARACTERS".enum,
"LAYOUT_FEATURE_SELECTOR_JIS1983_CHARACTERS".enum,
"LAYOUT_FEATURE_SELECTOR_JIS1990_CHARACTERS".enum,
"LAYOUT_FEATURE_SELECTOR_TRADITIONAL_ALT_ONE".enum,
"LAYOUT_FEATURE_SELECTOR_TRADITIONAL_ALT_TWO".enum,
"LAYOUT_FEATURE_SELECTOR_TRADITIONAL_ALT_THREE".enum,
"LAYOUT_FEATURE_SELECTOR_TRADITIONAL_ALT_FOUR".enum,
"LAYOUT_FEATURE_SELECTOR_TRADITIONAL_ALT_FIVE".enum,
"LAYOUT_FEATURE_SELECTOR_EXPERT_CHARACTERS".enum,
"LAYOUT_FEATURE_SELECTOR_JIS2004_CHARACTERS".enum,
"LAYOUT_FEATURE_SELECTOR_HOJO_CHARACTERS".enum,
"LAYOUT_FEATURE_SELECTOR_NLCCHARACTERS".enum,
"LAYOUT_FEATURE_SELECTOR_TRADITIONAL_NAMES_CHARACTERS".enum,
"LAYOUT_FEATURE_SELECTOR_LOWER_CASE_NUMBERS".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_UPPER_CASE_NUMBERS".enum,
"LAYOUT_FEATURE_SELECTOR_PROPORTIONAL_TEXT".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_MONOSPACED_TEXT".enum,
"LAYOUT_FEATURE_SELECTOR_HALF_WIDTH_TEXT".enum,
"LAYOUT_FEATURE_SELECTOR_THIRD_WIDTH_TEXT".enum,
"LAYOUT_FEATURE_SELECTOR_QUARTER_WIDTH_TEXT".enum,
"LAYOUT_FEATURE_SELECTOR_ALT_PROPORTIONAL_TEXT".enum,
"LAYOUT_FEATURE_SELECTOR_ALT_HALF_WIDTH_TEXT".enum,
"LAYOUT_FEATURE_SELECTOR_NO_TRANSLITERATION".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_HANJA_TO_HANGUL".enum,
"LAYOUT_FEATURE_SELECTOR_HIRAGANA_TO_KATAKANA".enum,
"LAYOUT_FEATURE_SELECTOR_KATAKANA_TO_HIRAGANA".enum,
"LAYOUT_FEATURE_SELECTOR_KANA_TO_ROMANIZATION".enum,
"LAYOUT_FEATURE_SELECTOR_ROMANIZATION_TO_HIRAGANA".enum,
"LAYOUT_FEATURE_SELECTOR_ROMANIZATION_TO_KATAKANA".enum,
"LAYOUT_FEATURE_SELECTOR_HANJA_TO_HANGUL_ALT_ONE".enum,
"LAYOUT_FEATURE_SELECTOR_HANJA_TO_HANGUL_ALT_TWO".enum,
"LAYOUT_FEATURE_SELECTOR_HANJA_TO_HANGUL_ALT_THREE".enum,
"LAYOUT_FEATURE_SELECTOR_NO_ANNOTATION".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_BOX_ANNOTATION".enum,
"LAYOUT_FEATURE_SELECTOR_ROUNDED_BOX_ANNOTATION".enum,
"LAYOUT_FEATURE_SELECTOR_CIRCLE_ANNOTATION".enum,
"LAYOUT_FEATURE_SELECTOR_INVERTED_CIRCLE_ANNOTATION".enum,
"LAYOUT_FEATURE_SELECTOR_PARENTHESIS_ANNOTATION".enum,
"LAYOUT_FEATURE_SELECTOR_PERIOD_ANNOTATION".enum,
"LAYOUT_FEATURE_SELECTOR_ROMAN_NUMERAL_ANNOTATION".enum,
"LAYOUT_FEATURE_SELECTOR_DIAMOND_ANNOTATION".enum,
"LAYOUT_FEATURE_SELECTOR_INVERTED_BOX_ANNOTATION".enum,
"LAYOUT_FEATURE_SELECTOR_INVERTED_ROUNDED_BOX_ANNOTATION".enum,
"LAYOUT_FEATURE_SELECTOR_FULL_WIDTH_KANA".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_PROPORTIONAL_KANA".enum,
"LAYOUT_FEATURE_SELECTOR_FULL_WIDTH_IDEOGRAPHS".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_PROPORTIONAL_IDEOGRAPHS".enum,
"LAYOUT_FEATURE_SELECTOR_HALF_WIDTH_IDEOGRAPHS".enum,
"LAYOUT_FEATURE_SELECTOR_CANONICAL_COMPOSITION_ON".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_CANONICAL_COMPOSITION_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_COMPATIBILITY_COMPOSITION_ON".enum,
"LAYOUT_FEATURE_SELECTOR_COMPATIBILITY_COMPOSITION_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_TRANSCODING_COMPOSITION_ON".enum,
"LAYOUT_FEATURE_SELECTOR_TRANSCODING_COMPOSITION_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_NO_RUBY_KANA".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_RUBY_KANA".enum,
"LAYOUT_FEATURE_SELECTOR_RUBY_KANA_ON".enum,
"LAYOUT_FEATURE_SELECTOR_RUBY_KANA_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_NO_CJK_SYMBOL_ALTERNATIVES".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_CJK_SYMBOL_ALT_ONE".enum,
"LAYOUT_FEATURE_SELECTOR_CJK_SYMBOL_ALT_TWO".enum,
"LAYOUT_FEATURE_SELECTOR_CJK_SYMBOL_ALT_THREE".enum,
"LAYOUT_FEATURE_SELECTOR_CJK_SYMBOL_ALT_FOUR".enum,
"LAYOUT_FEATURE_SELECTOR_CJK_SYMBOL_ALT_FIVE".enum,
"LAYOUT_FEATURE_SELECTOR_NO_IDEOGRAPHIC_ALTERNATIVES".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_IDEOGRAPHIC_ALT_ONE".enum,
"LAYOUT_FEATURE_SELECTOR_IDEOGRAPHIC_ALT_TWO".enum,
"LAYOUT_FEATURE_SELECTOR_IDEOGRAPHIC_ALT_THREE".enum,
"LAYOUT_FEATURE_SELECTOR_IDEOGRAPHIC_ALT_FOUR".enum,
"LAYOUT_FEATURE_SELECTOR_IDEOGRAPHIC_ALT_FIVE".enum,
"LAYOUT_FEATURE_SELECTOR_CJK_VERTICAL_ROMAN_CENTERED".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_CJK_VERTICAL_ROMAN_HBASELINE".enum,
"LAYOUT_FEATURE_SELECTOR_NO_CJK_ITALIC_ROMAN".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_CJK_ITALIC_ROMAN".enum,
"LAYOUT_FEATURE_SELECTOR_CJK_ITALIC_ROMAN_ON".enum,
"LAYOUT_FEATURE_SELECTOR_CJK_ITALIC_ROMAN_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_CASE_SENSITIVE_LAYOUT_ON".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_CASE_SENSITIVE_LAYOUT_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_CASE_SENSITIVE_SPACING_ON".enum,
"LAYOUT_FEATURE_SELECTOR_CASE_SENSITIVE_SPACING_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_ALTERNATE_HORIZ_KANA_ON".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_ALTERNATE_HORIZ_KANA_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_ALTERNATE_VERT_KANA_ON".enum,
"LAYOUT_FEATURE_SELECTOR_ALTERNATE_VERT_KANA_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_NO_STYLISTIC_ALTERNATES".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_ONE_ON".enum("", "2"),
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_ONE_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_TWO_ON".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_TWO_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_THREE_ON".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_THREE_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_FOUR_ON".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_FOUR_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_FIVE_ON".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_FIVE_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_SIX_ON".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_SIX_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_SEVEN_ON".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_SEVEN_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_EIGHT_ON".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_EIGHT_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_NINE_ON".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_NINE_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_TEN_ON".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_TEN_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_ELEVEN_ON".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_ELEVEN_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_TWELVE_ON".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_TWELVE_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_THIRTEEN_ON".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_THIRTEEN_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_FOURTEEN_ON".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_FOURTEEN_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_FIFTEEN_ON".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_FIFTEEN_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_SIXTEEN_ON".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_SIXTEEN_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_SEVENTEEN_ON".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_SEVENTEEN_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_EIGHTEEN_ON".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_EIGHTEEN_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_NINETEEN_ON".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_NINETEEN_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_TWENTY_ON".enum,
"LAYOUT_FEATURE_SELECTOR_STYLISTIC_ALT_TWENTY_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_CONTEXTUAL_ALTERNATES_ON".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_CONTEXTUAL_ALTERNATES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_SWASH_ALTERNATES_ON".enum,
"LAYOUT_FEATURE_SELECTOR_SWASH_ALTERNATES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_CONTEXTUAL_SWASH_ALTERNATES_ON".enum,
"LAYOUT_FEATURE_SELECTOR_CONTEXTUAL_SWASH_ALTERNATES_OFF".enum,
"LAYOUT_FEATURE_SELECTOR_DEFAULT_LOWER_CASE".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_LOWER_CASE_SMALL_CAPS".enum,
"LAYOUT_FEATURE_SELECTOR_LOWER_CASE_PETITE_CAPS".enum,
"LAYOUT_FEATURE_SELECTOR_DEFAULT_UPPER_CASE".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_UPPER_CASE_SMALL_CAPS".enum,
"LAYOUT_FEATURE_SELECTOR_UPPER_CASE_PETITE_CAPS".enum,
"LAYOUT_FEATURE_SELECTOR_HALF_WIDTH_CJK_ROMAN".enum("", "0"),
"LAYOUT_FEATURE_SELECTOR_PROPORTIONAL_CJK_ROMAN".enum,
"LAYOUT_FEATURE_SELECTOR_DEFAULT_CJK_ROMAN".enum,
"LAYOUT_FEATURE_SELECTOR_FULL_WIDTH_CJK_ROMAN".enum
)
IntConstant(
"""
Used when getting or setting AAT feature selectors.
Indicates that there is no selector index corresponding to the selector of interest.
""",
"LAYOUT_NO_SELECTOR_INDEX".."0xFFFF"
)
unsigned_int(
"layout_get_feature_types",
"",
hb_face_t.p("face", ""),
unsigned_int("start_offset", ""),
AutoSize("features")..Check(1)..nullable..unsigned_int.p("feature_count", ""),
nullable..hb_aat_layout_feature_type_t.p("features", "")
)
hb_ot_name_id_t(
"layout_feature_type_get_name_id",
"",
hb_face_t.p("face", ""),
hb_aat_layout_feature_type_t("feature_type", "")
)
unsigned_int(
"layout_feature_type_get_selector_infos",
"",
hb_face_t.p("face", ""),
hb_aat_layout_feature_type_t("feature_type", ""),
unsigned_int("start_offset", ""),
AutoSize("selectors")..Check(1)..nullable..unsigned_int.p("selector_count", ""),
nullable..hb_aat_layout_feature_selector_info_t.p("selectors", ""),
Check(1)..nullable..unsigned_int.p("default_index", "")
)
hb_bool_t(
"layout_has_substitution",
"",
hb_face_t.p("face", "")
)
hb_bool_t(
"layout_has_positioning",
"",
hb_face_t.p("face", "")
)
hb_bool_t(
"layout_has_tracking",
"",
hb_face_t.p("face", "")
)
} | bsd-3-clause | 199e5504ceccf82e1e3c80ffc4b79614 | 47.602871 | 135 | 0.67177 | 3.367871 | false | false | false | false |
exponentjs/exponent | packages/expo-image-loader/android/src/main/java/expo/modules/imageloader/ImageLoaderModule.kt | 2 | 3759 | package expo.modules.imageloader
import android.content.Context
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.os.AsyncTask
import androidx.annotation.NonNull
import androidx.annotation.Nullable
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.facebook.common.references.CloseableReference
import com.facebook.datasource.DataSource
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber
import com.facebook.imagepipeline.image.CloseableImage
import com.facebook.imagepipeline.request.ImageRequest
import expo.modules.interfaces.imageloader.ImageLoaderInterface
import expo.modules.core.interfaces.InternalModule
import java.util.concurrent.ExecutionException
import java.util.concurrent.Future
class ImageLoaderModule(val context: Context) : InternalModule, ImageLoaderInterface {
override fun getExportedInterfaces(): List<Class<*>>? {
return listOf(ImageLoaderInterface::class.java)
}
override fun loadImageForDisplayFromURL(url: String): Future<Bitmap> {
val future = SimpleSettableFuture<Bitmap>()
loadImageForDisplayFromURL(
url,
object : ImageLoaderInterface.ResultListener {
override fun onSuccess(bitmap: Bitmap) = future.set(bitmap)
override fun onFailure(@Nullable cause: Throwable?) = future.setException(ExecutionException(cause))
}
)
return future
}
override fun loadImageForDisplayFromURL(url: String, resultListener: ImageLoaderInterface.ResultListener) {
val imageRequest = ImageRequest.fromUri(url)
val imagePipeline = Fresco.getImagePipeline()
val dataSource = imagePipeline.fetchDecodedImage(imageRequest, context)
dataSource.subscribe(
object : BaseBitmapDataSubscriber() {
override fun onNewResultImpl(bitmap: Bitmap?) {
bitmap?.let {
resultListener.onSuccess(bitmap)
return
}
resultListener.onFailure(Exception("Loaded bitmap is null"))
}
override fun onFailureImpl(@NonNull dataSource: DataSource<CloseableReference<CloseableImage>>) {
resultListener.onFailure(dataSource.failureCause)
}
},
AsyncTask.THREAD_POOL_EXECUTOR
)
}
override fun loadImageForManipulationFromURL(@NonNull url: String): Future<Bitmap> {
val future = SimpleSettableFuture<Bitmap>()
loadImageForManipulationFromURL(
url,
object : ImageLoaderInterface.ResultListener {
override fun onSuccess(bitmap: Bitmap) = future.set(bitmap)
override fun onFailure(@NonNull cause: Throwable?) = future.setException(ExecutionException(cause))
}
)
return future
}
override fun loadImageForManipulationFromURL(url: String, resultListener: ImageLoaderInterface.ResultListener) {
val normalizedUrl = normalizeAssetsUrl(url)
Glide.with(context)
.asBitmap()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.load(normalizedUrl)
.into(object : SimpleTarget<Bitmap>() {
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
resultListener.onSuccess(resource)
}
override fun onLoadFailed(errorDrawable: Drawable?) {
resultListener.onFailure(Exception("Loading bitmap failed"))
}
})
}
private fun normalizeAssetsUrl(url: String): String {
var actualUrl = url
if (url.startsWith("asset:///")) {
actualUrl = "file:///android_asset/" + url.split("/").last()
}
return actualUrl
}
}
| bsd-3-clause | 965a90c02a6678b2db842863e3413ba6 | 34.462264 | 114 | 0.739824 | 5.052419 | false | false | false | false |
Adventech/sabbath-school-android-2 | features/lessons/src/main/java/com/cryart/sabbathschool/lessons/ui/quarterlies/model/QuarterlySpec.kt | 1 | 2999 | /*
* Copyright (c) 2022. Adventech <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.cryart.sabbathschool.lessons.ui.quarterlies.model
import androidx.compose.runtime.Immutable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import app.ss.design.compose.theme.parse
import app.ss.models.QuarterlyGroup
import app.ss.models.SSQuarterly
@Immutable
data class QuarterlySpec(
val id: String,
val title: String,
val date: String,
val cover: String,
val color: Color,
val index: String,
val isPlaceholder: Boolean = false,
val type: Type = Type.NORMAL,
val onClick: () -> Unit = {}
) {
enum class Type {
NORMAL,
LARGE;
fun width(largeScreen: Boolean): Dp = when {
largeScreen && this == NORMAL -> 150.dp
largeScreen && this == LARGE -> 198.dp
this == NORMAL -> 100.dp
this == LARGE -> 148.dp
else -> Dp.Unspecified
}
fun height(largeScreen: Boolean): Dp = when {
largeScreen && this == NORMAL -> 198.dp
largeScreen && this == LARGE -> 276.dp
this == NORMAL -> 146.dp
this == LARGE -> 226.dp
else -> Dp.Unspecified
}
}
}
internal fun SSQuarterly.spec(
type: QuarterlySpec.Type = QuarterlySpec.Type.NORMAL,
onClick: () -> Unit = {}
): QuarterlySpec = QuarterlySpec(
id = id,
title = title,
date = human_date,
cover = cover,
color = Color.parse(color_primary),
index = index,
isPlaceholder = isPlaceholder,
type,
onClick
)
internal fun QuarterlyGroup.spec() = QuarterlyGroupSpec(
name, order
)
internal fun QuarterlyGroupSpec.group() = QuarterlyGroup(
name, order
)
@Immutable
internal data class GroupedQuarterliesSpec(
val title: String,
val items: List<QuarterlySpec>,
val lastIndex: Boolean
)
| mit | 94223babd984f50fc75297b2d7aab91b | 30.568421 | 80 | 0.67856 | 4.206171 | false | false | false | false |
ouattararomuald/kotlin-experiment | src/main/kotlin/com/ouattararomuald/datastructures/Queue.kt | 1 | 2149 | /*
* Copyright 2017 Romuald OUATTARA
*
* 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.ouattararomuald.datastructures
/** Simple First-In-First-Out (FIFO) data structures. */
internal class Queue<T> {
/** Checks whether or not the queue is empty. */
val isEmpty: Boolean
get() = size == 0
/** Returns the number of items currently in the queue. */
var size: Int = 0
private set
/** First item of the queue. */
private var head: Node<T>? = null
/** Last item of the queue. */
private var tail: Node<T>? = null
/**
* Returns but does not retrieve the first item of the queue.
*
* @return The first item of the queue.
* @exception UnderflowException If the queue is empty.
*/
fun peek(): T? {
if (isEmpty) {
throw UnderflowException()
} else {
return head?.data
}
}
/**
* Retrieves and returns the first item of the queue.
*
* @return The first item of the queue.
* @exception UnderflowException If the queue is empty.
*/
fun dequeue(): T? {
if (isEmpty) {
throw UnderflowException()
} else {
val data = head?.data
head = head?.next
if (head == null) {
tail = null
}
size--
return data
}
}
/**
* Adds the given item to the end of the queue.
* @param data Item to add in the queue.
*/
fun enqueue(data: T) {
val newNode = Node(data, null)
if (isEmpty) {
head = newNode
tail = head
} else {
tail!!.next = newNode
tail = newNode
}
size++
}
private data class Node<T>(val data: T, var next: Node<T>?)
} | apache-2.0 | 6e6026b6552e46f7925fad21c8902af9 | 24.294118 | 76 | 0.624942 | 3.810284 | false | false | false | false |
Unpublished/AmazeFileManager | app/src/main/java/com/amaze/filemanager/filesystem/MakeFileOperation.kt | 2 | 4203 | /*
* Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager 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.amaze.filemanager.filesystem
import android.content.Context
import android.os.Build
import android.util.Log
import com.amaze.filemanager.ui.icons.MimeTypes
import com.amaze.filemanager.utils.AppConstants
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStreamWriter
// This object is here to not polute the global namespace
// All functions must be static
object MakeFileOperation {
val LOG = "MakeFileOperation"
/**
* Get a temp file.
*
* @param file The base file for which to create a temp file.
* @return The temp file.
*/
@JvmStatic
fun getTempFile(file: File, context: Context): File {
val extDir = context.getExternalFilesDir(null)
return File(extDir, file.name)
}
@JvmStatic
fun mkfile(file: File?, context: Context): Boolean {
if (file == null) return false
if (file.exists()) {
// nothing to create.
return !file.isDirectory
}
// Try the normal way
try {
if (file.createNewFile()) {
return true
}
} catch (e: IOException) {
e.printStackTrace()
}
// Try with Storage Access Framework.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP &&
ExternalSdCardOperation.isOnExtSdCard(file, context)
) {
val document = ExternalSdCardOperation.getDocumentFile(file.parentFile, true, context)
// getDocumentFile implicitly creates the directory.
return try {
(
document?.createFile(
MimeTypes.getMimeType(file.path, file.isDirectory), file.name
)
!= null
)
} catch (e: UnsupportedOperationException) {
e.printStackTrace()
false
}
}
return if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
MediaStoreHack.mkfile(context, file)
} else false
}
@JvmStatic
fun mktextfile(data: String?, path: String?, fileName: String): Boolean {
val f = File(
path,
"$fileName${AppConstants.NEW_FILE_DELIMITER}${AppConstants.NEW_FILE_EXTENSION_TXT}"
)
var out: FileOutputStream? = null
var outputWriter: OutputStreamWriter? = null
return try {
if (f.createNewFile()) {
out = FileOutputStream(f, false)
outputWriter = OutputStreamWriter(out)
outputWriter.write(data)
true
} else {
false
}
} catch (io: IOException) {
Log.e(LOG, "Error writing file contents", io)
false
} finally {
try {
if (outputWriter != null) {
outputWriter.flush()
outputWriter.close()
}
if (out != null) {
out.flush()
out.close()
}
} catch (e: IOException) {
Log.e(LOG, "Error closing file output stream", e)
}
}
}
}
| gpl-3.0 | 44df5a52abdc7ae4ddf5dc661865b6dc | 32.624 | 107 | 0.583393 | 4.67 | false | false | false | false |
ksmirenko/cards-toefl | app/src/main/java/io/github/ksmirenko/toeflcards/layout/ModuleListFragment.kt | 1 | 3660 | package io.github.ksmirenko.toeflcards.layout
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CursorAdapter
import android.widget.ListView
import android.widget.Toast
import io.github.ksmirenko.toeflcards.R
import io.github.ksmirenko.toeflcards.ToeflCardsDatabaseProvider
import io.github.ksmirenko.toeflcards.adapters.ModuleCursorAdapter
import kotlinx.android.synthetic.main.fragment_modules_list.view.*
import nl.komponents.kovenant.task
import nl.komponents.kovenant.ui.successUi
/**
* Fragment for category screen, contains a dictionary button and list of modules.
* @author Kirill Smirenko
*/
class ModuleListFragment : Fragment() {
private lateinit var moduleListView: ListView
private var modulesAdapter: CursorAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
ToeflCardsDatabaseProvider.initIfNull(context!!)
// load the list of modules in background thread
val db = ToeflCardsDatabaseProvider.db
task {
db.getModules()
} successUi {
cursor ->
modulesAdapter = ModuleCursorAdapter(context!!, cursor)
setupListAdapter()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.fragment_modules_list, container, false)
moduleListView = rootView.listview_modules
// filling the list with modules and setting up onClick
if (modulesAdapter != null) {
setupListAdapter()
}
return rootView
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RES_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
val unansweredCount = data!!.getIntExtra(RES_ARG_CARDS_UNANSWERED_CNT, -1)
val totalCount = data.getIntExtra(RES_ARG_CARDS_TOTAL_CNT, -1)
val unanswered = data.getStringExtra(RES_ARG_CARDS_UNANSWERED)
val moduleId = data.getLongExtra(RES_ARG_MODULE_ID, -1)
val db = ToeflCardsDatabaseProvider.db
task {
db.updateModuleProgress(moduleId, unanswered)
} successUi {
Toast.makeText(
context,
getString(R.string.cards_answered) + " "
+ (totalCount - unansweredCount) + "/" + totalCount,
Toast.LENGTH_SHORT).show()
}
}
}
private fun setupListAdapter() {
with(moduleListView) {
adapter = modulesAdapter
setOnItemClickListener { parent, view, position, id ->
// launch card view activity
val detailIntent = Intent(context, CardActivity::class.java)
detailIntent.putExtra(CardActivity.ARG_MODULE_ID, id)
startActivityForResult(detailIntent, RES_REQUEST_CODE)
}
}
}
companion object {
// Request code and arguments for CardActivity result
private const val RES_REQUEST_CODE = 1
const val RES_ARG_CARDS_UNANSWERED = "CARDS_UNANSWERED"
const val RES_ARG_CARDS_UNANSWERED_CNT = "CARDS_UNANSWERED_CNT"
const val RES_ARG_CARDS_TOTAL_CNT = "CARDS_TOTAL_CNT"
const val RES_ARG_MODULE_ID = "MODULE_ID"
}
}
| apache-2.0 | d92c70f43a684e0402e28e9211a52205 | 37.125 | 116 | 0.662568 | 4.463415 | false | false | false | false |
Rin-Da/UCSY-News | app/src/main/java/io/github/rin_da/ucsynews/presentation/home/view/AppBarHome.kt | 1 | 1224 | package io.github.rin_da.ucsynews.presentation.home.view
import android.content.Context
import android.support.v7.widget.Toolbar
import android.view.View
import io.github.rin_da.ucsynews.R
import org.jetbrains.anko.*
import org.jetbrains.anko.appcompat.v7.toolbar
import org.jetbrains.anko.design.appBarLayout
import org.jetbrains.anko.design.coordinatorLayout
/**
* Created by user on 12/15/16.
*/
class AppBarHome : AnkoComponent<Context> {
lateinit var tb: Toolbar
get
override fun createView(ui: AnkoContext<Context>): View {
with(ui) {
coordinatorLayout {
lparams(width = matchParent, height = matchParent)
fitsSystemWindows = true
appBarLayout(theme = R.style.LoginTheme_AppBarOverlay) {
tb = toolbar {
backgroundColor = R.color.colorPrimary
popupTheme = R.style.LoginTheme_PopupOverlay
}.lparams(width = matchParent, height = context.resources.getDimension(R.dimen.abc_action_bar_default_height_material).toInt())
}.lparams(height = wrapContent, width = matchParent)
}
}
return ui.view
}
} | mit | 1ac3bd0700315c5be840946100efe88e | 32.108108 | 147 | 0.647876 | 4.450909 | false | false | false | false |
Maccimo/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/data/PackageSearchProjectService.kt | 2 | 16248 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* 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.
******************************************************************************/
@file:Suppress("DEPRECATION")
package com.jetbrains.packagesearch.intellij.plugin.data
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.openapi.application.readAction
import com.intellij.openapi.components.Service
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiManager
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.PluginEnvironment
import com.jetbrains.packagesearch.intellij.plugin.api.PackageSearchApiClient
import com.jetbrains.packagesearch.intellij.plugin.api.ServerURLs
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.PackageSearchToolWindowFactory
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ModuleModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackagesToUpgrade
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ProjectDataProvider
import com.jetbrains.packagesearch.intellij.plugin.util.BackgroundLoadingBarController
import com.jetbrains.packagesearch.intellij.plugin.util.TraceInfo
import com.jetbrains.packagesearch.intellij.plugin.util.batchAtIntervals
import com.jetbrains.packagesearch.intellij.plugin.util.catchAndLog
import com.jetbrains.packagesearch.intellij.plugin.util.coroutineModuleTransformers
import com.jetbrains.packagesearch.intellij.plugin.util.filesChangedEventFlow
import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope
import com.jetbrains.packagesearch.intellij.plugin.util.logTrace
import com.jetbrains.packagesearch.intellij.plugin.util.mapLatestTimedWithLoading
import com.jetbrains.packagesearch.intellij.plugin.util.modifiedBy
import com.jetbrains.packagesearch.intellij.plugin.util.moduleChangesSignalFlow
import com.jetbrains.packagesearch.intellij.plugin.util.moduleTransformers
import com.jetbrains.packagesearch.intellij.plugin.util.nativeModulesChangesFlow
import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectCachesService
import com.jetbrains.packagesearch.intellij.plugin.util.packageVersionNormalizer
import com.jetbrains.packagesearch.intellij.plugin.util.parallelMap
import com.jetbrains.packagesearch.intellij.plugin.util.parallelUpdatedKeys
import com.jetbrains.packagesearch.intellij.plugin.util.replayOnSignals
import com.jetbrains.packagesearch.intellij.plugin.util.showBackgroundLoadingBar
import com.jetbrains.packagesearch.intellij.plugin.util.throttle
import com.jetbrains.packagesearch.intellij.plugin.util.timer
import com.jetbrains.packagesearch.intellij.plugin.util.toolWindowManagerFlow
import com.jetbrains.packagesearch.intellij.plugin.util.trustedProjectFlow
import com.jetbrains.packagesearch.intellij.plugin.util.whileLoading
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.combineTransform
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.take
import kotlinx.serialization.json.Json
import kotlin.time.Duration
import kotlin.time.seconds
@Service(Service.Level.PROJECT)
internal class PackageSearchProjectService(private val project: Project) {
private val retryFromErrorChannel = Channel<Unit>()
private val restartChannel = Channel<Unit>()
val dataProvider = ProjectDataProvider(
PackageSearchApiClient(ServerURLs.base),
project.packageSearchProjectCachesService.installedDependencyCache
)
private val projectModulesLoadingFlow = MutableStateFlow(false)
private val knownRepositoriesLoadingFlow = MutableStateFlow(false)
private val moduleModelsLoadingFlow = MutableStateFlow(false)
private val allInstalledKnownRepositoriesLoadingFlow = MutableStateFlow(false)
private val installedPackagesStep1LoadingFlow = MutableStateFlow(false)
private val installedPackagesStep2LoadingFlow = MutableStateFlow(false)
private val installedPackagesDifferenceLoadingFlow = MutableStateFlow(false)
private val packageUpgradesLoadingFlow = MutableStateFlow(false)
private val availableUpgradesLoadingFlow = MutableStateFlow(false)
val canShowLoadingBar = MutableStateFlow(false)
private val operationExecutedChannel = Channel<List<ProjectModule>>()
private val json = Json { prettyPrint = true }
private val cacheDirectory = project.packageSearchProjectCachesService.projectCacheDirectory.resolve("installedDependencies")
val isLoadingFlow = combineTransform(
projectModulesLoadingFlow,
knownRepositoriesLoadingFlow,
moduleModelsLoadingFlow,
allInstalledKnownRepositoriesLoadingFlow,
installedPackagesStep1LoadingFlow,
installedPackagesStep2LoadingFlow,
installedPackagesDifferenceLoadingFlow,
packageUpgradesLoadingFlow
) { booleans -> emit(booleans.any { it }) }
.stateIn(project.lifecycleScope, SharingStarted.Eagerly, false)
private val projectModulesSharedFlow = project.trustedProjectFlow.flatMapLatest { isProjectTrusted ->
if (isProjectTrusted) project.nativeModulesChangesFlow else flowOf(emptyList())
}
.replayOnSignals(
retryFromErrorChannel.receiveAsFlow().throttle(10.seconds),
project.moduleChangesSignalFlow,
restartChannel.receiveAsFlow()
)
.mapLatestTimedWithLoading("projectModulesSharedFlow", projectModulesLoadingFlow) { modules ->
val moduleTransformations = project.moduleTransformers.map { transformer ->
async { readAction { runCatching { transformer.transformModules(project, modules) } }.getOrThrow() }
}
val coroutinesModulesTransformations = project.coroutineModuleTransformers
.map { async { it.transformModules(project, modules) } }
.awaitAll()
.flatten()
moduleTransformations.awaitAll().flatten() + coroutinesModulesTransformations
}
.catchAndLog(
context = "${this::class.qualifiedName}#projectModulesSharedFlow",
message = "Error while elaborating latest project modules",
fallbackValue = emptyList(),
retryChannel = retryFromErrorChannel
)
.shareIn(project.lifecycleScope, SharingStarted.Eagerly)
val projectModulesStateFlow = projectModulesSharedFlow.stateIn(project.lifecycleScope, SharingStarted.Eagerly, emptyList())
val isAvailable
get() = projectModulesStateFlow.value.isNotEmpty()
private val knownRepositoriesFlow = timer(Duration.hours(1))
.mapLatestTimedWithLoading("knownRepositoriesFlow", knownRepositoriesLoadingFlow) { dataProvider.fetchKnownRepositories() }
.catchAndLog(
context = "${this::class.qualifiedName}#knownRepositoriesFlow",
message = "Error while refreshing known repositories",
fallbackValue = emptyList()
)
.stateIn(project.lifecycleScope, SharingStarted.Eagerly, emptyList())
private val buildFileChangesFlow = combine(
projectModulesSharedFlow,
project.filesChangedEventFlow.map { it.mapNotNull { it.file } }
) { modules, changedBuildFiles -> modules.filter { it.buildFile in changedBuildFiles } }
.shareIn(project.lifecycleScope, SharingStarted.Eagerly)
private val projectModulesChangesFlow = merge(
buildFileChangesFlow.filter { it.isNotEmpty() },
operationExecutedChannel.consumeAsFlow()
)
.batchAtIntervals(1.seconds)
.map { it.flatMap { it }.distinct() }
.catchAndLog(
context = "${this::class.qualifiedName}#projectModulesChangesFlow",
message = "Error while checking Modules changes",
fallbackValue = emptyList()
)
.shareIn(project.lifecycleScope, SharingStarted.Eagerly)
val moduleModelsStateFlow = projectModulesSharedFlow
.mapLatestTimedWithLoading(
loggingContext = "moduleModelsStateFlow",
loadingFlow = moduleModelsLoadingFlow
) { projectModules ->
projectModules.parallelMap { it to ModuleModel(it) }.toMap()
}
.modifiedBy(projectModulesChangesFlow) { repositories, changedModules ->
repositories.parallelUpdatedKeys(changedModules) { ModuleModel(it) }
}
.map { it.values.toList() }
.catchAndLog(
context = "${this::class.qualifiedName}#moduleModelsStateFlow",
message = "Error while evaluating modules models",
fallbackValue = emptyList(),
retryChannel = retryFromErrorChannel
)
.stateIn(project.lifecycleScope, SharingStarted.Eagerly, emptyList())
val allInstalledKnownRepositoriesStateFlow =
combine(moduleModelsStateFlow, knownRepositoriesFlow) { moduleModels, repos -> moduleModels to repos }
.mapLatestTimedWithLoading(
loggingContext = "allInstalledKnownRepositoriesFlow",
loadingFlow = allInstalledKnownRepositoriesLoadingFlow
) { (moduleModels, repos) ->
allKnownRepositoryModels(moduleModels, repos)
}
.catchAndLog(
context = "${this::class.qualifiedName}#allInstalledKnownRepositoriesFlow",
message = "Error while evaluating installed repositories",
fallbackValue = KnownRepositories.All.EMPTY
)
.stateIn(project.lifecycleScope, SharingStarted.Eagerly, KnownRepositories.All.EMPTY)
val dependenciesByModuleStateFlow = projectModulesSharedFlow
.mapLatestTimedWithLoading("installedPackagesStep1LoadingFlow", installedPackagesStep1LoadingFlow) {
fetchProjectDependencies(it, cacheDirectory, json)
}
.modifiedBy(projectModulesChangesFlow) { installed, changedModules ->
val (result, time) = installedPackagesDifferenceLoadingFlow.whileLoading {
installed.parallelUpdatedKeys(changedModules) { it.installedDependencies(cacheDirectory, json) }
}
logTrace("installedPackagesStep1LoadingFlow") {
"Took ${time} to process diffs for ${changedModules.size} module" + if (changedModules.size > 1) "s" else ""
}
result
}
.catchAndLog(
context = "${this::class.qualifiedName}#dependenciesByModuleStateFlow",
message = "Error while evaluating installed dependencies",
fallbackValue = emptyMap(),
retryChannel = retryFromErrorChannel
)
.stateIn(project.lifecycleScope, SharingStarted.Eagerly, emptyMap())
val installedPackagesStateFlow = dependenciesByModuleStateFlow
.mapLatestTimedWithLoading("installedPackagesStep2LoadingFlow", installedPackagesStep2LoadingFlow) {
installedPackages(
it,
project,
dataProvider,
TraceInfo(TraceInfo.TraceSource.INIT)
)
}
.catchAndLog(
context = "${this::class.qualifiedName}#installedPackagesStateFlow",
message = "Error while evaluating installed packages",
fallbackValue = emptyList(),
retryChannel = retryFromErrorChannel
)
.stateIn(project.lifecycleScope, SharingStarted.Eagerly, emptyList())
val packageUpgradesStateFlow = combine(
installedPackagesStateFlow,
moduleModelsStateFlow,
knownRepositoriesFlow
) { installedPackages, moduleModels, repos ->
coroutineScope {
availableUpgradesLoadingFlow.whileLoading {
val allKnownRepos = allKnownRepositoryModels(moduleModels, repos)
val nativeModulesMap = moduleModels.associateBy { it.projectModule }
val getUpgrades: suspend (Boolean) -> PackagesToUpgrade = {
computePackageUpgrades(installedPackages, it, packageVersionNormalizer, allKnownRepos, nativeModulesMap)
}
val stableUpdates = async { getUpgrades(true) }
val allUpdates = async { getUpgrades(false) }
PackageUpgradeCandidates(stableUpdates.await(), allUpdates.await())
}.value
}
}
.catchAndLog(
context = "${this::class.qualifiedName}#packageUpgradesStateFlow",
message = "Error while evaluating packages upgrade candidates",
fallbackValue = PackageUpgradeCandidates.EMPTY,
retryChannel = retryFromErrorChannel
)
.stateIn(project.lifecycleScope, SharingStarted.Eagerly, PackageUpgradeCandidates.EMPTY)
init {
// allows rerunning PKGS inspections on already opened files
// when the data is finally available or changes for PackageUpdateInspection
// or when a build file changes
packageUpgradesStateFlow.throttle(5.seconds)
.map { projectModulesStateFlow.value.map { it.buildFile.path }.toSet() }
.filter { it.isNotEmpty() }
.flatMapLatest { knownBuildFiles ->
FileEditorManager.getInstance(project).openFiles
.filter { it.path in knownBuildFiles }.asFlow()
}
.mapNotNull { readAction { PsiManager.getInstance(project).findFile(it) } }
.onEach { DaemonCodeAnalyzer.getInstance(project).restart(it) }
.launchIn(project.lifecycleScope)
var controller: BackgroundLoadingBarController? = null
project.toolWindowManagerFlow
.filter { it.id == PackageSearchToolWindowFactory.ToolWindowId }
.take(1)
.onEach { canShowLoadingBar.emit(true) }
.launchIn(project.lifecycleScope)
if (PluginEnvironment.isNonModalLoadingEnabled) {
canShowLoadingBar.filter { it }
.flatMapLatest { isLoadingFlow }
.throttle(1.seconds)
.onEach { controller?.clear() }
.filter { it }
.onEach {
controller = showBackgroundLoadingBar(
project,
PackageSearchBundle.message("toolwindow.stripe.Dependencies"),
PackageSearchBundle.message("packagesearch.ui.loading")
)
}.launchIn(project.lifecycleScope)
}
}
fun notifyOperationExecuted(successes: List<ProjectModule>) {
operationExecutedChannel.trySend(successes)
}
suspend fun restart() {
restartChannel.send(Unit)
}
}
| apache-2.0 | 406dc1d8c7d0bf4fb53abdbfb9eaf051 | 47.646707 | 131 | 0.718673 | 5.850918 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/framework/JavaRuntimeLibraryDescription.kt | 2 | 1960 | // 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.framework
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.libraries.LibraryKind
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.KotlinJvmBundle
import org.jetbrains.kotlin.idea.compiler.configuration.Kotlin2JvmCompilerArgumentsHolder
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinPluginLayout
import org.jetbrains.kotlin.idea.configuration.KotlinJavaModuleConfigurator
import org.jetbrains.kotlin.idea.versions.getDefaultJvmTarget
/**
* @param project null when project doesn't exist yet (called from project wizard)
*/
class JavaRuntimeLibraryDescription(project: Project?) : CustomLibraryDescriptorWithDeferredConfig(
project,
KotlinJavaModuleConfigurator.NAME,
LIBRARY_NAME,
KOTLIN_JAVA_RUNTIME_KIND,
SUITABLE_LIBRARY_KINDS
) {
override fun configureKotlinSettings(project: Project, sdk: Sdk?) {
val defaultJvmTarget = getDefaultJvmTarget(sdk, KotlinPluginLayout.ideCompilerVersion)
if (defaultJvmTarget != null) {
Kotlin2JvmCompilerArgumentsHolder.getInstance(project).update {
jvmTarget = defaultJvmTarget.description
}
}
}
companion object {
val KOTLIN_JAVA_RUNTIME_KIND: LibraryKind = LibraryKind.create("kotlin-java-runtime")
const val LIBRARY_NAME = "KotlinJavaRuntime"
val JAVA_RUNTIME_LIBRARY_CREATION
@Nls
get() = KotlinJvmBundle.message("java.runtime.library.creation")
val DIALOG_TITLE
@Nls
get() = KotlinJvmBundle.message("create.kotlin.java.runtime.library")
val SUITABLE_LIBRARY_KINDS: Set<LibraryKind> = setOf(KOTLIN_JAVA_RUNTIME_KIND)
}
}
| apache-2.0 | 7edd31fc8f92fa9a6e21663b7f57ba59 | 40.702128 | 158 | 0.746429 | 4.590164 | false | true | false | false |
r-ralph/Quartz | compiler/src/main/kotlin/ms/ralph/quartz/compiler/util/Extension.kt | 1 | 1727 | /*
* Copyright 2016 Ralph
*
* 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 ms.ralph.quartz.compiler.util
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.ParameterSpec
import javax.annotation.processing.Messager
import javax.lang.model.element.Element
import javax.lang.model.util.Elements
import javax.tools.Diagnostic
// Element
fun Element.getPackageName(elements: Elements): String =
elements.getPackageOf(this).qualifiedName.toString()
fun List<Element>.mapToParameterSpec(): List<ParameterSpec> =
map { ParameterSpec.builder(ClassName.get(it.asType()), it.simpleName.toString()).build() }
// Messager
fun Messager.note(text: String) = printMessage(Diagnostic.Kind.NOTE, text)
fun Messager.warn(text: String) = printMessage(Diagnostic.Kind.WARNING, text)
fun Messager.error(text: String) = printMessage(Diagnostic.Kind.ERROR, text)
fun Messager.other(text: String) = printMessage(Diagnostic.Kind.OTHER, text)
fun String.upperCase(i: Int): String {
var str = ""
if (i != 0) {
str = substring(0, i - 1)
}
str += toCharArray()[i].toUpperCase()
if (i != length - 1) {
str += substring(i + 1, length)
}
return str
} | apache-2.0 | 9d8033b4d5a94bfa89fa41639c9a1cfe | 31 | 99 | 0.725536 | 3.829268 | false | false | false | false |
pyamsoft/pydroid | bootstrap/src/main/java/com/pyamsoft/pydroid/bootstrap/version/VersionInteractorNetwork.kt | 1 | 1940 | /*
* Copyright 2022 Peter Kenji Yamanaka
*
* 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.pyamsoft.pydroid.bootstrap.version
import com.pyamsoft.pydroid.core.Enforcer
import com.pyamsoft.pydroid.core.Logger
import com.pyamsoft.pydroid.core.ResultWrapper
import com.pyamsoft.pydroid.util.ifNotCancellation
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
internal class VersionInteractorNetwork
internal constructor(
private val updater: AppUpdater,
) : VersionInteractor {
override suspend fun watchForDownloadComplete(onDownloadCompleted: () -> Unit) =
withContext(context = Dispatchers.IO) {
Enforcer.assertOffMainThread()
return@withContext updater.watchForDownloadComplete(onDownloadCompleted)
}
override suspend fun completeUpdate() =
withContext(context = Dispatchers.Main) {
Enforcer.assertOnMainThread()
Logger.d("GOING DOWN FOR UPDATE")
updater.complete()
}
override suspend fun checkVersion(): ResultWrapper<AppUpdateLauncher> =
withContext(context = Dispatchers.IO) {
Enforcer.assertOffMainThread()
return@withContext try {
ResultWrapper.success(updater.checkForUpdate())
} catch (e: Throwable) {
e.ifNotCancellation {
Logger.e(e, "Failed to check for updates")
ResultWrapper.failure(e)
}
}
}
}
| apache-2.0 | 54308e5de840960cd44e2c6d91b35ee1 | 31.881356 | 82 | 0.720103 | 4.608076 | false | false | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/presentation/SystemLinkHandler.kt | 1 | 5916 | package forpdateam.ru.forpda.presentation
import android.app.DownloadManager
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import android.net.Uri
import android.os.Build
import android.os.Environment
import androidx.appcompat.app.AlertDialog
import android.util.Log
import android.widget.Toast
import com.yandex.metrica.YandexMetrica
import forpdateam.ru.forpda.App
import forpdateam.ru.forpda.R
import forpdateam.ru.forpda.common.MimeTypeUtil
import forpdateam.ru.forpda.common.Utils
import forpdateam.ru.forpda.entity.common.AuthState
import forpdateam.ru.forpda.model.AuthHolder
import forpdateam.ru.forpda.model.data.remote.api.NetworkRequest
import forpdateam.ru.forpda.model.preferences.MainPreferencesHolder
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
class SystemLinkHandler(
private val context: Context,
private val mainPreferencesHolder: MainPreferencesHolder,
private val router: TabRouter,
private val authHolder: AuthHolder
) : ISystemLinkHandler {
override fun handle(url: String) {
try {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(FLAG_ACTIVITY_NEW_TASK)
context.startActivity(Intent.createChooser(intent, context.getString(R.string.open_with)).addFlags(FLAG_ACTIVITY_NEW_TASK))
} catch (e: ActivityNotFoundException) {
YandexMetrica.reportError(e.message.orEmpty(), e)
//ACRA.getErrorReporter().handleException(e)
}
}
override fun handleDownload(url: String, inputFileName: String?) {
val fileName = Utils.getFileNameFromUrl(url) ?: url
val activity = App.getActivity()
if (activity != null) {
AlertDialog.Builder(activity)
.setMessage(String.format(activity.getString(R.string.load_file), fileName))
.setPositiveButton(activity.getString(R.string.ok)) { dialog, which -> redirectDownload(fileName, url) }
.setNegativeButton(activity.getString(R.string.cancel), null)
.show()
} else {
redirectDownload(fileName, url)
}
}
private fun redirectDownload(fileName: String, url: String) {
if (!authHolder.get().isAuth()) {
App.getActivity()?.also { activity ->
Utils.showNeedAuthDialog(activity)
}
return
}
Toast.makeText(context, String.format(context.getString(R.string.perform_request_link), fileName), Toast.LENGTH_SHORT).show()
val disposable = Observable
.fromCallable {
val request = NetworkRequest.Builder().url(url).withoutBody().build()
App.get().Di().webClient.request(request)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ response ->
if (response.url == null) {
Toast.makeText(App.getContext(), R.string.error_occurred, Toast.LENGTH_SHORT).show()
return@subscribe
}
try {
val activity = App.getActivity()
val downloadUrl = response.redirect.run {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
replace("https", "http")
} else {
this
}
}
if (!mainPreferencesHolder.getSystemDownloader() || activity == null) {
externalDownloader(downloadUrl)
} else {
val checkAction = {
try {
systemDownloader(fileName, downloadUrl)
} catch (exception: Exception) {
Toast.makeText(context, R.string.perform_loading_error, Toast.LENGTH_SHORT).show()
externalDownloader(downloadUrl)
}
}
App.get().checkStoragePermission(checkAction, activity)
}
} catch (ex: Exception) {
YandexMetrica.reportError(ex.message.orEmpty(), ex)
//ACRA.getErrorReporter().handleException(ex)
}
}, {
it.printStackTrace()
Toast.makeText(context, R.string.error_occurred, Toast.LENGTH_SHORT).show()
})
}
private fun systemDownloader(fileName: String, url: String) {
val dm = App.getContext().getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val request = DownloadManager.Request(Uri.parse(url))
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName)
request.setMimeType(MimeTypeUtil.getType(fileName))
dm.enqueue(request)
}
private fun externalDownloader(url: String) {
try {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(FLAG_ACTIVITY_NEW_TASK)
context.startActivity(Intent.createChooser(intent, context.getString(R.string.load_with)).addFlags(FLAG_ACTIVITY_NEW_TASK))
} catch (e: ActivityNotFoundException) {
YandexMetrica.reportError(e.message.orEmpty(), e)
//ACRA.getErrorReporter().handleException(e)
}
}
} | gpl-3.0 | ff704425baadf109488f4358f8c10496 | 44.868217 | 135 | 0.59787 | 5.078112 | false | false | false | false |
edwardharks/Aircraft-Recognition | redux/src/main/kotlin/redux/Redux.kt | 1 | 1546 | package redux
import rx.Emitter
import rx.Observable
import rx.Subscription
interface Action
typealias Unsubscriber = () -> Unit
class Store<S>(private val reducer: (S, Action) -> S, initialState: S) {
var state: S = initialState
private set
private val listeners = HashSet<(S) -> Unit>()
private var isDispatching = false
private val lock = Object()
fun dispatch(action: Action) {
synchronized(lock) {
if (isDispatching) {
throw IllegalStateException("Reducers may not dispatch actions.")
}
try {
isDispatching = true
state = reducer(state, action)
} finally {
isDispatching = false
}
}
for (listener in listeners) {
listener(state)
}
}
fun subscribe(listener: (S) -> Unit): Unsubscriber {
listeners.add(listener)
listener(state)
return {
listeners.remove(listener)
}
}
companion object {
fun <S> create(reducer: (S, Action) -> S, initialState: S): Store<S> =
Store(reducer, initialState)
}
}
fun <S> Store<S>.dispatch(actions: Observable<out Action>): Subscription {
return actions.subscribe { dispatch(it) }
}
fun <S> Store<S>.observe(): Observable<out S> {
return Observable.create({ emitter ->
val unsubscriber = subscribe { emitter.onNext(it) }
emitter.setCancellation(unsubscriber)
}, Emitter.BackpressureMode.DROP)
}
| gpl-3.0 | f4734756a4fbb4368270a967a20e2dcc | 23.935484 | 81 | 0.586028 | 4.404558 | false | false | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/ui/activities/updatechecker/SimpleUpdateChecker.kt | 1 | 3257 | package forpdateam.ru.forpda.ui.activities.updatechecker
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import forpdateam.ru.forpda.App
import forpdateam.ru.forpda.BuildConfig
import forpdateam.ru.forpda.R
import forpdateam.ru.forpda.entity.remote.checker.UpdateData
import forpdateam.ru.forpda.model.repository.checker.CheckerRepository
import io.reactivex.disposables.CompositeDisposable
/**
* Created by radiationx on 23.07.17.
*/
class SimpleUpdateChecker(
private val checkerRepository: CheckerRepository
) {
private val compositeDisposable = CompositeDisposable()
fun checkUpdate() {
compositeDisposable.add(
checkerRepository
.checkUpdate(true)
.subscribe({
showUpdateData(it)
}, {
it.printStackTrace()
})
)
}
fun destroy() {
compositeDisposable.clear()
}
@SuppressLint("NewApi")
private fun showUpdateData(update: UpdateData) {
val currentVersionCode = BuildConfig.VERSION_CODE
if (update.code > currentVersionCode) {
val context: Context = App.getContext()
val channelId = "forpda_channel_updates"
val channelName = context.getString(R.string.updater_notification_title)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT)
val manager = context.getSystemService(NotificationManager::class.java)
manager?.createNotificationChannel(channel)
}
val mBuilder = NotificationCompat.Builder(context, channelId)
val mNotificationManager = NotificationManagerCompat.from(context)
mBuilder.setSmallIcon(R.drawable.ic_notify_mention)
mBuilder.setContentTitle(context.getString(R.string.updater_notification_title))
mBuilder.setContentText(String.format(context.getString(R.string.updater_notification_content_VerName), update.name))
mBuilder.setChannelId(channelId)
val notifyIntent = Intent(context, UpdateCheckerActivity::class.java)
notifyIntent.action = Intent.ACTION_VIEW
val notifyPendingIntent = PendingIntent.getActivity(context, 0, notifyIntent, 0)
mBuilder.setContentIntent(notifyPendingIntent)
mBuilder.setAutoCancel(true)
mBuilder.priority = NotificationCompat.PRIORITY_DEFAULT
mBuilder.setCategory(NotificationCompat.CATEGORY_EVENT)
var defaults = 0
//defaults = defaults or NotificationCompat.DEFAULT_SOUND
defaults = defaults or NotificationCompat.DEFAULT_VIBRATE
mBuilder.setDefaults(defaults)
mNotificationManager.notify(update.code, mBuilder.build())
}
}
}
| gpl-3.0 | 21247f2be144870a575f2aec22b92b38 | 35.188889 | 129 | 0.682223 | 5.348112 | false | false | false | false |
byu-oit/android-byu-suite-v2 | support/src/main/java/edu/byu/support/fragment/CamerasGridFragment.kt | 2 | 8795 | package edu.byu.support.fragment
import android.graphics.Bitmap
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable
import android.os.Bundle
import android.os.CountDownTimer
import android.support.v4.content.ContextCompat
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.animation.GlideAnimation
import com.bumptech.glide.request.target.SimpleTarget
import edu.byu.support.ByuClickListener
import edu.byu.support.ByuRecyclerView
import edu.byu.support.ByuViewHolder
import edu.byu.support.R
import edu.byu.support.activity.ByuActivity
import edu.byu.support.adapter.ByuRecyclerAdapter
import edu.byu.support.client.cameraFeed.ByuCameraFeedClient
import edu.byu.support.client.cameraFeed.model.CameraFeed
import edu.byu.support.retrofit.ByuSuccessCallback
import kotlinx.android.synthetic.main.camera_feed_cardview.view.*
import kotlinx.android.synthetic.main.camera_feed_layout.view.*
import kotlinx.android.synthetic.main.cameras_fragment_recycler_layout.*
import kotlinx.android.synthetic.main.cameras_fragment_recycler_layout.view.*
import retrofit2.Call
import retrofit2.Response
import java.lang.Exception
/**
* Created by ahill18 on 2/28/18.
*/
class CamerasGridFragment: ByuRecyclerViewFragment() {
var expandedCameraView: View? = null
companion object {
const val NUM_COLUMNS = 2
const val GRID_VIEW_SWITCHER_POSITION = 1
const val CAMERA_FILTER = "camera_filter"
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
val view = super.onCreateView(inflater, container, R.layout.cameras_fragment_recycler_layout)
recyclerView.layoutManager = GridLayoutManager(activity, NUM_COLUMNS)
recyclerView.removeHorizontalLineDivider()
expandedCameraView = view.camera_feed_full_screen_frame
val layerDrawable = expandedCameraView?.camera_view_progress_bar?.progressDrawable as LayerDrawable
val drawable = layerDrawable.getDrawable(2)
activity?.let { drawable.setColorFilter(ContextCompat.getColor(it, R.color.colorAccent), PorterDuff.Mode.SRC_IN) }
setAdapter(FeedRecyclerAdapter())
recyclerView.addOnScrollListener(object: RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
updateShowingImages()
}
})
loadCameras()
return view
}
private fun loadCameras() {
enqueueCall(ByuCameraFeedClient().getApi(activity).availableCameraFeeds, object: ByuSuccessCallback<List<CameraFeed>>(activity as? ByuActivity) {
override fun onSuccess(call: Call<List<CameraFeed>>, response: Response<List<CameraFeed>>) {
//Filter out unneeded camera streams through CAMERA_FILTER variable
val list: List<CameraFeed>? = response.body()?.filter { feed ->
arguments?.getString(CAMERA_FILTER) == null || feed.category == arguments?.getString(CAMERA_FILTER)
}
recyclerView.adapter.setList(ArrayList<RefreshTimerImage>())
list?.let {
for ((index, feed) in it.withIndex()) {
recyclerView.adapter.list.add(RefreshTimerImage(feed, index))
}
}
view?.loading_grid_view_switcher?.displayedChild = GRID_VIEW_SWITCHER_POSITION
recyclerView.adapter.notifyDataSetChanged()
}
})
}
fun updateShowingImages() {
val first = (recyclerView.layoutManager as GridLayoutManager).findFirstVisibleItemPosition()
val last = (recyclerView.layoutManager as GridLayoutManager).findLastVisibleItemPosition()
//Check if any of the visible views are waiting to be updated
if ((recyclerView as ByuRecyclerView).adapter.list.size > 0) {
for (feed: Any in recyclerView.adapter.list.subList(first, last + 1)) {
if (feed is RefreshTimerImage && feed.waitingToLoad) {
feed.loadImage()
}
}
}
}
inner class RefreshTimerImage(val feed: CameraFeed, val index: Int) {
private var timer: CountDownTimer? = null
var bitmap: Bitmap? = null
var viewIsShowing = false
var initialLoad = false
var millisecondsLeft = (feed.refreshInterval * 1000).toLong()
var waitingToLoad = false
fun resumeTimer() {
timer?.cancel()
timer = object: CountDownTimer(millisecondsLeft, 100L) {
override fun onFinish() {
loadImage()
millisecondsLeft = (feed.refreshInterval * 1000).toLong()
}
override fun onTick(millisecondsLeft: Long) {
[email protected] = millisecondsLeft
val progress = ((millisecondsLeft.toDouble() / (feed.refreshInterval * 1000).toDouble()) * 100).toInt()
recyclerView?.layoutManager?.findViewByPosition(index)?.camera_card_view_frame_layout?.camera_view_progress_bar?.progress = progress
if (viewIsShowing) {
expandedCameraView?.camera_view_progress_bar?.progress = progress
}
}
}
timer?.start()
}
fun stopTimer() {
timer?.cancel()
}
fun loadImage() {
//Glide is used here because it handles recycling the bitmaps and prevents memory leaks
//Only load image if it is currently visible to the user
if ((recyclerView?.layoutManager as GridLayoutManager).findFirstVisibleItemPosition() <= index
&& (recyclerView?.layoutManager as GridLayoutManager).findLastVisibleItemPosition() >= index
&& userVisibleHint) {
Glide.with(activity)
.load(feed.location)
.asBitmap()
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(object: SimpleTarget<Bitmap>() {
override fun onResourceReady(resource: Bitmap?, glideAnimation: GlideAnimation<in Bitmap>?) {
if (viewIsShowing) {
expandedCameraView?.camera_view_image?.setImageBitmap(resource)
}
bitmap = resource
recyclerView.adapter.notifyItemChanged(index)
resumeTimer()
waitingToLoad = false
}
override fun onLoadFailed(e: Exception?, errorDrawable: Drawable?) {
//If it fails to load just restart timer with current image and try again when timer finishes
resumeTimer()
}
})
} else {
waitingToLoad = true
}
}
}
inner class FeedRecyclerAdapter: ByuRecyclerAdapter<RefreshTimerImage>(emptyList()) {
inner class ViewHolder(itemView: View): ByuViewHolder<RefreshTimerImage>(itemView) {
private val loadingBar: ProgressBar = itemView.camera_card_view_loading_bar
val textView: TextView = itemView.camera_card_view_frame_layout.camera_view_text
val image: ImageView = itemView.camera_card_view_frame_layout.camera_view_image
override fun bind(data: RefreshTimerImage, listener: ByuClickListener<RefreshTimerImage>?) {
super.bind(data, listener)
textView.text = data.feed.name
image.setImageBitmap(data.bitmap)
image.scaleType = ImageView.ScaleType.CENTER_CROP
//If the bitmap isn't null, hide the card view loading bar
data.bitmap?.let { loadingBar.visibility = View.GONE }
if (!data.initialLoad) {
data.loadImage()
data.initialLoad = true
}
itemView.setOnClickListener {
//Show expanded view
expandedCameraView?.camera_view_image?.setImageBitmap(data.bitmap)
expandedCameraView?.camera_view_text?.text = data.feed.name
expandedCameraView?.camera_view_image?.layoutParams?.height = ViewGroup.LayoutParams.WRAP_CONTENT
expandedCameraView?.visibility = View.VISIBLE
data.viewIsShowing = true
camera_feed_full_screen?.setOnClickListener {
//Hide expanded view
expandedCameraView?.visibility = View.GONE
data.viewIsShowing = false
}
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ByuViewHolder<RefreshTimerImage> {
val view = LayoutInflater.from(parent.context).inflate(R.layout.camera_feed_cardview, parent, false)
val displayFeed = LayoutInflater.from(parent.context).inflate(R.layout.camera_feed_layout, parent, false)
val layerDrawable = displayFeed.camera_view_progress_bar?.progressDrawable as LayerDrawable
val drawable = layerDrawable.getDrawable(2)
activity?.let { drawable.setColorFilter(ContextCompat.getColor(it, R.color.colorAccent), PorterDuff.Mode.SRC_IN) }
view.camera_card_view_frame_layout.addView(displayFeed)
return ViewHolder(view)
}
}
override fun onDestroy() {
super.onDestroy()
if (recyclerView.adapter.list is List<*>) {
for (feed: Any in recyclerView.adapter.list) {
if (feed is RefreshTimerImage) {
feed.stopTimer()
}
}
}
}
} | apache-2.0 | 32e594d16b5f44209b2dc3fef3ebc50f | 34.611336 | 147 | 0.74747 | 4.00866 | false | false | false | false |
GunoH/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/execution/target/GradleServerClasspathInferer.kt | 9 | 5460 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.gradle.execution.target
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.util.io.URLUtil.urlToFile
import org.gradle.api.GradleException
import org.gradle.internal.classloader.ClassLoaderUtils
import org.gradle.internal.classloader.ClasspathUtil
import org.gradle.internal.impldep.com.google.common.collect.MapMaker
import org.gradle.internal.impldep.com.google.common.io.ByteStreams
import org.gradle.internal.impldep.org.objectweb.asm.ClassReader
import org.gradle.internal.impldep.org.objectweb.asm.Type
import org.gradle.tooling.BuildAction
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.plugins.gradle.model.ProjectImportAction
import java.net.JarURLConnection
import java.net.URL
import java.util.concurrent.ConcurrentMap
@ApiStatus.Internal
internal class GradleServerClasspathInferer {
private val classesUsedInBuildAction = LinkedHashSet<Class<*>>()
private val classesUsedByGradleProxyApp = LinkedHashSet<Class<*>>()
fun add(buildAction: BuildAction<*>) {
if (buildAction is ProjectImportAction) {
classesUsedInBuildAction.addAll(buildAction.modelProvidersClasses)
}
}
fun add(clazz: Class<*>) {
classesUsedByGradleProxyApp.add(clazz)
}
fun getClasspath(): List<String> {
val paths = LinkedHashSet<String>()
classesUsedByGradleProxyApp.mapNotNullTo(paths) { PathManager.getJarPathForClass(it) }
val classpathInferer = ClasspathInferer { className -> !className.startsWith("org.gradle.") } // skip traversing of Gradle api classes
for (clazz in classesUsedInBuildAction) {
val classpathUrls = classpathInferer.getClassPathFor(clazz)
for (url in classpathUrls) {
paths.add(urlToFile(url).path)
}
}
return paths.toList()
}
fun getClassloaders(): Collection<ClassLoader> {
return (classesUsedInBuildAction + classesUsedByGradleProxyApp)
.map { it.classLoader }
.toSet()
}
}
/**
* Based on [org.gradle.tooling.internal.provider.serialization.ClasspathInferer].
* Only classes matching the given [classNamePredicate] will be processed.
*/
private class ClasspathInferer(private val classNamePredicate: (String) -> Boolean = { true }) {
private val classPathCache: ConcurrentMap<Class<*>, Collection<URL>> = MapMaker().weakKeys().makeMap()
/**
* Returns a classpath URLs.
*/
fun getClassPathFor(targetClass: Class<*>): Collection<URL> {
if (!classNamePredicate(targetClass.name)) return emptyList()
return classPathCache.computeIfAbsent(targetClass) { find(targetClass) }
}
private fun find(target: Class<*>,
visited: MutableCollection<Class<*>?> = hashSetOf(),
dest: MutableCollection<URL> = linkedSetOf()): Collection<URL> {
val targetClassLoader = target.classLoader ?: return dest
if (targetClassLoader === ClassLoaderUtils.getPlatformClassLoader()) return dest // A system class, skip it
if (!visited.add(target)) return dest // Already seen this class, skip it
val resourceName = target.name.replace('.', '/') + ".class"
val resource = targetClassLoader.getResource(resourceName)
if (resource == null) {
log.warn("Could not determine classpath for $target")
return dest
}
try {
val classPathRoot = ClasspathUtil.getClasspathForClass(target)
dest.add(classPathRoot.toURI().toURL())
// To determine the dependencies of the class, load up the byte code and look for CONSTANT_Class entries in the constant pool
val urlConnection = resource.openConnection()
// Using the caches for these connections leaves the Jar files open. Don't use the cache, so that the Jar file is closed when the stream is closed below
// There are other options for solving this that may be more performant. However a class is inspected this way once and the result reused, so this approach is probably fine
(urlConnection as? JarURLConnection)?.useCaches = false
val reader = urlConnection.getInputStream().use { ClassReader(ByteStreams.toByteArray(it)) }
val charBuffer = CharArray(reader.maxStringLength)
for (i in 1 until reader.itemCount) {
val itemOffset = reader.getItem(i)
if (itemOffset > 0 && reader.readByte(itemOffset - 1) == 7) {
val classDescriptor = reader.readUTF8(itemOffset, charBuffer)
var type = Type.getObjectType(classDescriptor)
while (type.sort == Type.ARRAY) {
type = type.elementType
}
if (type.sort != Type.OBJECT) continue // A primitive type
val className = type.className
if (className == target.name) continue // A reference to this class
if (!classNamePredicate(className)) continue
val cl: Class<*> = try {
Class.forName(className, false, targetClassLoader)
}
catch (e: ClassNotFoundException) {
log.warn("Could not determine classpath for $target")
continue
}
find(cl, visited, dest)
}
}
}
catch (e: Exception) {
throw GradleException("Could not determine the class-path for $target.", e)
}
return dest
}
companion object {
private val log = logger<GradleServerClasspathInferer>()
}
}
| apache-2.0 | 7fd8f8a00ae9c3aa183f0af50a17a1a0 | 42.68 | 178 | 0.712821 | 4.490132 | false | false | false | false |
dpapathanasiou/ARMS | src/main/kotlin/org/papathanasiou/denis/ARMS/TimeBasedOneTimePassword.kt | 1 | 1862 | package org.papathanasiou.denis.ARMS
import java.nio.ByteBuffer
import java.nio.charset.StandardCharsets
import java.security.NoSuchAlgorithmException
import java.util.Date
import java.util.concurrent.TimeUnit
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import kotlin.experimental.and
/**
* TimeBasedOneTimePassword is an implementation of <a href="https://tools.ietf.org/html/rfc6238">RFC 6238</a>,
* using the given seed and acceptable timestep range to produce a one-time integer password using the given
* Date and HMAC algorithm (defaults to now and SHA512, respectively).
*/
object TimeBasedOneTimePassword {
fun generate(seed: String,
timestep: Long,
timeunit: TimeUnit,
timestamp: Date = Date(),
algo: String = "HmacSHA512"): Int {
// define a "Message Authentication Code" (MAC) algorithm, and initialize it with the seed
val mac = Mac.getInstance(algo)
?: throw NoSuchAlgorithmException("""unsupported algorithm: $algo""")
mac.init(SecretKeySpec(seed.byteInputStream(StandardCharsets.US_ASCII).readBytes(), "RAW"))
// generate a password as an integer, based on the Date + TimeUnit values
val buffer: ByteBuffer = ByteBuffer.allocate(8)
buffer.putLong(0, timestamp.getTime() / timeunit.toMillis(timestep))
val hmac = mac.doFinal(buffer.array())
val offset = (hmac[hmac.size - 1] and 0x0f).toInt()
for(i in 0 until 4) {
buffer.put(i, hmac[i + offset]);
}
return (buffer.getInt(0) and 0x7fffffff) % 100_000_000
}
val TOTP = fun (seed: String): Int {
// define a "standard" computation, i.e., using 30 seconds as the timestep range
return TimeBasedOneTimePassword.generate(seed,30L, TimeUnit.SECONDS)
}
}
| mit | 96cdacd178367d1becc04c0da619e9f9 | 36.24 | 111 | 0.676155 | 4.083333 | false | false | false | false |
jk1/intellij-community | platform/lang-api/src/com/intellij/codeInsight/hints/settings/ParameterNameHintsSettings.kt | 4 | 5566 | // Copyright 2000-2018 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.codeInsight.hints.settings
import com.intellij.lang.Language
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.util.getAttributeBooleanValue
import org.jdom.Element
private object XmlTagHelper {
val BLACKLISTS = "blacklists"
val LANGUAGE_LIST = "blacklist"
val LANGUAGE = "language"
val ADDED = "added"
val REMOVED = "removed"
val PATTERN = "pattern"
}
class Diff(val added: Set<String>, val removed: Set<String>) {
fun applyOn(base: Set<String>): Set<String> {
val baseSet = base.toMutableSet()
added.forEach { baseSet.add(it) }
removed.forEach { baseSet.remove(it) }
return baseSet
}
companion object Builder {
fun build(base: Set<String>, updated: Set<String>): Diff {
val removed = base.toMutableSet()
removed.removeAll(updated)
val added = updated.toMutableSet()
added.removeAll(base)
return Diff(added, removed)
}
}
}
@State(name = "ParameterNameHintsSettings", storages = [(Storage("parameter.hints.xml"))])
class ParameterNameHintsSettings : PersistentStateComponent<Element> {
private val removedPatterns = hashMapOf<String, Set<String>>()
private val addedPatterns = hashMapOf<String, Set<String>>()
private val options = hashMapOf<String, Boolean>()
fun addIgnorePattern(language: Language, pattern: String) {
val patternsBefore = getAddedPatterns(language)
setAddedPatterns(language, patternsBefore + pattern)
}
fun getBlackListDiff(language: Language): Diff {
val added = getAddedPatterns(language)
val removed = getRemovedPatterns(language)
return Diff(added, removed)
}
fun setBlackListDiff(language: Language, diff: Diff) {
setAddedPatterns(language, diff.added)
setRemovedPatterns(language, diff.removed)
}
override fun getState(): Element {
val root = Element("settings")
if (removedPatterns.isNotEmpty() || addedPatterns.isNotEmpty()) {
val blacklists = Element(XmlTagHelper.BLACKLISTS)
root.addContent(blacklists)
val allLanguages = removedPatterns.keys + addedPatterns.keys
allLanguages.forEach {
val removed = removedPatterns[it] ?: emptySet()
val added = addedPatterns[it] ?: emptySet()
val languageBlacklist = Element(XmlTagHelper.LANGUAGE_LIST).apply {
setAttribute(XmlTagHelper.LANGUAGE, it)
val removedElements = removed.map { it.toPatternElement(XmlTagHelper.REMOVED) }
val addedElements = added.map { it.toPatternElement(XmlTagHelper.ADDED) }
addContent(addedElements + removedElements)
}
blacklists.addContent(languageBlacklist)
}
}
options.forEach { id, value ->
val element = Element("option")
element.setAttribute("id", id)
element.setAttribute("value", value.toString())
root.addContent(element)
}
return root
}
override fun loadState(state: Element) {
addedPatterns.clear()
removedPatterns.clear()
options.clear()
val allBlacklistElements = state.getChild(XmlTagHelper.BLACKLISTS)
?.getChildren(XmlTagHelper.LANGUAGE_LIST) ?: emptyList()
allBlacklistElements.forEach { blacklistElement ->
val language = blacklistElement.attributeValue(XmlTagHelper.LANGUAGE) ?: return@forEach
val added = blacklistElement.extractPatterns(XmlTagHelper.ADDED)
addedPatterns[language] = addedPatterns[language]?.plus(added) ?: added
val removed = blacklistElement.extractPatterns(XmlTagHelper.REMOVED)
removedPatterns[language] = removedPatterns[language]?.plus(removed) ?: removed
}
state.getChildren("option").forEach {
val id = it.getAttributeValue("id")
options[id] = it.getAttributeBooleanValue("value")
}
}
companion object {
@JvmStatic
fun getInstance(): ParameterNameHintsSettings = ServiceManager.getService(ParameterNameHintsSettings::class.java)
}
fun getOption(optionId: String): Boolean? {
return options[optionId]
}
fun setOption(optionId: String, value: Boolean?) {
if (value == null) {
options.remove(optionId)
}
else {
options[optionId] = value
}
}
private fun getAddedPatterns(language: Language): Set<String> {
val key = language.displayName
return addedPatterns[key] ?: emptySet()
}
private fun getRemovedPatterns(language: Language): Set<String> {
val key = language.displayName
return removedPatterns[key] ?: emptySet()
}
private fun setRemovedPatterns(language: Language, removed: Set<String>) {
val key = language.displayName
removedPatterns[key] = removed
}
private fun setAddedPatterns(language: Language, added: Set<String>) {
val key = language.displayName
addedPatterns[key] = added
}
}
private fun Element.extractPatterns(tag: String): Set<String> {
return getChildren(tag).mapNotNull { it.attributeValue(XmlTagHelper.PATTERN) }.toSet()
}
private fun Element.attributeValue(attr: String): String? = this.getAttribute(attr)?.value
private fun String.toPatternElement(status: String): Element {
val element = Element(status)
element.setAttribute(XmlTagHelper.PATTERN, this)
return element
} | apache-2.0 | 36f06fd722b926ce643fb858520afbaa | 30.811429 | 140 | 0.706432 | 4.406968 | false | false | false | false |
jk1/intellij-community | platform/projectModel-impl/src/com/intellij/openapi/module/EmptyModuleManager.kt | 2 | 2684 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.module
import com.intellij.openapi.module.impl.createGrouper
import com.intellij.openapi.project.Project
import com.intellij.util.messages.MessageBus
import org.jetbrains.annotations.NotNull
class EmptyModuleManager(private val project: Project, messageBus: MessageBus) : ModuleManager() {
override fun hasModuleGroups(): Boolean = false
override fun newModule(filePath: String, moduleTypeId: String): Nothing = throw UnsupportedOperationException()
override fun loadModule(filePath: String): Nothing = throw UnsupportedOperationException()
override fun disposeModule(module: Module) {
}
override fun getModules(): Array<Module> = emptyArray<Module>()
override fun findModuleByName(name: String): Nothing? = null
override fun getSortedModules(): Array<Module> = emptyArray<Module>()
override fun moduleDependencyComparator(): Nothing = throw UnsupportedOperationException()
override fun getModuleDependentModules(module: Module): List<Module> = emptyList<Module>()
override fun isModuleDependent(@NotNull module: Module, @NotNull onModule: Module): Boolean = false
override fun moduleGraph(): Nothing = moduleGraph(true)
override fun moduleGraph(includeTests: Boolean): Nothing = throw UnsupportedOperationException()
override fun getModifiableModel(): Nothing = throw UnsupportedOperationException()
override fun getModuleGroupPath(module: Module): Array<String> = emptyArray<String>()
override fun setUnloadedModules(unloadedModuleNames: MutableList<String>) {
}
override fun getModuleGrouper(model: ModifiableModuleModel?): ModuleGrouper {
return createGrouper(project, model)
}
override fun getAllModuleDescriptions(): List<ModuleDescription> = emptyList<ModuleDescription>()
override fun getUnloadedModuleDescriptions(): List<UnloadedModuleDescription> = emptyList<UnloadedModuleDescription>()
override fun getUnloadedModuleDescription(moduleName: String): Nothing? = null
override fun removeUnloadedModules(unloadedModules: MutableCollection<UnloadedModuleDescription>) {
}
} | apache-2.0 | dd9f45e8460ffafa67658954343bc9ff | 38.485294 | 120 | 0.78465 | 5.064151 | false | false | false | false |
mvmike/min-cal-widget | app/src/test/kotlin/cat/mvmike/minimalcalendarwidget/domain/configuration/item/ThemeTest.kt | 1 | 14954 | // Copyright (c) 2016, Miquel Martí <[email protected]>
// See LICENSE for licensing information
package cat.mvmike.minimalcalendarwidget.domain.configuration.item
import cat.mvmike.minimalcalendarwidget.BaseTest
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import java.time.DayOfWeek
import java.util.stream.Stream
// MAIN
internal const val DARK_THEME_MAIN_TEXT_COLOUR = 2131034226
internal const val LIGHT_THEME_MAIN_TEXT_COLOUR = 2131034227
private const val HEADER_LAYOUT = 2131427357
// CELL
internal const val CELL_VIEW_ID = 16908308
internal const val CELL_LAYOUT = 2131427356
internal const val DARK_THEME_CELL_TEXT_COLOUR = 2131034228
internal const val LIGHT_THEME_CELL_TEXT_COLOUR = 2131034229
internal const val SATURDAY_IN_MONTH_DARK_THEME_CELL_BACKGROUND = 2131034149
internal const val SUNDAY_IN_MONTH_DARK_THEME_CELL_BACKGROUND = 2131034155
internal const val SATURDAY_DARK_THEME_CELL_BACKGROUND = 2131034147
internal const val SUNDAY_DARK_THEME_CELL_BACKGROUND = 2131034153
internal const val TODAY_DARK_THEME_CELL_BACKGROUND = 2131034161
internal const val IN_MONTH_DARK_THEME_CELL_BACKGROUND = 2131034159
private const val TODAY_LIGHT_THEME_CELL_BACKGROUND = 2131034162
private const val IN_MONTH_LIGHT_THEME_CELL_BACKGROUND = 2131034160
internal const val SATURDAY_IN_MONTH_LIGHT_THEME_CELL_BACKGROUND = 2131034150
internal const val SUNDAY_IN_MONTH_LIGHT_THEME_CELL_BACKGROUND = 2131034156
internal class ThemeTest : BaseTest() {
@ParameterizedTest
@MethodSource("getCombinationOfThemesAndDaysOfWeekWithExpectedCellHeader")
fun getCellHeader(theme: Theme, dayOfWeek: DayOfWeek, expectedResult: Cell) {
val result = theme.getCellHeader(dayOfWeek)
assertThat(result).isEqualTo(expectedResult)
}
@ParameterizedTest
@MethodSource("getCombinationOfThemesAndDayStatusesWithExpectedCellDay")
fun getCellDay(theme: Theme, isToday: Boolean, inMonth: Boolean, dayOfWeek: DayOfWeek, expectedResult: Cell) {
val result = theme.getCellDay(
isToday = isToday,
inMonth = inMonth,
dayOfWeek = dayOfWeek
)
assertThat(result).isEqualTo(expectedResult)
}
@Suppress("UnusedPrivateMember")
private fun getCombinationOfThemesAndDaysOfWeekWithExpectedCellHeader(): Stream<Arguments> = Stream.of(
Arguments.of(
Theme.DARK, DayOfWeek.MONDAY,
Cell(CELL_VIEW_ID, layout = HEADER_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = null)
),
Arguments.of(
Theme.DARK, DayOfWeek.TUESDAY,
Cell(CELL_VIEW_ID, layout = HEADER_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = null)
),
Arguments.of(
Theme.DARK, DayOfWeek.WEDNESDAY,
Cell(CELL_VIEW_ID, layout = HEADER_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = null)
),
Arguments.of(
Theme.DARK, DayOfWeek.THURSDAY,
Cell(CELL_VIEW_ID, layout = HEADER_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = null)
),
Arguments.of(
Theme.DARK, DayOfWeek.FRIDAY,
Cell(CELL_VIEW_ID, layout = HEADER_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = null)
),
Arguments.of(
Theme.DARK, DayOfWeek.SATURDAY,
Cell(CELL_VIEW_ID, layout = HEADER_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = SATURDAY_IN_MONTH_DARK_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.DARK, DayOfWeek.SUNDAY,
Cell(CELL_VIEW_ID, layout = HEADER_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = SUNDAY_IN_MONTH_DARK_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.LIGHT, DayOfWeek.MONDAY,
Cell(CELL_VIEW_ID, layout = HEADER_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = null)
),
Arguments.of(
Theme.LIGHT, DayOfWeek.TUESDAY,
Cell(CELL_VIEW_ID, layout = HEADER_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = null)
),
Arguments.of(
Theme.LIGHT, DayOfWeek.WEDNESDAY,
Cell(CELL_VIEW_ID, layout = HEADER_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = null)
),
Arguments.of(
Theme.LIGHT, DayOfWeek.THURSDAY,
Cell(CELL_VIEW_ID, layout = HEADER_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = null)
),
Arguments.of(
Theme.LIGHT, DayOfWeek.FRIDAY,
Cell(CELL_VIEW_ID, layout = HEADER_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = null)
),
Arguments.of(
Theme.LIGHT, DayOfWeek.SATURDAY,
Cell(CELL_VIEW_ID, layout = HEADER_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = SATURDAY_IN_MONTH_LIGHT_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.LIGHT, DayOfWeek.SUNDAY,
Cell(CELL_VIEW_ID, layout = HEADER_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = SUNDAY_IN_MONTH_LIGHT_THEME_CELL_BACKGROUND)
)
)
@Suppress("UnusedPrivateMember", "LongMethod")
private fun getCombinationOfThemesAndDayStatusesWithExpectedCellDay(): Stream<Arguments> = Stream.of(
Arguments.of(
Theme.DARK, true, true, DayOfWeek.MONDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = TODAY_DARK_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.DARK, true, true, DayOfWeek.TUESDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = TODAY_DARK_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.DARK, true, true, DayOfWeek.WEDNESDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = TODAY_DARK_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.DARK, true, true, DayOfWeek.THURSDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = TODAY_DARK_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.DARK, true, true, DayOfWeek.FRIDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = TODAY_DARK_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.DARK, true, true, DayOfWeek.SATURDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = 2131034151)
),
Arguments.of(
Theme.DARK, true, true, DayOfWeek.SUNDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = 2131034157)
),
Arguments.of(
Theme.DARK, false, true, DayOfWeek.MONDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = IN_MONTH_DARK_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.DARK, false, true, DayOfWeek.TUESDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = IN_MONTH_DARK_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.DARK, false, true, DayOfWeek.WEDNESDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = IN_MONTH_DARK_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.DARK, false, true, DayOfWeek.THURSDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = IN_MONTH_DARK_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.DARK, false, true, DayOfWeek.FRIDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = IN_MONTH_DARK_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.DARK, false, true, DayOfWeek.SATURDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = SATURDAY_IN_MONTH_DARK_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.DARK, false, true, DayOfWeek.SUNDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_MAIN_TEXT_COLOUR, background = SUNDAY_IN_MONTH_DARK_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.DARK, false, false, DayOfWeek.MONDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_CELL_TEXT_COLOUR, background = null)
),
Arguments.of(
Theme.DARK, false, false, DayOfWeek.TUESDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_CELL_TEXT_COLOUR, background = null)
),
Arguments.of(
Theme.DARK, false, false, DayOfWeek.WEDNESDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_CELL_TEXT_COLOUR, background = null)
),
Arguments.of(
Theme.DARK, false, false, DayOfWeek.THURSDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_CELL_TEXT_COLOUR, background = null)
),
Arguments.of(
Theme.DARK, false, false, DayOfWeek.FRIDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_CELL_TEXT_COLOUR, background = null)
),
Arguments.of(
Theme.DARK, false, false, DayOfWeek.SATURDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_CELL_TEXT_COLOUR, background = SATURDAY_DARK_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.DARK, false, false, DayOfWeek.SUNDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = DARK_THEME_CELL_TEXT_COLOUR, background = SUNDAY_DARK_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.LIGHT, true, true, DayOfWeek.MONDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = TODAY_LIGHT_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.LIGHT, true, true, DayOfWeek.TUESDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = TODAY_LIGHT_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.LIGHT, true, true, DayOfWeek.WEDNESDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = TODAY_LIGHT_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.LIGHT, true, true, DayOfWeek.THURSDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = TODAY_LIGHT_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.LIGHT, true, true, DayOfWeek.FRIDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = TODAY_LIGHT_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.LIGHT, true, true, DayOfWeek.SATURDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = 2131034152)
),
Arguments.of(
Theme.LIGHT, true, true, DayOfWeek.SUNDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = 2131034158)
),
Arguments.of(
Theme.LIGHT, false, true, DayOfWeek.MONDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = IN_MONTH_LIGHT_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.LIGHT, false, true, DayOfWeek.TUESDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = IN_MONTH_LIGHT_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.LIGHT, false, true, DayOfWeek.WEDNESDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = IN_MONTH_LIGHT_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.LIGHT, false, true, DayOfWeek.THURSDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = IN_MONTH_LIGHT_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.LIGHT, false, true, DayOfWeek.FRIDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = IN_MONTH_LIGHT_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.LIGHT, false, true, DayOfWeek.SATURDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = SATURDAY_IN_MONTH_LIGHT_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.LIGHT, false, true, DayOfWeek.SUNDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_MAIN_TEXT_COLOUR, background = SUNDAY_IN_MONTH_LIGHT_THEME_CELL_BACKGROUND)
),
Arguments.of(
Theme.LIGHT, false, false, DayOfWeek.MONDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_CELL_TEXT_COLOUR, background = null)
),
Arguments.of(
Theme.LIGHT, false, false, DayOfWeek.TUESDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_CELL_TEXT_COLOUR, background = null)
),
Arguments.of(
Theme.LIGHT, false, false, DayOfWeek.WEDNESDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_CELL_TEXT_COLOUR, background = null)
),
Arguments.of(
Theme.LIGHT, false, false, DayOfWeek.THURSDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_CELL_TEXT_COLOUR, background = null)
),
Arguments.of(
Theme.LIGHT, false, false, DayOfWeek.FRIDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_CELL_TEXT_COLOUR, background = null)
),
Arguments.of(
Theme.LIGHT, false, false, DayOfWeek.SATURDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_CELL_TEXT_COLOUR, background = 2131034148)
),
Arguments.of(
Theme.LIGHT, false, false, DayOfWeek.SUNDAY,
Cell(CELL_VIEW_ID, layout = CELL_LAYOUT, textColour = LIGHT_THEME_CELL_TEXT_COLOUR, background = 2131034154)
)
)
}
| bsd-3-clause | 2ea59150c557b1991b7eb88a008e4b3e | 50.03413 | 157 | 0.651976 | 3.905197 | false | false | false | false |
bgogetap/KotlinWeather | app/src/main/kotlin/com/cultureoftech/kotlinweather/main/MainPresenter.kt | 1 | 5321 | package com.cultureoftech.kotlinweather.main
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationManager
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.Snackbar
import android.view.Menu
import android.view.MenuItem
import com.cultureoftech.kotlinweather.R
import com.cultureoftech.kotlinweather.base.ActivityPresenter
import com.cultureoftech.kotlinweather.base.ActivityResultDelegate
import com.cultureoftech.kotlinweather.dagger.ForMain
import com.cultureoftech.kotlinweather.details.DetailsScreen
import com.cultureoftech.kotlinweather.permissions.Permission
import com.cultureoftech.kotlinweather.permissions.PermissionHelper
import com.cultureoftech.kotlinweather.ui.PresenterRoot
import com.cultureoftech.kotlinweather.ui.UiManager
import com.cultureoftech.kotlinweather.weather.CityWeatherResponse
import timber.log.Timber
import javax.inject.Inject
/**
* Created by bgogetap on 2/20/16.
*/
@ForMain
class MainPresenter @Inject constructor(
val sharedPrefs: SharedPreferences,
val uiManager: UiManager,
val permissionHelper: PermissionHelper,
val loader: WeatherLoader,
val activityPresenter: ActivityPresenter
) : PresenterRoot<MainView>(), MainContract.Presenter, ActivityResultDelegate {
private var data: CityWeatherResponse? = null
private var city: String = ""
private var lastId: Long = -1L
override fun viewAttached() {
activityPresenter.registerResultDelegate(this)
activityPresenter.resetToolbarMenu()
city = sharedPrefs.getString("last_city", "Omaha")
lastId = sharedPrefs.getLong("last_city_id", -1L)
loadData(false)
}
override fun loadData(forceRefresh: Boolean) {
if (data == null || forceRefresh) {
if (lastId != -1L) {
loadDataForCityId()
} else {
loadDataForCity(city)
}
} else {
setData()
}
}
override fun loadDataForCity(city: String) {
val query = city.replace(" ", "_")
loader.getWeatherForCity(query).subscribe({
Timber.d(it.toString())
data = it
setData()
}, { Timber.e("Error loading weather", it.message) })
}
private fun loadDataForCityId() {
loader.getWeatherForCityId(lastId).subscribe({
Timber.d(it.toString())
data = it
setData()
}, { Timber.e("Error loading weather from ID", it.message) })
}
override fun loadDataForLocation(location: Location) {
loader.getWeatherForLocation(location.latitude, location.longitude).subscribe({
Timber.d(it.toString())
data = it
setData()
}, { Timber.e("Error loading weather from location", it.message) })
}
override fun loadDetailsForCity() {
val cityId: Long = data?.id ?: -1L
if (cityId != -1L) {
uiManager.push(DetailsScreen(cityId, data?.name))
}
//TODO please try again with a different city
}
private fun setData() {
sharedPrefs.edit().putString("last_city", data?.name).apply()
sharedPrefs.edit().putLong("last_city_id", lastId).apply()
lastId = data?.id ?: lastId
city = data?.name ?: city
getView()?.setData(data)
}
override fun onCreateOptionsMenu(menu: Menu?) {
if (!uiManager.isTopScreen(MainScreen::class.java)) return
getView()?.initSearch(menu)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if (permissions[0].equals(Permission.LOCATION.permissionString)) {
val granted = grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
if (granted) {
getLocation()
} else {
if (getView() != null) {
Snackbar.make(getView() as CoordinatorLayout,
R.string.cant_provide_location_based_weather, Snackbar.LENGTH_LONG)
.show()
}
}
}
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.menu_location -> {
getLocation()
return true
}
R.id.menu_refresh -> loadData(true)
}
return false
}
private fun getLocation() {
if (permissionHelper.hasPermission(Permission.LOCATION)) {
val locationManager: LocationManager = getView()?.context?.getSystemService(Context.LOCATION_SERVICE) as LocationManager
val lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)
if (lastKnownLocation != null) {
loadDataForLocation(lastKnownLocation)
} else {
// TODO "Try searching for a city"
}
} else {
permissionHelper.requestPermission(Permission.LOCATION)
}
}
override fun viewDetached() {
activityPresenter.unregisterResultDelegate(this)
}
} | apache-2.0 | 4ae990c3e6700e00c132d00a6c6f7960 | 34.48 | 132 | 0.642548 | 4.772197 | false | false | false | false |
cmzy/okhttp | okhttp-testing-support/src/main/kotlin/okhttp3/FakeDns.kt | 1 | 2472 | /*
* Copyright (C) 2012 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.net.InetAddress
import java.net.UnknownHostException
import org.assertj.core.api.Assertions.assertThat
class FakeDns : Dns {
private val hostAddresses: MutableMap<String, List<InetAddress>> = mutableMapOf()
private val requestedHosts: MutableList<String> = mutableListOf()
private var nextAddress = 100
/** Sets the results for `hostname`. */
operator fun set(
hostname: String,
addresses: List<InetAddress>
): FakeDns {
hostAddresses[hostname] = addresses
return this
}
/** Clears the results for `hostname`. */
fun clear(hostname: String): FakeDns {
hostAddresses.remove(hostname)
return this
}
@Throws(UnknownHostException::class) fun lookup(
hostname: String,
index: Int
): InetAddress {
return hostAddresses[hostname]!![index]
}
@Throws(UnknownHostException::class)
override fun lookup(hostname: String): List<InetAddress> {
requestedHosts.add(hostname)
return hostAddresses[hostname] ?: throw UnknownHostException()
}
fun assertRequests(vararg expectedHosts: String?) {
assertThat(requestedHosts).containsExactly(*expectedHosts)
requestedHosts.clear()
}
/** Allocates and returns `count` fake addresses like [255.0.0.100, 255.0.0.101]. */
fun allocate(count: Int): List<InetAddress> {
return try {
val result: MutableList<InetAddress> = mutableListOf()
for (i in 0 until count) {
if (nextAddress > 255) {
throw AssertionError("too many addresses allocated")
}
result.add(
InetAddress.getByAddress(
byteArrayOf(
255.toByte(), 0.toByte(), 0.toByte(),
nextAddress++.toByte()
)
)
)
}
result
} catch (e: UnknownHostException) {
throw AssertionError()
}
}
}
| apache-2.0 | 2b94dccf747dbe27aa4d7ee1ec28b081 | 29.146341 | 87 | 0.669903 | 4.390764 | false | false | false | false |
ridibooks/rbhelper-android | src/main/kotlin/com/ridi/books/helper/Log.kt | 1 | 2142 | package com.ridi.books.helper
import android.util.Log
object Log {
@JvmStatic
fun e(tag: String, e: Throwable?) = e(tag, "", e)
@JvmOverloads
@JvmStatic
fun e(tag: String, message: String, e: Throwable? = null) = Log.e(tag, message, e)
@JvmStatic
fun e(clazz: Class<*>, e: Throwable?) = e(clazz, "", e)
@JvmOverloads
@JvmStatic
fun e(clazz: Class<*>, message: String, e: Throwable? = null) = e(clazz.simpleName, message, e)
@JvmStatic
fun w(tag: String, e: Throwable?) = w(tag, "", e)
@JvmOverloads
@JvmStatic
fun w(tag: String, message: String, e: Throwable? = null) = Log.w(tag, message, e)
@JvmStatic
fun w(clazz: Class<*>, e: Throwable?) = w(clazz, "", e)
@JvmOverloads
@JvmStatic
fun w(clazz: Class<*>, message: String, e: Throwable? = null) = w(clazz.simpleName, message, e)
@JvmStatic
fun d(tag: String, e: Throwable?) = d(tag, "", e)
@JvmOverloads
@JvmStatic
fun d(tag: String, message: String, e: Throwable? = null) = Log.d(tag, message, e)
@JvmStatic
fun d(clazz: Class<*>, e: Throwable?) = d(clazz, "", e)
@JvmOverloads
@JvmStatic
fun d(clazz: Class<*>, message: String, e: Throwable? = null) = d(clazz.simpleName, message, e)
@JvmStatic
fun d(message: String) = d("ridibug", message)
@JvmStatic
fun v(tag: String, e: Throwable?) = v(tag, "", e)
@JvmOverloads
@JvmStatic
fun v(tag: String, message: String, e: Throwable? = null) = Log.v(tag, message, e)
@JvmStatic
fun v(clazz: Class<*>, e: Throwable?) = v(clazz, "", e)
@JvmOverloads
@JvmStatic
fun v(clazz: Class<*>, message: String, e: Throwable? = null) = v(clazz.simpleName, message, e)
@JvmStatic
fun i(tag: String, e: Throwable?) = i(tag, "", e)
@JvmOverloads
@JvmStatic
fun i(tag: String, message: String, e: Throwable? = null) = Log.i(tag, message, e)
@JvmStatic
fun i(clazz: Class<*>, e: Throwable?) = i(clazz, "", e)
@JvmOverloads
@JvmStatic
fun i(clazz: Class<*>, message: String, e: Throwable? = null) = i(clazz.simpleName, message, e)
}
| mit | 6d891e4deb36c7e5241b389122b82358 | 26.461538 | 99 | 0.602241 | 3.373228 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/tracker/importer/internal/TrackerImporterBreakTheGlassHelper.kt | 1 | 8301 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.tracker.importer.internal
import dagger.Reusable
import javax.inject.Inject
import org.hisp.dhis.android.core.arch.db.querybuilders.internal.WhereClauseBuilder
import org.hisp.dhis.android.core.enrollment.internal.EnrollmentStore
import org.hisp.dhis.android.core.imports.TrackerImportConflictTableInfo
import org.hisp.dhis.android.core.imports.internal.TEIWebResponseHandlerSummary
import org.hisp.dhis.android.core.imports.internal.TrackerImportConflictStore
import org.hisp.dhis.android.core.program.AccessLevel
import org.hisp.dhis.android.core.program.internal.ProgramStoreInterface
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstance
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstanceInternalAccessor
import org.hisp.dhis.android.core.trackedentity.internal.NewTrackerImporterPayload
import org.hisp.dhis.android.core.trackedentity.ownership.OwnershipManagerImpl
import org.hisp.dhis.android.core.user.internal.UserOrganisationUnitLinkStore
@Reusable
internal class TrackerImporterBreakTheGlassHelper @Inject constructor(
private val conflictStore: TrackerImportConflictStore,
private val userOrganisationUnitLinkStore: UserOrganisationUnitLinkStore,
private val enrollmentStore: EnrollmentStore,
private val programStore: ProgramStoreInterface,
private val ownershipManagerImpl: OwnershipManagerImpl
) {
/**
* Get glass errors for importer V1
*/
fun getGlassErrors(
summary: TEIWebResponseHandlerSummary,
instances: List<TrackedEntityInstance>
): List<TrackedEntityInstance> {
return summary.enrollments.ignored.filter { enrollment ->
isProtectedInSearchScope(enrollment.program(), enrollment.organisationUnit())
}.mapNotNull { enrollment ->
instances.mapNotNull { tei ->
val teiEnrollment =
TrackedEntityInstanceInternalAccessor.accessEnrollments(tei).find { it.uid() == enrollment.uid() }
if (teiEnrollment != null) {
TrackedEntityInstanceInternalAccessor
.insertEnrollments(tei.toBuilder(), listOf(teiEnrollment))
.build()
} else {
null
}
}.firstOrNull()
}
}
/**
* Get glass errors for importer V2
*/
fun getGlassErrors(payload: NewTrackerImporterPayload): NewTrackerImporterPayload {
val importedEnrollments = payload.enrollments.map { it.uid() }
val enrollmentWhereClause = WhereClauseBuilder()
.appendKeyStringValue(TrackerImportConflictTableInfo.Columns.ERROR_CODE, ImporterError.E1102.name)
.appendInKeyStringValues(TrackerImportConflictTableInfo.Columns.ENROLLMENT, importedEnrollments)
.build()
val importerEvents = payload.events.map { it.uid() }
val eventWhereClause = WhereClauseBuilder()
.appendKeyStringValue(TrackerImportConflictTableInfo.Columns.ERROR_CODE, ImporterError.E1000.name)
.appendInKeyStringValues(TrackerImportConflictTableInfo.Columns.EVENT, importerEvents)
.build()
val candidateEnrollments = conflictStore.selectWhere(enrollmentWhereClause)
val candidateEvents = conflictStore.selectWhere(eventWhereClause)
val glassErrors = NewTrackerImporterPayload()
candidateEnrollments
.mapNotNull { error -> error.enrollment()?.let { id -> payload.enrollments.find { it.uid() == id } } }
.filter { enrollment ->
isProtectedInSearchScope(enrollment.program(), enrollment.organisationUnit())
}
.map { enrollment ->
glassErrors.enrollments.add(enrollment)
glassErrors.trackedEntities.addAll(
payload.trackedEntities.filter {
it.uid() == enrollment.trackedEntity()
}
)
glassErrors.events.addAll(
payload.events.filter {
it.enrollment() == enrollment.uid()
}
)
}
candidateEvents
.filter { error -> glassErrors.events.none { it.uid() == error.event() } }
.mapNotNull { error -> error.event()?.let { id -> payload.events.find { it.uid() == id } } }
.filter { event ->
event.enrollment()?.let { enrollmentStore.selectByUid(it) }?.let {
isProtectedInSearchScope(it.program(), it.organisationUnit())
} ?: false
}
.map { event ->
glassErrors.events.add(event)
}
return glassErrors
}
/**
* Fake break the glass for importer V1
*/
fun fakeBreakGlass(instances: List<TrackedEntityInstance>) {
instances.forEach { instance ->
TrackedEntityInstanceInternalAccessor.accessEnrollments(instance).forEach { enrollment ->
if (instance.uid() != null && enrollment.program() != null)
ownershipManagerImpl.fakeBreakGlass(instance.uid()!!, enrollment.program()!!)
}
}
}
/**
* Fake break the glass for importer V2
*/
fun fakeBreakGlass(payload: NewTrackerImporterPayload) {
payload.enrollments.forEach {
if (it.trackedEntity() != null && it.program() != null) {
ownershipManagerImpl.fakeBreakGlass(it.trackedEntity()!!, it.program()!!)
}
}
payload.events
.filter { event -> payload.enrollments.none { it.uid() == event.enrollment() } }
.forEach { event ->
event.enrollment()?.let { enrollmentStore.selectByUid(it) }?.let {
if (it.trackedEntityInstance() != null && it.program() != null) {
ownershipManagerImpl.fakeBreakGlass(it.trackedEntityInstance()!!, it.program()!!)
}
}
}
}
fun isProtectedInSearchScope(program: String?, organisationUnit: String?): Boolean {
return if (program != null && organisationUnit != null) {
isProtectedProgram(program) && isNotCaptureScope(organisationUnit)
} else {
false
}
}
private fun isProtectedProgram(program: String?): Boolean {
return program?.let { programStore.selectByUid(it)?.accessLevel() == AccessLevel.PROTECTED } ?: false
}
private fun isNotCaptureScope(organisationUnit: String?): Boolean {
return organisationUnit?.let { !userOrganisationUnitLinkStore.isCaptureScope(it) } ?: false
}
}
| bsd-3-clause | 9d3b66a371b32860689702f016cb0e7d | 44.861878 | 118 | 0.666426 | 5.067766 | false | false | false | false |
Tickaroo/tikxml | processor/src/test/java/com/tickaroo/tikxml/processor/mock/MockXmlElement.kt | 1 | 1333 | /*
* Copyright (C) 2015 Hannes Dorfmann
* Copyright (C) 2015 Tickaroo, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.tickaroo.tikxml.processor.mock
import com.tickaroo.tikxml.processor.field.AttributeField
import com.tickaroo.tikxml.processor.xml.XmlChildElement
import com.tickaroo.tikxml.processor.xml.XmlRootElement
import java.util.LinkedHashMap
import javax.lang.model.element.TypeElement
/**
*
* @author Hannes Dorfmann
*/
class MockXmlElement(override val nameAsRoot: String = "mockRoot", override val element: TypeElement = MockClassElement()) :
XmlRootElement {
override val attributes = LinkedHashMap<String, AttributeField>()
override val childElements = LinkedHashMap<String, XmlChildElement>()
override fun isXmlElementAccessableFromOutsideTypeAdapter() = true
} | apache-2.0 | 82093122da464e5e2af5458090767686 | 33.205128 | 124 | 0.768942 | 4.231746 | false | false | false | false |
dahlstrom-g/intellij-community | python/src/com/jetbrains/python/console/PydevConsoleCli.kt | 5 | 6540 | // Copyright 2000-2018 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.
@file:JvmName("PydevConsoleCli")
package com.jetbrains.python.console
import com.intellij.execution.ExecutionException
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.configurations.ParamsGroup
import com.intellij.execution.target.HostPort
import com.intellij.execution.target.TargetEnvironment
import com.intellij.execution.target.value.TargetEnvironmentFunction
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkAdditionalData
import com.jetbrains.python.PythonHelper
import com.jetbrains.python.run.PythonCommandLineState
import com.jetbrains.python.run.PythonExecution
import com.jetbrains.python.run.prepareHelperScriptExecution
import com.jetbrains.python.run.target.HelpersAwareTargetEnvironmentRequest
import com.jetbrains.python.sdk.PythonEnvUtil
import com.jetbrains.python.sdk.PythonSdkAdditionalData
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor
import java.io.File
import java.util.function.Function
const val MODE_OPTION = "mode"
const val MODE_OPTION_SERVER_VALUE = "server"
const val MODE_OPTION_CLIENT_VALUE = "client"
const val HOST_OPTION = "host"
const val PORT_OPTION = "port"
private fun getOptionString(name: String, value: Any): String = "--$name=$value"
private fun getOptionString(name: String, value: TargetEnvironmentFunction<*>): TargetEnvironmentFunction<String> =
value.andThen { it: Any? -> "--$name=$it" }
/**
* Adds new or replaces existing [PythonCommandLineState.GROUP_SCRIPT]
* parameters of [this] command line with the path to Python console script
* (*pydevconsole.py*) and parameters required for running it in the *client*
* mode.
*
* @param port the port that Python console script will connect to
*
* @see PythonHelper.CONSOLE
*/
fun GeneralCommandLine.setupPythonConsoleScriptInClientMode(sdk: Sdk, port: Int) {
initializePydevConsoleScriptGroup(PythonSdkFlavor.getFlavor(sdk)).appendClientModeParameters(port)
}
/**
* Adds new or replaces existing [PythonCommandLineState.GROUP_SCRIPT]
* parameters of [this] command line with the path to Python console script
* (*pydevconsole.py*) and parameters required for running it in the *server*
* mode.
*
* Updates Python path according to the flavor defined in [sdkAdditionalData].
*
* @param sdkAdditionalData the additional data where [PythonSdkFlavor] is taken
* from
* @param port the optional port that Python console script will listen at
*
* @see PythonHelper.CONSOLE
*/
@JvmOverloads
fun GeneralCommandLine.setupPythonConsoleScriptInServerMode(sdkAdditionalData: SdkAdditionalData, port: Int? = null) {
initializePydevConsoleScriptGroup((sdkAdditionalData as? PythonSdkAdditionalData)?.flavor).appendServerModeParameters(port)
}
private fun GeneralCommandLine.initializePydevConsoleScriptGroup(pythonSdkFlavor: PythonSdkFlavor?): ParamsGroup {
val group: ParamsGroup = parametersList.getParamsGroup(PythonCommandLineState.GROUP_SCRIPT)?.apply { parametersList.clearAll() }
?: parametersList.addParamsGroup(PythonCommandLineState.GROUP_SCRIPT)
val pythonPathEnv = hashMapOf<String, String>()
PythonHelper.CONSOLE.addToPythonPath(pythonPathEnv)
val consolePythonPath = pythonPathEnv[PythonEnvUtil.PYTHONPATH]
// here we get Python console path for the system interpreter
// let us convert it to the project interpreter path
consolePythonPath?.split(File.pathSeparator)?.let { pythonPathList ->
pythonSdkFlavor?.initPythonPath(pythonPathList, false, environment) ?: PythonEnvUtil.addToPythonPath(environment, pythonPathList)
}
group.addParameter(PythonHelper.CONSOLE.asParamString())
// fix `AttributeError` when running Python Console on IronPython
pythonSdkFlavor?.extraDebugOptions?.let { extraDebugOptions ->
val exeGroup = parametersList.getParamsGroup(PythonCommandLineState.GROUP_EXE_OPTIONS)
extraDebugOptions.forEach { exeGroup?.addParameter(it) }
}
return group
}
private fun ParamsGroup.appendServerModeParameters(port: Int? = null) {
addParameter(getOptionString(MODE_OPTION, MODE_OPTION_SERVER_VALUE))
port?.let { addParameter(getOptionString(PORT_OPTION, it)) }
}
private fun ParamsGroup.appendClientModeParameters(port: Int) {
addParameter(getOptionString(MODE_OPTION, MODE_OPTION_CLIENT_VALUE))
addParameter(getOptionString(PORT_OPTION, port))
}
/**
* Waits for Python console server to be started. The indication for this is
* the server port that Python console script outputs to *stdout* when the
* server socket is bound to the port and it is listening to it.
*
* The connection to Python console script server should be established *after*
* this method finishes.
*
* @throws ExecutionException if timeout occurred or an other error
*
* @see PydevConsoleRunnerImpl.PORTS_WAITING_TIMEOUT
* @see PydevConsoleRunnerImpl.getRemotePortFromProcess
*/
@Throws(ExecutionException::class)
fun waitForPythonConsoleServerToBeStarted(process: Process) {
PydevConsoleRunnerImpl.getRemotePortFromProcess(process)
}
fun createPythonConsoleScriptInServerMode(serverPort: Int,
helpersAwareTargetRequest: HelpersAwareTargetEnvironmentRequest): PythonExecution {
val pythonScriptExecution = prepareHelperScriptExecution(PythonHelper.CONSOLE, helpersAwareTargetRequest)
pythonScriptExecution.addParameter(getOptionString(MODE_OPTION, MODE_OPTION_SERVER_VALUE))
pythonScriptExecution.addParameter(getOptionString(PORT_OPTION, serverPort))
return pythonScriptExecution
}
/**
* @param ideServerPort the host and port where the IDE being Python
* Console frontend listens for the connection
*/
fun createPythonConsoleScriptInClientMode(ideServerPort: Function<TargetEnvironment, HostPort>,
helpersAwareTargetRequest: HelpersAwareTargetEnvironmentRequest): PythonExecution {
val pythonScriptExecution = prepareHelperScriptExecution(PythonHelper.CONSOLE, helpersAwareTargetRequest)
pythonScriptExecution.addParameter(getOptionString(MODE_OPTION, MODE_OPTION_CLIENT_VALUE))
pythonScriptExecution.addParameter(getOptionString(HOST_OPTION, ideServerPort.andThen(HostPort::host)))
pythonScriptExecution.addParameter(getOptionString(PORT_OPTION, ideServerPort.andThen(HostPort::port)))
return pythonScriptExecution
} | apache-2.0 | 5239e4610b8b993a2eb805a4b74c722d | 45.721429 | 140 | 0.791896 | 4.618644 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/inspections/cleanup/basic/deprecatedSymbols.kt | 15 | 383 | package pack
@Deprecated("", ReplaceWith("bar(p + 1)"))
public fun oldFun1(p: Int): Int = 0
@Deprecated("", ReplaceWith("bar(-1)"))
public fun oldFun1(): Int = 0
@Deprecated("", ReplaceWith("bar(p + 2)"))
public fun oldFun2(p: Int): Int = 0
public fun oldFun2(): Int = 0
@Deprecated("", ReplaceWith("bar(p)"))
public fun oldFun3(p: Int): Int = 0
public fun bar(p: Int): Int = p | apache-2.0 | bb9671aef0d718ab99e1e80e3a6be982 | 21.588235 | 42 | 0.639687 | 3.165289 | false | false | false | false |
Killian-LeClainche/Java-Base-Application-Engine | src/polaris/okapi/render/TextureManager.kt | 1 | 10326 | package polaris.okapi.render
import org.lwjgl.opengl.GL11
import polaris.okapi.options.IntSetting
import polaris.okapi.options.Settings
import polaris.okapi.util.ioResourceToByteBuffer
import org.lwjgl.opengl.GL11.*
import org.lwjgl.opengl.GL12.GL_TEXTURE_MAX_LEVEL
import org.lwjgl.stb.STBImage.*
import org.lwjgl.stb.STBImageResize.*
import org.lwjgl.system.MemoryStack.stackPush
import org.lwjgl.system.rpmalloc.RPmalloc.rpfree
import org.lwjgl.system.rpmalloc.RPmalloc.rpmalloc
import org.lwjgl.opengl.GL30.glGenerateMipmap
import org.lwjgl.opengl.GL42.glTexStorage2D
import java.io.File
import java.io.IOException
import java.nio.ByteBuffer
import java.util.HashMap
import kotlin.experimental.and
import kotlin.math.roundToInt
/**
* Created by Killian Le Clainche on 12/12/2017.
*/
class TextureManager(val settings: Settings) {
var textures: MutableMap<String, Texture> = HashMap()
set(value) = field.forEach { reinitTexture(it.value) }
operator fun get(value: String) : Texture {
return textures[value]!!
}
operator fun get(value: List<String>) : List<Texture> {
return value.filter { textures.containsKey(it) }.map { textures[it]!! }
}
operator fun get(value: Array<String>) : List<Texture> {
return value.filter { textures.containsKey(it) }.map { textures[it]!! }
}
operator fun set(key: String, value: String) {
val mipmap = (settings["mipmap"] as IntSetting?)?.value ?: 0
if(!textures.containsKey(key))
genTexture(key, File(value), mipmap)
}
operator fun set(key: String, value: Array<String>) {
val mipmap = (settings["mipmap"] as IntSetting?)?.value ?: 0
if(!textures.containsKey(key))
genTexture(key, File(value[0]), File(value[1]), mipmap)
}
operator fun set(key: String, value: Texture) {
if(textures.containsKey(key) && textures[key] != value)
textures[key]!!.close()
textures[key] = value
}
operator fun set(key: List<String>, value: List<Texture>) {
key.forEachIndexed { index, _key ->
this[_key] = value[index]
}
}
operator fun set(key: Array<String>, value: Array<Texture>) {
key.forEachIndexed { index, _key ->
this[_key] = value[index]
}
}
operator fun plusAssign(value: Texture) {
reinitTexture(value)
}
operator fun plusAssign(value: List<Texture>) {
val mipmap = (settings["mipmap"] as IntSetting?)?.value ?: 0
value.forEach { reinitTexture(it) }
}
operator fun plusAssign(value: Array<Texture>) {
val mipmap = (settings["mipmap"] as IntSetting?)?.value ?: 0
value.forEach { reinitTexture(it) }
}
operator fun plusAssign(value: Array<String>) {
val mipmap = (settings["mipmap"] as IntSetting?)?.value ?: 0
if(value.size == 3)
genTexture(value[0], File(value[1]), File(value[2]), mipmap)
else
genTexture(value[0], File(value[1]), mipmap)
}
operator fun minusAssign(value: Texture) {
clearTexture(value)
}
operator fun minusAssign(value: String) {
val texture = textures[value]
if(texture != null)
clearTexture(texture)
}
operator fun minusAssign(value: List<Any>) {
getTextures(value).forEach {
clearTexture(it)
}
}
operator fun minusAssign(value: Array<Any>) {
getTextures(value).forEach {
clearTexture(it)
}
}
operator fun remAssign(value: Texture) {
textures.filterNot { it.value.id == value.id }
.forEach { clearTexture(it.value) }
}
operator fun remAssign(value: String) {
if(textures.containsKey(value))
textures.filterNot { it.key == value }
.forEach { clearTexture(it.value) }
}
operator fun remAssign(value: List<Any>) {
val list = getTextures(value)
textures.filterNot { list.any { it2 -> it2.id == it.value.id } }
.forEach { clearTexture(it.value) }
}
operator fun remAssign(value: Array<Any>) {
val list = getTextures(value)
textures.filterNot { list.any { it2 -> it2.id == it.value.id } }
.forEach { clearTexture(it.value) }
}
fun getTextures(list: List<Any>) : List<Texture> {
return list.filter {
if(it is Texture)
true
else
textures.containsKey(it)
}.map {
it as? Texture ?: textures[it]!!
}
}
fun getTextures(list: Array<Any>) : List<Texture> {
return list.filter {
if(it is Texture)
true
else
textures.containsKey(it)
}.map {
it as? Texture ?: textures[it]!!
}
}
@JvmOverloads
fun genTexture(textureName: String, textureFile: File, mipmapMaxLevel: Int = 1): Texture? {
val image = ioResourceToByteBuffer(textureFile) ?: return null
var texture: Texture? = null
stackPush().use {
val width = it.mallocInt(1)
val height = it.mallocInt(1)
val comp = it.mallocInt(1)
if(!stbi_info_from_memory(image, width, height, comp)) {
System.err.println("Could not load info for image!")
System.err.println(stbi_failure_reason())
return null;
}
val data = stbi_load_from_memory(image, width, height, comp, 0)
if(data == null) {
System.err.println("Could not load image!")
System.err.println(stbi_failure_reason())
return null;
}
texture = Texture(textureName, width[0], height[0], comp[0], mipmapMaxLevel, data)
genTexture(texture!!)
textures.put(textureName, texture!!)
}
return texture
}
@JvmOverloads
fun genTexture(textureName: String, width : Int, height : Int, comp : Int, data : ByteBuffer, mipmapMaxLevel: Int = 1) : Texture {
val texture = Texture(textureName, width, height, comp, mipmapMaxLevel, data)
genTexture(texture)
textures.put(textureName, texture)
return texture
}
fun genTexture(texture: Texture) {
texture.bind()
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, texture.mipmapMaxLevel)
val format = if(texture.composite == 4)
GL_RGBA
else
GL_RGB
glTexImage2D(GL_TEXTURE_2D, 0, format, texture.width, texture.height, 0, format, GL_UNSIGNED_BYTE, texture.image)
var pixelsIn : ByteBuffer? = texture.image
var widthIn = texture.width
var heightIn = texture.height
var mipmapLevel = 1
while(mipmapLevel <= texture.mipmapMaxLevel && widthIn > 1 && heightIn > 1) {
val widthOut = (widthIn shr 1).coerceAtLeast(2)
val heightOut = (heightIn shr 1).coerceAtLeast(2)
val pixelsOut = rpmalloc((widthOut * heightOut * texture.composite).toLong())
if(pixelsOut != null && pixelsIn != null) {
stbir_resize_uint8_generic(pixelsIn, widthIn, heightIn, widthIn * texture.composite,
pixelsOut, widthOut, heightOut, widthOut * texture.composite,
texture.composite, if (texture.composite == 4) 3 else STBIR_ALPHA_CHANNEL_NONE, STBIR_FLAG_ALPHA_PREMULTIPLIED,
STBIR_EDGE_WRAP, STBIR_FILTER_MITCHELL, STBIR_COLORSPACE_SRGB)
glTexImage2D(GL_TEXTURE_2D, mipmapLevel++, format, widthOut, heightOut, 0, format, GL_UNSIGNED_BYTE, pixelsOut)
}
else
System.err.println("Error creating ByteBuffer of size $widthOut $heightOut and composite ${texture.composite}!")
if (pixelsIn != null && mipmapLevel > 1)
rpfree(pixelsIn)
pixelsIn = pixelsOut
widthIn = widthOut
heightIn = heightOut
}
if(pixelsIn != null && mipmapLevel > 1)
rpfree(pixelsIn)
/*texture.bind()
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
if (texture.mipmapMaxLevel > 1)
{
glTexStorage2D(GL_TEXTURE_2D, 5, GL_RGBA8, texture.width, texture.height);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, texture.width, texture.height, GL_RGBA, GL_UNSIGNED_BYTE, texture.image);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
}
else
{
GL11.glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture.width, texture.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, texture.image);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}*/
this[texture.name] = texture
}
@JvmOverloads
fun genTexture(textureName: String, textureFile: File, arrayFile: File, mipmapMaxLevel: Int = 1): TextureArray? {
val buffer= ioResourceToByteBuffer(arrayFile) ?: return null
val baseTexture = genTexture(textureName, textureFile, mipmapMaxLevel) ?: return null
val texture = TextureArray(baseTexture, buffer)
textures.put(textureName, texture)
return texture
}
fun reinitTexture(texture: Texture) {
texture.destroy()
texture.id = glGenTextures()
genTexture(texture)
this[texture.name] = texture
}
fun clear() {
textures.forEach { it.value.close() }
textures.clear()
}
fun clearTexture(texture: Texture) {
texture.close()
textures.remove(texture.name)
}
}
| gpl-2.0 | 1d8775960dab0b0d124a697e8a724d62 | 31.88535 | 135 | 0.606721 | 3.991496 | false | false | false | false |
Leanplum/Leanplum-Android-SDK | AndroidSDKCore/src/main/java/com/leanplum/actions/MessageDisplayChoice.kt | 1 | 1707 | /*
* Copyright 2022, Leanplum, Inc. All rights reserved.
*
* 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.leanplum.actions
/**
* Use static factory methods [MessageDisplayChoice.show], [MessageDisplayChoice.discard], and
* [MessageDisplayChoice.delay] as a result to [MessageDisplayController.shouldDisplayMessage].
*/
data class MessageDisplayChoice private constructor(val type: Type, val delaySeconds: Int = 0) {
enum class Type {
SHOW,
DISCARD,
DELAY
}
companion object {
@JvmStatic
fun show() = MessageDisplayChoice(Type.SHOW)
@JvmStatic
fun discard() = MessageDisplayChoice(Type.DISCARD)
@JvmStatic
fun delay(delaySeconds: Int) = MessageDisplayChoice(Type.DELAY, delaySeconds)
/**
* When actions are delayed indefinitely use [LeanplumActions.triggerDelayedMessages] to trigger
* them again.
*/
@JvmStatic
fun delayIndefinitely() = delay(0)
}
}
| apache-2.0 | c858e1648bfcc59fcdb7566d5792b558 | 31.826923 | 100 | 0.728764 | 4.246269 | false | false | false | false |
vladmm/intellij-community | platform/script-debugger/backend/src/org/jetbrains/rpc/CommandSenderBase.kt | 1 | 1983 | /*
* 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 org.jetbrains.rpc
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.Promise
import org.jetbrains.jsonProtocol.Request
abstract class CommandSenderBase<SUCCESS_RESPONSE> {
protected abstract fun <RESULT : Any> doSend(message: Request<RESULT>, callback: RequestPromise<SUCCESS_RESPONSE, RESULT>)
fun <RESULT : Any> send(message: Request<RESULT>): Promise<RESULT> {
val callback = RequestPromise<SUCCESS_RESPONSE, RESULT>(message.methodName)
doSend(message, callback)
return callback
}
protected class RequestPromise<SUCCESS_RESPONSE, RESULT : Any>(private val methodName: String?) : AsyncPromise<RESULT>(), RequestCallback<SUCCESS_RESPONSE> {
@Suppress("BASE_WITH_NULLABLE_UPPER_BOUND")
override fun onSuccess(response: SUCCESS_RESPONSE?, resultReader: ResultReader<SUCCESS_RESPONSE>?) {
try {
if (resultReader == null || response == null) {
@Suppress("UNCHECKED_CAST")
setResult(response as RESULT?)
}
else {
if (methodName == null) {
setResult(null)
}
else {
setResult(resultReader.readResult(methodName, response))
}
}
}
catch (e: Throwable) {
LOG.error(e)
setError(e)
}
}
override fun onError(error: Throwable) {
setError(error)
}
}
} | apache-2.0 | e8786b614cc1d87bfa252ab283de0bc3 | 33.206897 | 159 | 0.683812 | 4.339168 | false | false | false | false |
georocket/georocket | src/main/kotlin/io/georocket/index/postgresql/PostgreSQLIndex.kt | 1 | 14382 | package io.georocket.index.postgresql
import io.georocket.constants.ConfigConstants
import io.georocket.index.AbstractIndex
import io.georocket.index.DatabaseIndex
import io.georocket.index.Index
import io.georocket.index.normalizeLayer
import io.georocket.query.Compare
import io.georocket.query.IndexQuery
import io.georocket.query.QueryPart
import io.georocket.query.StartsWith
import io.georocket.storage.ChunkMeta
import io.georocket.util.UniqueID
import io.georocket.util.getAwait
import io.vertx.core.Vertx
import io.vertx.core.json.JsonArray
import io.vertx.kotlin.core.json.jsonArrayOf
import io.vertx.kotlin.core.json.jsonObjectOf
import io.vertx.kotlin.coroutines.await
import io.vertx.sqlclient.Row
import io.vertx.sqlclient.Tuple
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.flow
import org.slf4j.LoggerFactory
class PostgreSQLIndex private constructor(
vertx: Vertx, url: String,
username: String, password: String
) : Index, AbstractIndex() {
companion object {
private val log = LoggerFactory.getLogger(PostgreSQLIndex::class.java)
/**
* Table and column names
*/
private const val CHUNK_META = "chunkMeta"
private const val DOCUMENTS = "documents"
private const val ID = "id"
private const val DATA = "data"
private const val TAGS = "tags"
private const val PROPS = "props"
private const val GENATTRS = "genAttrs"
private const val KEY = "key"
private const val VALUE = "value"
private const val NAME = "name"
private const val LAYER = "layer"
private const val IDX_PREFIX = "georocket_"
suspend fun create(
vertx: Vertx, url: String? = null, username: String? = null,
password: String? = null
): PostgreSQLIndex {
val config = vertx.orCreateContext.config()
val actualUrl = url ?: config.getString(ConfigConstants.INDEX_POSTGRESQL_URL) ?: throw IllegalStateException(
"Missing configuration item `" +
ConfigConstants.INDEX_POSTGRESQL_URL + "'"
)
val actualUsername =
username ?: config.getString(ConfigConstants.INDEX_POSTGRESQL_USERNAME) ?: throw IllegalStateException(
"Missing configuration item `" +
ConfigConstants.INDEX_POSTGRESQL_USERNAME + "'"
)
val actualPassword =
password ?: config.getString(ConfigConstants.INDEX_POSTGRESQL_PASSWORD) ?: throw IllegalStateException(
"Missing configuration item `" +
ConfigConstants.INDEX_POSTGRESQL_PASSWORD + "'"
)
return vertx.executeBlocking<PostgreSQLIndex> { p ->
p.complete(PostgreSQLIndex(vertx, actualUrl, actualUsername, actualPassword))
}.await()
}
}
private val pgClient = PostgreSQLClient(vertx, url, username, password)
private val client = pgClient.client
private suspend fun addOrGetChunkMeta(meta: ChunkMeta): String {
return addedChunkMetaCache.getAwait(meta) {
val statement = "WITH new_id AS (" +
"INSERT INTO $CHUNK_META ($ID, $DATA) VALUES ($1, $2) " +
"ON CONFLICT DO NOTHING RETURNING $ID" +
") SELECT COALESCE(" +
"(SELECT $ID FROM new_id)," +
"(SELECT $ID from $CHUNK_META WHERE $DATA=$2)" +
")"
val params = Tuple.of(UniqueID.next(), meta.toJsonObject())
val r = client.preparedQuery(statement).execute(params).await()
r.first().getString(0)
}
}
private suspend fun findChunkMeta(id: String): ChunkMeta {
val r = loadedChunkMetaCache.getAwait(id) {
val statement = "SELECT $DATA FROM $CHUNK_META WHERE $ID=$1"
val r = client.preparedQuery(statement).execute(Tuple.of(id)).await()
r?.first()?.getJsonObject(0)?.let { ChunkMeta.fromJsonObject(it) }
?: throw NoSuchElementException("Could not find chunk metadata with ID `$id' in index")
}
return r
}
override suspend fun close() {
client.close()
}
override suspend fun addMany(docs: Collection<Index.AddManyParam>) {
val params = docs.map { d ->
val chunkMetaId = addOrGetChunkMeta(d.meta)
val copy = d.doc.copy()
copy.put(CHUNK_META, chunkMetaId)
Tuple.of(d.path, copy)
}
val statement = "INSERT INTO $DOCUMENTS ($ID, $DATA) VALUES ($1, $2)"
client.preparedQuery(statement).executeBatch(params).await()
}
private suspend fun <T> streamQuery(
statement: String, params: List<Any>,
readSize: Int = 50, rowToItem: suspend (Row) -> T
): Flow<T> = flow {
pgClient.withConnection { conn ->
val preparedStatement = conn.prepare(statement).await()
val transaction = conn.begin().await()
try {
val cursor = preparedStatement.cursor(Tuple.wrap(params))
try {
do {
val rows = cursor.read(readSize).await()
emitAll(rows.map { rowToItem(it) }.asFlow())
} while (cursor.hasMore())
} finally {
cursor.close()
}
} finally {
transaction.commit()
}
}
}
override suspend fun getDistinctMeta(query: IndexQuery): Flow<ChunkMeta> {
val (where, params) = PostgreSQLQueryTranslator.translate(query)
val statement = "SELECT DISTINCT $DATA->>'$CHUNK_META' FROM $DOCUMENTS WHERE $where"
return streamQuery(statement, params) { findChunkMeta(it.getString(0)) }
}
override suspend fun getMeta(query: IndexQuery): Flow<Pair<String, ChunkMeta>> {
val (where, params) = PostgreSQLQueryTranslator.translate(query)
val statement = "SELECT $ID, $DATA->>'$CHUNK_META' FROM $DOCUMENTS WHERE $where"
return streamQuery(statement, params) { it.getString(0) to findChunkMeta(it.getString(1)) }
}
override suspend fun getPaginatedMeta(
query: IndexQuery, maxPageSize: Int,
previousScrollId: String?
): Index.Page<Pair<String, ChunkMeta>> {
val (where, whereParams) = PostgreSQLQueryTranslator.translate(query)
val (statement, params) = if (previousScrollId != null) {
val params = whereParams + previousScrollId + maxPageSize
val statement = "SELECT $ID, $DATA->>'$CHUNK_META' FROM $DOCUMENTS " +
"WHERE $ID > $${whereParams.size + 1} AND ($where) " +
"ORDER BY $ID LIMIT $${whereParams.size + 2}"
statement to params
} else {
val params = whereParams + maxPageSize
val statement = "SELECT $ID, $DATA->>'$CHUNK_META' FROM $DOCUMENTS " +
"WHERE $where ORDER BY $ID LIMIT $${whereParams.size + 1}"
statement to params
}
val items = client.preparedQuery(statement).execute(Tuple.from(params))
.await().map { it.getString(0) to findChunkMeta(it.getString(1)) }
val scrollId = items.lastOrNull()?.first
return Index.Page(items, scrollId)
}
override suspend fun getPaths(query: IndexQuery): Flow<String> {
val (where, params) = PostgreSQLQueryTranslator.translate(query)
val statement = "SELECT $ID FROM $DOCUMENTS WHERE $where"
return streamQuery(statement, params) { it.getString(0) }
}
override suspend fun addTags(query: IndexQuery, tags: Collection<String>) {
val (where, params) = PostgreSQLQueryTranslator.translate(query)
val n = params.size
val statement = "UPDATE $DOCUMENTS SET " +
"$DATA = jsonb_set(" +
"$DATA, '{$TAGS}', to_jsonb(" +
"ARRAY(" +
"SELECT DISTINCT jsonb_array_elements(" +
"COALESCE($DATA->'$TAGS', '[]'::jsonb) || $${n + 1}" +
")" +
")" +
")" +
") WHERE $where"
val paramsList = params.toMutableList()
paramsList.add(JsonArray(tags.toList()))
client.preparedQuery(statement).execute(Tuple.wrap(paramsList)).await()
}
override suspend fun removeTags(query: IndexQuery, tags: Collection<String>) {
val (where, params) = PostgreSQLQueryTranslator.translate(query)
val n = params.size
val statement = "UPDATE $DOCUMENTS SET $DATA = jsonb_set($DATA, '{$TAGS}', " +
"COALESCE(($DATA->'$TAGS')::jsonb, '[]'::jsonb) - $${n + 1}::text[]) WHERE $where"
val paramsList = params.toMutableList()
paramsList.add(tags.toTypedArray())
client.preparedQuery(statement).execute(Tuple.wrap(paramsList)).await()
}
override suspend fun setProperties(query: IndexQuery, properties: Map<String, Any>) {
// convert to JSON array
val props = jsonArrayOf()
properties.entries.forEach { e ->
props.add(jsonObjectOf(KEY to e.key, VALUE to e.value))
}
// remove properties with these keys (if they exist)
removeProperties(query, properties.keys)
val (where, params) = PostgreSQLQueryTranslator.translate(query)
val n = params.size
val statement = "UPDATE $DOCUMENTS SET $DATA = jsonb_set(" +
"$DATA, '{$PROPS}', $DATA->'$PROPS' || $${n + 1}" +
") WHERE $where"
val paramsList = params.toMutableList()
paramsList.add(props)
client.preparedQuery(statement).execute(Tuple.wrap(paramsList)).await()
}
override suspend fun removeProperties(query: IndexQuery, properties: Collection<String>) {
val (where, params) = PostgreSQLQueryTranslator.translate(query)
val n = params.size
val statement = "UPDATE $DOCUMENTS SET " +
"$DATA = jsonb_set(" +
"$DATA, '{$PROPS}', to_jsonb(" +
"ARRAY(" +
"WITH a AS (SELECT jsonb_array_elements($DATA->'$PROPS') AS c) " +
"SELECT * FROM a WHERE c->>'$KEY' != ANY($${n + 1})" +
")" +
")" +
") WHERE $where"
val paramsList = params.toMutableList()
paramsList.add(properties.toTypedArray())
client.preparedQuery(statement).execute(Tuple.wrap(paramsList)).await()
}
override suspend fun getPropertyValues(query: IndexQuery, propertyName: String): Flow<Any?> {
val (where, params) = PostgreSQLQueryTranslator.translate(query)
val n = params.size
val statement = "WITH p AS (SELECT jsonb_array_elements($DATA->'$PROPS') " +
"AS a FROM $DOCUMENTS WHERE $where) " +
"SELECT DISTINCT a->'$VALUE' FROM p WHERE a->'$KEY'=$${n + 1}"
val paramsList = params.toMutableList()
paramsList.add(propertyName)
return streamQuery(statement, paramsList) { it.getValue(0) }
}
override suspend fun getAttributeValues(query: IndexQuery, attributeName: String): Flow<Any?> {
val (where, params) = PostgreSQLQueryTranslator.translate(query)
val n = params.size
val statement = "WITH p AS (SELECT jsonb_array_elements($DATA->'$GENATTRS') " +
"AS a FROM $DOCUMENTS WHERE $where) " +
"SELECT DISTINCT a->'$VALUE' FROM p WHERE a->'$KEY'=$${n + 1}"
val paramsList = params.toMutableList()
paramsList.add(attributeName)
return streamQuery(statement, paramsList) { it.getValue(0) }
}
override suspend fun delete(query: IndexQuery) {
val (where, params) = PostgreSQLQueryTranslator.translate(query)
val statement = "DELETE FROM $DOCUMENTS WHERE $where"
client.preparedQuery(statement).execute(Tuple.from(params)).await()
}
override suspend fun delete(paths: Collection<String>) {
val statement = "DELETE FROM $DOCUMENTS WHERE $ID=ANY($1)"
val preparedStatement = client.preparedQuery(statement)
for (chunk in paths.chunked(1000)) {
val deleteParams = Tuple.of(chunk.toTypedArray())
preparedStatement.execute(deleteParams).await()
}
}
override suspend fun getLayers(): Flow<String> {
val statement = "SELECT DISTINCT $DATA->>'$LAYER' FROM $DOCUMENTS"
return streamQuery(statement, emptyList()) { it.getString(0) }
}
override suspend fun existsLayer(name: String): Boolean {
val (where, params) = PostgreSQLQueryTranslator.translate(StartsWith(LAYER, normalizeLayer(name)))
val statement = "SELECT TRUE FROM $DOCUMENTS WHERE $where LIMIT 1"
val r = client.preparedQuery(statement).execute(Tuple.wrap(params)).await()
return r.size() > 0
}
override suspend fun setUpDatabaseIndexes(indexes: List<DatabaseIndex>) {
fun indexName(idx: DatabaseIndex): String = "$IDX_PREFIX${idx.name.lowercase()}"
// Check which indexes already exist.
// We only ever touch indexes, that start with the prefix 'georocket_',
// so that we do not accidentally remove/overwrite/alter any indexes that the user/dba added
// manually or the default index on the primary key.
val existingIndexes =
client.query("SELECT indexname FROM pg_indexes WHERE tablename = '$DOCUMENTS' AND indexname LIKE '$IDX_PREFIX%'")
.execute().await().map { it.getString(0) }
// create new indexes
val indexesToAdd = indexes.filter { idx ->
val name = indexName(idx)
!existingIndexes.contains(name)
}
for (idx in indexesToAdd) {
val using = when (idx) {
is DatabaseIndex.Array -> "gin((${fieldJsonValue(DATA, idx.field)}) jsonb_path_ops)"
is DatabaseIndex.ElemMatchExists -> "gin((${fieldJsonValue(DATA, idx.field)}) jsonb_path_ops)"
is DatabaseIndex.Eq -> "hash((${fieldJsonValue(DATA, idx.field)}))"
is DatabaseIndex.Geo -> "gist(ST_GeomFromGeoJSON(${fieldJsonValue(DATA, idx.field)}))"
is DatabaseIndex.Range -> "btree((${fieldJsonValue(DATA, idx.field)}))"
is DatabaseIndex.StartsWith -> "btree((${fieldStringValue(DATA, idx.field)}) text_pattern_ops)"
is DatabaseIndex.ElemMatchCompare -> {
val array = fieldJsonValue(DATA, idx.field)
val jsonpath = jsonPathToArrayElementField(
listOf(
Compare(idx.elemKeyField, idx.keyValue, QueryPart.ComparisonOperator.EQ)
), idx.elemValueField
)
"btree(jsonb_path_query_first($array, '$jsonpath'))"
}
}
val name = indexName(idx)
log.info("Creating database index $name")
val statement = "CREATE INDEX $name ON $DOCUMENTS USING $using"
log.debug("Index definition: $statement")
client.query(statement).execute().await()
}
// Remove indexes that are not present anymore.
val indexesToRemove =
existingIndexes.filter { index_name ->
indexes.none { indexName(it) == index_name }
}
for (name in indexesToRemove) {
log.info("Dropping database index $name")
client.query("DROP INDEX $name").execute().await()
}
// Refresh statistics
if (indexesToAdd.isNotEmpty() || indexesToRemove.isNotEmpty()) {
log.debug("Executing ANALYZE")
client.query("ANALYZE").execute().await()
}
}
}
| apache-2.0 | d011d07b5cd27e96e9b4481ee1649bdc | 38.729282 | 119 | 0.667153 | 3.955446 | false | false | false | false |
algra/pact-jvm | pact-jvm-pact-broker/src/main/kotlin/au/com/dius/pact/provider/broker/com/github/kittinunf/result/Result.kt | 1 | 3800 | /**
* This file inlined from https://github.com/kittinunf/Result
*/
package au.com.dius.pact.provider.broker.com.github.kittinunf.result
inline fun <reified X> Result<*, *>.getAs() = when (this) {
is Result.Success -> value as? X
is Result.Failure -> error as? X
}
fun <V : Any> Result<V, *>.success(f: (V) -> Unit) = fold(f, {})
fun <E : Exception> Result<*, E>.failure(f: (E) -> Unit) = fold({}, f)
infix fun <V : Any, E : Exception> Result<V, E>.or(fallback: V) = when (this) {
is Result.Success -> this
else -> Result.Success<V, E>(fallback)
}
infix fun <V : Any, E : Exception> Result<V, E>.getOrElse(fallback: V) = when (this) {
is Result.Success -> value
else -> fallback
}
fun <V : Any, U : Any, E : Exception> Result<V, E>.map(transform: (V) -> U): Result<U, E> = when (this) {
is Result.Success -> Result.Success<U, E>(transform(value))
is Result.Failure -> Result.Failure<U, E>(error)
}
fun <V : Any, U : Any, E : Exception> Result<V, E>.flatMap(transform: (V) -> Result<U, E>): Result<U, E> = when (this) {
is Result.Success -> transform(value)
is Result.Failure -> Result.Failure<U, E>(error)
}
fun <V : Any, E : Exception, E2 : Exception> Result<V, E>.mapError(transform: (E) -> E2) = when (this) {
is Result.Success -> Result.Success<V, E2>(value)
is Result.Failure -> Result.Failure<V, E2>(transform(error))
}
fun <V : Any, E : Exception, E2 : Exception> Result<V, E>.flatMapError(transform: (E) -> Result<V, E2>) = when (this) {
is Result.Success -> Result.Success<V, E2>(value)
is Result.Failure -> transform(error)
}
fun <V : Any> Result<V, *>.any(predicate: (V) -> Boolean): Boolean = when (this) {
is Result.Success -> predicate(value)
is Result.Failure -> false
}
fun <V : Any, U : Any> Result<V, *>.fanout(other: () -> Result<U, *>): Result<Pair<V, U>, *> =
flatMap { outer -> other().map { outer to it } }
sealed class Result<out V : Any, out E : Exception> {
abstract operator fun component1(): V?
abstract operator fun component2(): E?
inline fun <X> fold(success: (V) -> X, failure: (E) -> X): X {
return when (this) {
is Success -> success(this.value)
is Failure -> failure(this.error)
}
}
abstract fun get(): V
class Success<out V : Any, out E : Exception>(val value: V) : Result<V, E>() {
override fun component1(): V? = value
override fun component2(): E? = null
override fun get(): V = value
override fun toString() = "[Success: $value]"
override fun hashCode(): Int = value.hashCode()
override fun equals(other: Any?): Boolean {
if (this === other) return true
return other is Success<*, *> && value == other.value
}
}
class Failure<out V : Any, out E : Exception>(val error: E) : Result<V, E>() {
override fun component1(): V? = null
override fun component2(): E? = error
override fun get(): V = throw error
fun getException(): E = error
override fun toString() = "[Failure: $error]"
override fun hashCode(): Int = error.hashCode()
override fun equals(other: Any?): Boolean {
if (this === other) return true
return other is Failure<*, *> && error == other.error
}
}
companion object {
// Factory methods
fun <E : Exception> error(ex: E) = Failure<Nothing, E>(ex)
fun <V : Any> of(value: V?, fail: (() -> Exception) = { Exception() }): Result<V, Exception> {
return value?.let { Success<V, Nothing>(it) } ?: error(fail())
}
fun <V : Any> of(f: () -> V): Result<V, Exception> = try {
Success(f())
} catch (ex: Exception) {
Failure(ex)
}
}
}
| apache-2.0 | e4ffe83302e257c48283f3e1718136d1 | 32.043478 | 120 | 0.574474 | 3.417266 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/bridgeEntities/extensions.kt | 3 | 18475 | // 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.workspaceModel.storage.bridgeEntities
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.api.*
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import java.util.*
import kotlin.collections.HashMap
fun MutableEntityStorage.addModuleEntity(name: String,
dependencies: List<ModuleDependencyItem>,
source: EntitySource,
type: String? = null): ModuleEntity {
val entity = ModuleEntity(name, dependencies, source) {
this.type = type
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addJavaModuleSettingsEntity(inheritedCompilerOutput: Boolean,
excludeOutput: Boolean,
compilerOutput: VirtualFileUrl?,
compilerOutputForTests: VirtualFileUrl?,
languageLevelId: String?,
module: ModuleEntity,
source: EntitySource): JavaModuleSettingsEntity {
val entity = JavaModuleSettingsEntity(inheritedCompilerOutput, excludeOutput, source) {
this.compilerOutput = compilerOutput
this.compilerOutputForTests = compilerOutputForTests
this.languageLevelId = languageLevelId
this.module = module
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addModuleCustomImlDataEntity(rootManagerTagCustomData: String?,
customModuleOptions: Map<String, String>,
module: ModuleEntity,
source: EntitySource): ModuleCustomImlDataEntity {
val entity = ModuleCustomImlDataEntity(HashMap(customModuleOptions), source) {
this.rootManagerTagCustomData = rootManagerTagCustomData
this.module = module
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addModuleGroupPathEntity(path: List<String>,
module: ModuleEntity,
source: EntitySource): ModuleGroupPathEntity {
val entity = ModuleGroupPathEntity(path, source) {
this.module = module
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addSourceRootEntity(contentRoot: ContentRootEntity,
url: VirtualFileUrl,
rootType: String,
source: EntitySource): SourceRootEntity {
val entity = SourceRootEntity(url, rootType, source) {
this.contentRoot = contentRoot
}
this.addEntity(entity)
return entity
}
/**
* [JavaSourceRootEntity] has the same entity source as [SourceRootEntity].
* [JavaSourceRootEntityData] contains assertion for that. Please update an assertion in case you need a different entity source for these
* entities.
*/
fun MutableEntityStorage.addJavaSourceRootEntity(sourceRoot: SourceRootEntity,
generated: Boolean,
packagePrefix: String): JavaSourceRootEntity {
val entity = JavaSourceRootEntity(generated, packagePrefix, sourceRoot.entitySource) {
this.sourceRoot = sourceRoot
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addJavaResourceRootEntity(sourceRoot: SourceRootEntity,
generated: Boolean,
relativeOutputPath: String): JavaResourceRootEntity {
val entity = JavaResourceRootEntity(generated, relativeOutputPath, sourceRoot.entitySource) {
this.sourceRoot = sourceRoot
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addCustomSourceRootPropertiesEntity(sourceRoot: SourceRootEntity,
propertiesXmlTag: String): CustomSourceRootPropertiesEntity {
val entity = CustomSourceRootPropertiesEntity(propertiesXmlTag, sourceRoot.entitySource) {
this.sourceRoot = sourceRoot
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addContentRootEntity(url: VirtualFileUrl,
excludedUrls: List<VirtualFileUrl>,
excludedPatterns: List<String>,
module: ModuleEntity): ContentRootEntity {
return addContentRootEntityWithCustomEntitySource(url, excludedUrls, excludedPatterns, module, module.entitySource)
}
/**
* Entity source of content root is *almost* the same as the entity source of the corresponding module.
* Please update assertConsistency in [ContentRootEntityData] if you're using this method.
*/
fun MutableEntityStorage.addContentRootEntityWithCustomEntitySource(url: VirtualFileUrl,
excludedUrls: List<VirtualFileUrl>,
excludedPatterns: List<String>,
module: ModuleEntity,
source: EntitySource): ContentRootEntity {
val entity = ContentRootEntity(url, excludedUrls, excludedPatterns, source) {
this.module = module
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addLibraryEntity(name: String, tableId: LibraryTableId, roots: List<LibraryRoot>,
excludedRoots: List<VirtualFileUrl>, source: EntitySource): LibraryEntity {
val entity = LibraryEntity(name, tableId, roots, excludedRoots, source)
this.addEntity(entity)
return entity
}
/**
* [LibraryPropertiesEntity] has the same entity source as [LibraryEntity].
* [LibraryPropertiesEntityData] contains assertion for that. Please update an assertion in case you need a different entity source for these
* entities.
*/
fun MutableEntityStorage.addLibraryPropertiesEntity(library: LibraryEntity,
libraryType: String,
propertiesXmlTag: String?): LibraryPropertiesEntity {
val entity = LibraryPropertiesEntity(libraryType, library.entitySource) {
this.library = library
this.propertiesXmlTag = propertiesXmlTag
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addSdkEntity(library: LibraryEntity,
homeUrl: VirtualFileUrl, source: EntitySource): SdkEntity {
val entity = SdkEntity(homeUrl, source) {
this.library = library
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.getOrCreateExternalSystemModuleOptions(module: ModuleEntity,
source: EntitySource): ExternalSystemModuleOptionsEntity {
return module.exModuleOptions ?: run {
val entity = ExternalSystemModuleOptionsEntity(source) {
this.module = module
}
this.addEntity(entity)
entity
}
}
fun MutableEntityStorage.addFacetEntity(name: String,
facetType: String,
configurationXmlTag: String?,
module: ModuleEntity,
underlyingFacet: FacetEntity?,
source: EntitySource): FacetEntity {
val entity = FacetEntity(name, facetType, module.persistentId, source) {
this.configurationXmlTag = configurationXmlTag
this.module = module
this.underlyingFacet = underlyingFacet
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addArtifactEntity(name: String,
artifactType: String,
includeInProjectBuild: Boolean,
outputUrl: VirtualFileUrl?,
rootElement: CompositePackagingElementEntity,
source: EntitySource): ArtifactEntity {
val entity = ArtifactEntity(name, artifactType, includeInProjectBuild, source) {
this.outputUrl = outputUrl
this.rootElement = rootElement
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addArtifactPropertiesEntity(artifact: ArtifactEntity,
providerType: String,
propertiesXmlTag: String?,
source: EntitySource): ArtifactPropertiesEntity {
val entity = ArtifactPropertiesEntity(providerType, source) {
this.artifact = artifact
this.propertiesXmlTag = propertiesXmlTag
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addArtifactRootElementEntity(children: List<PackagingElementEntity>,
source: EntitySource): ArtifactRootElementEntity {
val entity = ArtifactRootElementEntity(source) {
this.children = children
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addDirectoryPackagingElementEntity(directoryName: String,
children: List<PackagingElementEntity>,
source: EntitySource): DirectoryPackagingElementEntity {
val entity = DirectoryPackagingElementEntity(directoryName, source) {
this.children = children
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addArchivePackagingElementEntity(fileName: String,
children: List<PackagingElementEntity>,
source: EntitySource): ArchivePackagingElementEntity {
val entity = ArchivePackagingElementEntity(fileName, source) {
this.children = children
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addArtifactOutputPackagingElementEntity(artifact: ArtifactId?,
source: EntitySource): ArtifactOutputPackagingElementEntity {
val entity = ArtifactOutputPackagingElementEntity(source) {
this.artifact = artifact
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addModuleOutputPackagingElementEntity(module: ModuleId?,
source: EntitySource): ModuleOutputPackagingElementEntity {
val entity = ModuleOutputPackagingElementEntity(source) {
this.module = module
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addLibraryFilesPackagingElementEntity(library: LibraryId?,
source: EntitySource): LibraryFilesPackagingElementEntity {
val entity = LibraryFilesPackagingElementEntity(source) {
this.library = library
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addModuleSourcePackagingElementEntity(module: ModuleId?,
source: EntitySource): ModuleSourcePackagingElementEntity {
val entity = ModuleSourcePackagingElementEntity(source) {
this.module = module
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addModuleTestOutputPackagingElementEntity(module: ModuleId?,
source: EntitySource): ModuleTestOutputPackagingElementEntity {
val entity = ModuleTestOutputPackagingElementEntity(source) {
this.module = module
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addDirectoryCopyPackagingElementEntity(filePath: VirtualFileUrl,
source: EntitySource): DirectoryCopyPackagingElementEntity {
val entity = DirectoryCopyPackagingElementEntity(filePath, source)
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addExtractedDirectoryPackagingElementEntity(filePath: VirtualFileUrl,
pathInArchive: String,
source: EntitySource): ExtractedDirectoryPackagingElementEntity {
val entity = ExtractedDirectoryPackagingElementEntity(filePath, pathInArchive, source)
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addFileCopyPackagingElementEntity(filePath: VirtualFileUrl,
renamedOutputFileName: String?,
source: EntitySource): FileCopyPackagingElementEntity {
val entity = FileCopyPackagingElementEntity(filePath, source) {
this.renamedOutputFileName = renamedOutputFileName
}
this.addEntity(entity)
return entity
}
fun MutableEntityStorage.addCustomPackagingElementEntity(typeId: String,
propertiesXmlTag: String,
children: List<PackagingElementEntity>,
source: EntitySource): CustomPackagingElementEntity {
val entity = CustomPackagingElementEntity(typeId, propertiesXmlTag, source) {
this.children = children
}
this.addEntity(entity)
return entity
}
fun SourceRootEntity.asJavaSourceRoot(): JavaSourceRootEntity? = javaSourceRoots.firstOrNull()
fun SourceRootEntity.asJavaResourceRoot(): JavaResourceRootEntity? = javaResourceRoots.firstOrNull()
val ModuleEntity.sourceRoots: List<SourceRootEntity>
get() = contentRoots.flatMap { it.sourceRoots }
fun ModuleEntity.getModuleLibraries(storage: EntityStorage): Sequence<LibraryEntity> {
return storage.entities(LibraryEntity::class.java)
.filter { (it.persistentId.tableId as? LibraryTableId.ModuleLibraryTableId)?.moduleId?.name == name }
}
val EntityStorage.projectLibraries
get() = entities(LibraryEntity::class.java).filter { it.persistentId.tableId == LibraryTableId.ProjectLibraryTableId }
/**
* All the [equalsAsOrderEntry] methods work similar to [compareTo] methods of corresponding order entries in the
* legacy project model.
*/
fun SourceRootEntity.equalsAsOrderEntry(other: SourceRootEntity): Boolean {
val beforePackagePrefix = this.asJavaSourceRoot()?.packagePrefix ?: this.asJavaResourceRoot()?.relativeOutputPath
val afterPackagePrefix = other.asJavaSourceRoot()?.packagePrefix ?: other.asJavaResourceRoot()?.relativeOutputPath
if (beforePackagePrefix != afterPackagePrefix) return false
val beforeGenerated = this.asJavaSourceRoot()?.generated ?: this.asJavaResourceRoot()?.generated
val afterGenerated = other.asJavaSourceRoot()?.generated ?: other.asJavaResourceRoot()?.generated
if (beforeGenerated != afterGenerated) return false
if (this.url != other.url) return false
return true
}
fun SourceRootEntity.hashCodeAsOrderEntry(): Int {
val packagePrefix = this.asJavaSourceRoot()?.packagePrefix ?: this.asJavaResourceRoot()?.relativeOutputPath
val generated = this.asJavaSourceRoot()?.generated ?: this.asJavaResourceRoot()?.generated
return Objects.hash(packagePrefix, generated, url)
}
fun ContentRootEntity.equalsAsOrderEntry(other: ContentRootEntity): Boolean {
if (this.url != other.url) return false
if (this.excludedUrls != other.excludedUrls) return false
if (this.excludedPatterns != other.excludedPatterns) return false
return true
}
fun ContentRootEntity.hashCodeAsOrderEntry(): Int = Objects.hash(url, excludedUrls, excludedPatterns)
fun ModuleDependencyItem.equalsAsOrderEntry(other: ModuleDependencyItem,
thisStore: EntityStorage, otherStore: EntityStorage): Boolean {
if (this::class != other::class) return false
return when (this) {
is ModuleDependencyItem.InheritedSdkDependency -> true // This is object
is ModuleDependencyItem.ModuleSourceDependency -> true // This is object
is ModuleDependencyItem.SdkDependency -> {
other as ModuleDependencyItem.SdkDependency
sdkName == other.sdkName
}
is ModuleDependencyItem.Exportable -> {
other as ModuleDependencyItem.Exportable
when {
exported != other.exported -> false
scope != other.scope -> false
else -> when (this) {
is ModuleDependencyItem.Exportable.ModuleDependency -> {
other as ModuleDependencyItem.Exportable.ModuleDependency
when {
productionOnTest != other.productionOnTest -> false
module.name != other.module.name -> false
else -> true
}
}
is ModuleDependencyItem.Exportable.LibraryDependency -> {
other as ModuleDependencyItem.Exportable.LibraryDependency
if (library.name != other.library.name) false
else if (library.tableId.level != other.library.tableId.level) false
else {
val beforeLibrary = thisStore.resolve(library)!!
val afterLibrary = otherStore.resolve(other.library)!!
if (beforeLibrary.excludedRoots != afterLibrary.excludedRoots) false
else {
val beforeLibraryKind = beforeLibrary.libraryProperties?.libraryType
val afterLibraryKind = afterLibrary.libraryProperties?.libraryType
when {
beforeLibraryKind != afterLibraryKind -> false
beforeLibrary.roots != afterLibrary.roots -> false
else -> true
}
}
}
}
}
}
}
}
} | apache-2.0 | 77925d43366ea56d77dd5a5f6770b786 | 42.678487 | 141 | 0.632097 | 6.614751 | false | false | false | false |
allotria/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/statistics/MavenActionsUsagesCollector.kt | 3 | 1781 | // Copyright 2000-2018 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.jetbrains.idea.maven.statistics
import com.intellij.execution.Executor
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
private const val GROUP_ID = "build.maven.actions"
class MavenActionsUsagesCollector {
enum class ActionID {
IntroducePropertyAction,
ExtractManagedDependenciesAction,
RunBuildAction,
ExecuteMavenRunConfigurationAction,
ShowMavenConnectors,
KillMavenConnector,
StartLocalMavenServer,
StartWslMavenServer,
}
companion object {
@JvmStatic
fun trigger(project: Project?,
actionID: ActionID,
place: String?,
isFromContextMenu: Boolean,
executor : Executor? = null) {
val data = FeatureUsageData().addProject(project)
if (place != null) {
data.addPlace(place).addData("context_menu", isFromContextMenu)
}
executor?.let { data.addData("executor", it.id) }
FUCounterUsageLogger.getInstance().logEvent(GROUP_ID, actionID.name, data)
}
@JvmStatic
fun trigger(project: Project?, actionID: ActionID, event: AnActionEvent?, executor : Executor? = null) {
trigger(project, actionID, event?.place, event?.isFromContextMenu ?: false, executor)
}
@JvmStatic
fun trigger(project: Project?, feature: ActionID) {
if (project == null) return
FUCounterUsageLogger.getInstance().logEvent(project, GROUP_ID, feature.name)
}
}
}
| apache-2.0 | 8d3a5299c3961a822ac0a027fc021f3e | 32.603774 | 140 | 0.713083 | 4.474874 | false | false | false | false |
rodm/teamcity-gradle-init-scripts-plugin | common/src/main/kotlin/com/github/rodm/teamcity/gradle/scripts/GradleInitScriptsPlugin.kt | 1 | 990 | /*
* Copyright 2017 Rod MacKenzie.
*
* 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.rodm.teamcity.gradle.scripts;
object GradleInitScriptsPlugin {
const val FEATURE_TYPE = "gradle-init-scripts"
const val INIT_SCRIPT_NAME = "initScriptName"
const val INIT_SCRIPT_CONTENT = "initScriptContent"
const val INIT_SCRIPT_NAME_PARAMETER = "gradle.init.script.name"
const val INIT_SCRIPT_CONTENT_PARAMETER = "gradle.init.script.content"
}
| apache-2.0 | 311db70d09591d70d533d5ae76da3ef6 | 32 | 75 | 0.740404 | 3.96 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit/src/main/kotlin/slatekit/docs/DocFiles.kt | 1 | 1583 | package slatekit.docs
import java.io.File
class DocFiles(val ext: String = "kt", val lang: String = "kotlin") {
fun buildComponentFolder(root: String, doc: Doc): String {
// s"${root}\src\lib\kotlin\Slate.Common\src\main\kotlin
val componentFolder = doc.namespace.replace(".", "/")
val result = "${root}/src/lib/$lang/${doc.proj}/src/main/$lang/${componentFolder}"
return result
}
fun buildComponentExamplePath(root: String, doc: Doc): String {
// s"${root}\src\lib\kotlin\Slate.Common\src\main\kotlin
val result = File(root, buildComponentExamplePathLink(doc))
return result.absolutePath
}
/**
* Path to the example file
*/
fun buildComponentExamplePathLink(doc: Doc): String {
// {root}/src/lib/kotlin/slatekit-examples/src/main/kotlin/slatekit/examples/Examples_Args.kt
val result = "src/lib/$lang/slatekit-examples/src/main/$lang/slatekit/examples/${doc.example}.$ext"
return result.replace("/", "/")
}
fun buildSourceFolder(proj: String, folder: String): String {
return when (proj) {
"common" -> "slatekit-common/src/main/${lang}/slatekit/common/${folder}"
"entities" -> "slatekit-entities/src/main/${lang}/slatekit/entities/${folder}"
"core" -> "slatekit-core/src/main/${lang}/slatekit/core/${folder}"
"cloud" -> "slatekit-cloud/src/main/${lang}/slatekit/cloud/${folder}"
"ext" -> "slatekit-ext/src/main/${lang}/slatekit/ext/${folder}"
else -> ""
}
}
} | apache-2.0 | aa1ef2387ae813673b6d8b3d5db3152d | 35.837209 | 107 | 0.617814 | 3.851582 | false | false | false | false |
codeka/wwmmo | server/src/main/kotlin/au/com/codeka/warworlds/server/world/Player.kt | 1 | 12077 | package au.com.codeka.warworlds.server.world
import au.com.codeka.warworlds.common.Log
import au.com.codeka.warworlds.common.debug.PacketDebug
import au.com.codeka.warworlds.common.proto.*
import au.com.codeka.warworlds.common.sim.*
import au.com.codeka.warworlds.server.concurrency.TaskRunner
import au.com.codeka.warworlds.server.concurrency.Threads
import au.com.codeka.warworlds.server.net.Connection
import au.com.codeka.warworlds.server.world.chat.ChatManager
import au.com.codeka.warworlds.server.world.chat.Participant.OnlineCallback
import au.com.codeka.warworlds.server.world.rpcs.SitReportRpcHandler
import com.google.common.collect.Lists
import java.lang.RuntimeException
import java.util.*
/** Represents a currently-connected player. */
class Player(private val connection: Connection,
private val helloPacket: HelloPacket,
private val empire: WatchableObject<Empire>) {
/** The list of [Sector]s this player is currently watching. */
private val watchedSectors = ArrayList<WatchableObject<Sector>>()
/** The [Star]s that we are currently watching. */
private val watchedStars: MutableMap<Long, WatchableObject<Star>> = HashMap()
/** The [WatchableObject.Watcher] which we'll be watching stars with. */
private val starWatcher: WatchableObject.Watcher<Star>
init {
log.setPrefix(String.format(Locale.US, "[%d %s]", empire.get().id, empire.get().display_name))
starWatcher = object : WatchableObject.Watcher<Star> {
override fun onUpdate(obj: WatchableObject<Star>) {
sendStarsUpdatedPacket(Lists.newArrayList(obj.get()))
}
}
TaskRunner.i.runTask(Runnable { onPostConnect() }, Threads.BACKGROUND)
}
fun onPacket(pkt: Packet) {
when {
pkt.watch_sectors != null -> onWatchSectorsPacket(pkt.watch_sectors!!)
pkt.modify_star != null -> onModifyStar(pkt.modify_star!!)
pkt.request_empire != null -> onRequestEmpire(pkt.request_empire!!)
pkt.chat_msgs != null -> onChatMessages(pkt.chat_msgs!!)
pkt.rpc != null -> onRpc(pkt.rpc!!)
else -> log.error("Unknown/unexpected packet. %s", PacketDebug.getPacketDebug(pkt))
}
}
/**
* This is called on a background thread when this [Player] is created. We'll send the
* client some updates they might be interested in.
*/
private fun onPostConnect() {
val startTime = System.nanoTime()
val stars = StarManager.i.getStarsForEmpire(empire.get().id)
log.debug("Fetched %d stars for empire %d in %dms", stars.size, empire.get().id,
(System.nanoTime() - startTime) / 1000000L)
// Of the player's stars, send them all the ones that have been updated since their
// last_simulation.
val updatedStars = ArrayList<Star>()
for (star in stars) {
if (helloPacket.our_star_last_simulation == null
|| (star.get().last_simulation != null
&& star.get().last_simulation!! > helloPacket.our_star_last_simulation!!)) {
updatedStars.add(star.get())
}
}
if (updatedStars.isNotEmpty()) {
log.debug("%d updated stars, sending update packet.", updatedStars.size)
sendStarsUpdatedPacket(updatedStars)
} else {
log.debug("No updated stars, not sending update packet.")
}
// Register this player with the chat system so that we get notified of messages.
ChatManager.i.connectPlayer(empire.get().id, helloPacket.last_chat_time!!, chatCallback)
}
/**
* Called when the client disconnects from us.
*/
fun onDisconnect() {
ChatManager.i.disconnectPlayer(empire.get().id)
clearWatchedStars()
synchronized(watchedSectors) { watchedSectors.clear() }
}
private fun onWatchSectorsPacket(pkt: WatchSectorsPacket) {
// TODO: if we're already watching some of these sectors, we can just keep watching those,
// Remove all our current watched stars
clearWatchedStars()
val stars: MutableList<Star> = ArrayList()
synchronized(watchedSectors) {
watchedSectors.clear()
for (sectorY in pkt.top!!..pkt.bottom!!) {
for (sectorX in pkt.left!!..pkt.right!!) {
val sector = SectorManager.i.getSector(SectorCoord(x = sectorX, y = sectorY))
SectorManager.i.verifyNativeColonies(sector)
watchedSectors.add(sector)
stars.addAll(sector.get().stars)
}
}
}
sendStarsUpdatedPacket(stars)
synchronized(watchedStars) {
for (star in stars) {
val watchableStar = StarManager.i.getStar(star.id)
if (watchableStar == null) {
// Huh?
log.warning("Got unexpected null star: %d", star.id)
continue
}
watchableStar.addWatcher(starWatcher)
watchedStars[star.id] = watchableStar
}
}
}
private fun onModifyStar(pkt: ModifyStarPacket) {
val star = StarManager.i.getStarOrError(pkt.star_id)
for (modification in pkt.modification) {
if (modification.empire_id == null || modification.empire_id != empire.get().id) {
// Update the modification's empire_id to be our own, since that's what'll be recorded
// in the database and we don't want this suspicious event to be recorded against the
// other person's empire.
val otherEmpireId = modification.empire_id
SuspiciousEventManager.i.addSuspiciousEvent(SuspiciousModificationException(
pkt.star_id,
modification.copy(empire_id = empire.get().id),
"Modification empire_id does not equal our own empire. empire_id=%d",
otherEmpireId))
return
}
if (modification.full_fuel != null && modification.full_fuel!!) {
// Clients shouldn't be trying to create fleets at all, but they should also not be trying
// fill them with fuel. That's suspicious.
SuspiciousEventManager.i.addSuspiciousEvent(SuspiciousModificationException(
pkt.star_id, modification, "Modification tried to set full_fuel to true."))
return
}
}
try {
StarManager.i.modifyStar(star, pkt.modification, StarModifier.EMPTY_LOG_HANDLER)
} catch (e: SuspiciousModificationException) {
SuspiciousEventManager.i.addSuspiciousEvent(e)
log.warning("Suspicious star modification.", e)
}
}
private fun onRequestEmpire(pkt: RequestEmpirePacket) {
val empires: MutableList<Empire> = ArrayList()
for (id in pkt.empire_id) {
val empire = EmpireManager.i.getEmpire(id)
if (empire != null) {
empires.add(empire.get())
}
}
connection.send(Packet(empire_details = EmpireDetailsPacket(empires = empires)))
}
private fun onChatMessages(pkt: ChatMessagesPacket) {
if (pkt.messages.size != 1) {
// TODO: suspicious, should be only one chat message.
log.error("Didn't get the expected 1 chat message. Got %d.", pkt.messages.size)
return
}
ChatManager.i.send(null /* TODO */, pkt.messages[0].copy(
date_posted = System.currentTimeMillis(),
empire_id = empire.get().id,
action = ChatMessage.MessageAction.Normal,
room_id = null /* TODO */))
}
private fun onRpc(pkt: RpcPacket) {
val resp = when {
pkt.sit_report_request != null -> SitReportRpcHandler().handle(empire, pkt)
else -> throw RuntimeException("Unexpected RPC: $pkt")
}
connection.send(Packet(rpc = resp.copy(id = pkt.id)))
}
private val chatCallback = object : OnlineCallback {
override fun onChatMessage(msgs: List<ChatMessage>) {
connection.send(Packet(chat_msgs = ChatMessagesPacket(messages = msgs)))
}
}
/**
* Send a [StarUpdatedPacket] with the given list of updated stars.
*
*
* The most important function of this method is sanitizing the stars so that enemy fleets
* are not visible (unless we have a colony/fleet as well, or there's a radar nearby).
*/
private fun sendStarsUpdatedPacket(updatedStars: MutableList<Star>) {
for (i in updatedStars.indices) {
updatedStars[i] = sanitizeStar(updatedStars[i])
}
connection.send(Packet(star_updated = StarUpdatedPacket(stars = updatedStars)))
}
/**
* Sanitizes the given star. Removes enemy fleets, etc, unless we have a colony or fleet of our
* own on there, or there's a radar nearby.
*/
// TODO: check for existence of radar buildings nearby
private fun sanitizeStar(star: Star): Star {
// If the star is a wormhole, don't sanitize it -- a wormhole is basically fleets in transit
// anyway.
if (star.classification == Star.Classification.WORMHOLE) {
return star
}
val myEmpireId = empire.get().id
// Now, figure out if we need to sanitize this star at all. Full sanitization means we need
// to remove all fleets and simplify colonies (no population, etc). Partial sanitization means
// we need to remove some fleets that have the cloaking upgrade.
var needFullSanitization = true
var needPartialSanitization = false
for (planet in star.planets) {
val colony = planet.colony
if (colony?.empire_id != null && colony.empire_id == myEmpireId) {
// If we have a colony on here, then we get the full version of the star.
needFullSanitization = false
break
}
}
for (fleet in star.fleets) {
if (FleetHelper.isOwnedBy(fleet, myEmpireId)) {
// If we have a fleet on here, then we also get the full version.
needFullSanitization = false
}
// if (FleetHelper.hasUpgrade(fleet, Design.UpgradeType.CLOAK)) {
// needPartialSanitization = true
// }
}
// If there's any non-us scout reports we'll need to do a partial sanitization.
for (scoutReport in star.scout_reports) {
if (scoutReport.empire_id != myEmpireId) {
needPartialSanitization = true
}
}
// TODO: if we have a radar nearby, then we get the full version of the star.
// If we need neither full nor partial sanitization, we can save a bunch of time.
if (!needFullSanitization && !needPartialSanitization) {
return star
}
// OK, now we know we need to sanitize this star.
val mutableStar = MutableStar.from(star)
// If need to do full sanitization, then do that.
if (needFullSanitization) {
run {
var i = 0
while (i < mutableStar.fleets.size) {
// Only remove if non-moving. TODO: also remove moving fleets if there's no radar nearby
if (mutableStar.fleets[i].state != Fleet.FLEET_STATE.MOVING) {
mutableStar.fleets.removeAt(i)
i--
}
i++
}
}
for (planet in mutableStar.planets) {
// Sanitize colonies. We can see that they exist, but we only get certain details.
val colony = planet.colony
if (colony != null) {
colony.population = 0f
colony.buildRequests = ArrayList()
colony.buildings = ArrayList()
colony.defenceBonus = 0f
colony.deltaEnergy = 0f
colony.deltaGoods = 0f
colony.deltaMinerals = 0f
colony.deltaPopulation = 0f
}
}
} else {
// Even if we don't need full sanitization, we'll remove any fleets that have the cloaking
// upgrade.
// TODO: implement me
}
// Remove any scout reports that are not for us. We'll just take the most recent scout report
// from our last scout.
var myScoutReport: ScoutReport? = null
for (scoutReport in mutableStar.scoutReports) {
if (EmpireHelper.isSameEmpire(scoutReport.empire_id, myEmpireId)) {
myScoutReport = scoutReport
break
}
}
mutableStar.scoutReports.clear()
if (myScoutReport != null) {
mutableStar.scoutReports.add(myScoutReport)
}
return mutableStar.build()
}
private fun clearWatchedStars() {
synchronized(watchedStars) {
for (star in watchedStars.values) {
star.removeWatcher(starWatcher)
}
watchedStars.clear()
}
}
companion object {
private val log = Log("Player")
}
} | mit | 056abf19049ab25335434f8a75655bef | 36.509317 | 98 | 0.663079 | 4.029696 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/inlineUtils.kt | 5 | 4671 | // 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.refactoring.inline
import com.intellij.codeInsight.TargetElementUtil
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.util.CommonRefactoringUtil
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.codeInliner.CodeToInline
import org.jetbrains.kotlin.idea.codeInliner.CodeToInlineBuilder
import org.jetbrains.kotlin.idea.intentions.ConvertReferenceToLambdaIntention
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
internal fun buildCodeToInline(
declaration: KtDeclaration,
bodyOrInitializer: KtExpression,
isBlockBody: Boolean,
editor: Editor?,
fallbackToSuperCall: Boolean,
): CodeToInline? {
val descriptor = declaration.unsafeResolveToDescriptor()
val builder = CodeToInlineBuilder(
targetCallable = descriptor as CallableDescriptor,
resolutionFacade = declaration.getResolutionFacade(),
originalDeclaration = declaration,
fallbackToSuperCall = fallbackToSuperCall,
)
val expressionMapper: (KtExpression) -> Pair<KtExpression?, List<KtExpression>>? = if (isBlockBody) {
fun(bodyOrInitializer: KtExpression): Pair<KtExpression?, List<KtExpression>>? {
bodyOrInitializer as KtBlockExpression
val statements = bodyOrInitializer.statements
val returnStatements = bodyOrInitializer.collectDescendantsOfType<KtReturnExpression> {
val function = it.getStrictParentOfType<KtFunction>()
if (function != null && function != declaration) return@collectDescendantsOfType false
it.getLabelName().let { label -> label == null || label == declaration.name }
}
val lastReturn = statements.lastOrNull() as? KtReturnExpression
if (returnStatements.any { it != lastReturn }) {
val message = RefactoringBundle.getCannotRefactorMessage(
if (returnStatements.size > 1)
KotlinBundle.message("error.text.inline.function.is.not.supported.for.functions.with.multiple.return.statements")
else
KotlinBundle.message("error.text.inline.function.is.not.supported.for.functions.with.return.statements.not.at.the.end.of.the.body")
)
CommonRefactoringUtil.showErrorHint(
declaration.project,
editor,
message,
KotlinBundle.message("title.inline.function"),
null
)
return null
}
return lastReturn?.returnedExpression to statements.dropLast(returnStatements.size)
}
} else {
{ it to emptyList() }
}
return builder.prepareCodeToInlineWithAdvancedResolution(
bodyOrExpression = bodyOrInitializer,
expressionMapper = expressionMapper,
)
}
fun Editor.findSimpleNameReference(): PsiReference? {
val reference = TargetElementUtil.findReference(this, caretModel.offset) ?: return null
return when {
reference.element.language != KotlinLanguage.INSTANCE -> reference
reference is KtSimpleNameReference -> reference
reference is PsiMultiReference -> reference.references.firstIsInstanceOrNull<KtSimpleNameReference>()
else -> null
}
}
fun findCallableConflictForUsage(usage: PsiElement): @NlsContexts.DialogMessage String? {
val usageParent = usage.parent as? KtCallableReferenceExpression ?: return null
if (usageParent.callableReference != usage) return null
if (ConvertReferenceToLambdaIntention.isApplicableTo(usageParent)) return null
return KotlinBundle.message("text.reference.cannot.be.converted.to.a.lambda")
}
| apache-2.0 | 3c31fe6b3233bb0ee367cb3297e49b27 | 45.247525 | 158 | 0.726611 | 5.295918 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/src/git4idea/ui/StashInfo.kt | 9 | 1542 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.ui
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcs.log.Hash
import com.intellij.vcs.log.util.VcsLogUtil
import org.jetbrains.annotations.Nls
import java.util.regex.Pattern
/**
* Information about one stash.
*
* @param stash stash codename (e.g. stash@{1})
*/
class StashInfo(val root: VirtualFile, val hash: Hash, val parentHashes: List<Hash>, val authorTime: Long,
val stash: @NlsSafe String, val branch: @NlsSafe String?, val message: @NlsSafe @Nls String) {
val text: @Nls String // The formatted text representation
init {
val sb = HtmlBuilder()
sb.append(HtmlChunk.text(stash).wrapWith("tt").bold()).append(": ")
if (branch != null) {
sb.append(HtmlChunk.text(branch).italic()).append(": ")
}
sb.append(message)
text = sb.wrapWithHtmlBody().toString()
}
override fun toString() = text
companion object {
val StashInfo.subject: @NlsSafe String
get() {
return Pattern.compile("^" + VcsLogUtil.HASH_REGEX.pattern()).matcher(message).replaceFirst("").trim()
}
val StashInfo.branchName: @NlsSafe String?
get() {
if (branch == null || branch.endsWith("(no branch)")) return null
return branch.split(" ").lastOrNull()
}
}
} | apache-2.0 | 40e17e441eb7a04527a5d536930fcca4 | 32.543478 | 120 | 0.688716 | 3.923664 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/mock/factories/PhotoFactory.kt | 1 | 607 | package com.kickstarter.mock.factories
import com.kickstarter.models.Photo
import com.kickstarter.models.Photo.Companion.builder
object PhotoFactory {
@JvmStatic
fun photo(): Photo {
val url =
"https://ksr-ugc.imgix.net/assets/012/032/069/46817a8c099133d5bf8b64aad282a696_original.png?crop=faces&w=1552&h=873&fit=crop&v=1463725702&auto=format&q=92&s=72501d155e4a5e399276632687c77959"
return builder()
.ed(url)
.full(url)
.little(url)
.med(url)
.small(url)
.thumb(url)
.build()
}
}
| apache-2.0 | 5d2344b03c54c7bef8ba035a704e019b | 29.35 | 202 | 0.622735 | 3.065657 | false | false | false | false |
vovagrechka/fucking-everything | attic/photlin/src/org/jetbrains/kotlin/js/translate/general/ModuleWrapperTranslation.kt | 1 | 8415 | /*
* Copyright 2010-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 org.jetbrains.kotlin.js.translate.general
import photlinc.*
import org.jetbrains.kotlin.js.backend.ast.*
import org.jetbrains.kotlin.js.translate.context.Namer
import org.jetbrains.kotlin.js.translate.context.StaticContext
import org.jetbrains.kotlin.js.translate.utils.JsAstUtils
import org.jetbrains.kotlin.serialization.js.ModuleKind
import photlin.*
import vgrechka.*
object ModuleWrapperTranslation {
@JvmStatic fun wrapIfNecessary(
moduleId: String, function: JsExpression, importedModules: List<StaticContext.ImportedModule>,
program: JsProgram, kind: ModuleKind
): List<JsStatement> {
// return listOf(JsExpressionStatement(JsInvocation(function)))
return when (kind) {
ModuleKind.AMD -> wrapAmd(moduleId, function, importedModules, program)
ModuleKind.COMMON_JS -> wrapCommonJs(function, importedModules, program)
ModuleKind.UMD -> wrapUmd(moduleId, function, importedModules, program)
ModuleKind.PLAIN -> wrapPlain(moduleId, function, importedModules, program)
}
}
private fun wrapUmd(
moduleId: String, function: JsExpression,
importedModules: List<StaticContext.ImportedModule>, program: JsProgram
): List<JsStatement> {
val scope = program.scope
val defineName = scope.declareName("define")
val exportsName = scope.declareName("exports")
val adapterBody = JsBlock()
val adapter = JsFunction(program.scope, adapterBody, "Adapter")
val rootName = adapter.scope.declareName("root")
val factoryName = adapter.scope.declareName("factory")
adapter.parameters += JsParameter(rootName)
adapter.parameters += JsParameter(factoryName)
val amdTest = JsAstUtils.and(JsAstUtils.typeOfIs(defineName.makeRef(), program.getStringLiteral("function")),
JsNameRef("amd", defineName.makeRef()))
val commonJsTest = JsAstUtils.typeOfIs(exportsName.makeRef(), program.getStringLiteral("object"))
val amdBody = JsBlock(wrapAmd(moduleId, factoryName.makeRef(), importedModules, program))
val commonJsBody = JsBlock(wrapCommonJs(factoryName.makeRef(), importedModules, program))
val plainInvocation = makePlainInvocation(moduleId, factoryName.makeRef(), importedModules, program)
val lhs: JsExpression = if (Namer.requiresEscaping(moduleId)) {
JsArrayAccess(rootName.makeRef(), program.getStringLiteral(moduleId))
}
else {
JsNameRef(scope.declareName(moduleId), rootName.makeRef())
}
val plainBlock = JsBlock()
for (importedModule in importedModules) {
plainBlock.statements += addModuleValidation(moduleId, program, importedModule)
}
plainBlock.statements += JsAstUtils.assignment(lhs, plainInvocation).makeStmt()
val selector = JsAstUtils.newJsIf(amdTest, amdBody, JsAstUtils.newJsIf(commonJsTest, commonJsBody, plainBlock))
adapterBody.statements += selector
return listOf(JsInvocation(adapter, phpThisRef(), function).makeStmt())
}
private fun wrapAmd(
moduleId: String, function: JsExpression,
importedModules: List<StaticContext.ImportedModule>, program: JsProgram
): List<JsStatement> {
val scope = program.scope
val defineName = scope.declareName("define")
val invocationArgs = listOf(
program.getStringLiteral(moduleId),
JsArrayLiteral(listOf(program.getStringLiteral("exports")) + importedModules.map { program.getStringLiteral(it.externalName) }),
function
)
val invocation = JsInvocation(defineName.makeRef(), invocationArgs)
return listOf(invocation.makeStmt())
}
private fun wrapCommonJs(
function: JsExpression,
importedModules: List<StaticContext.ImportedModule>,
program: JsProgram
): List<JsStatement> {
wtf("6111bd89-e891-4727-a744-a5243d5d9a17")
// val scope = program.scope
// val moduleName = scope.declareName("module")
// val requireName = scope.declareName("require")
//
// val invocationArgs = importedModules.map { JsInvocation(requireName.makeRef(), program.getStringLiteral(it.externalName)) }
// val invocation = JsInvocation(function, listOf(JsNameRef("exports", moduleName.makeRef())) + invocationArgs)
// return listOf(invocation.makeStmt())
}
private fun wrapPlain(
moduleId: String, function: JsExpression,
importedModules: List<StaticContext.ImportedModule>, program: JsProgram
): List<JsStatement> {
return (function as JsFunction).body.statements
// val invocation = makePlainInvocation(moduleId, function, importedModules, program)
// val statements = mutableListOf<JsStatement>()
//
// for (importedModule in importedModules) {
// statements += addModuleValidation(moduleId, program, importedModule)
// }
//
// statements += if (Namer.requiresEscaping(moduleId)) {
// JsAstUtils.assignment(makePlainModuleRef(moduleId, program), invocation).makeStmt()
// }
// else {
// JsAstUtils.newVar(program.rootScope.declareName(moduleId), invocation)
// }
//
// return statements
}
private fun addModuleValidation(
currentModuleId: String,
program: JsProgram,
module: StaticContext.ImportedModule
): JsStatement {
val moduleRef = makePlainModuleRef(module, program)
val moduleExistsCond = JsAstUtils.typeOfIs(moduleRef, program.getStringLiteral("undefined"))
val moduleNotFoundMessage = program.getStringLiteral(
"Error loading module '" + currentModuleId + "'. Its dependency '" + module.externalName + "' was not found. " +
"Please, check whether '" + module.externalName + "' is loaded prior to '" + currentModuleId + "'.")
val moduleNotFoundThrow = JsThrow(JsNew(JsNameRef("Error"), listOf<JsExpression>(moduleNotFoundMessage)))
return JsSingleLineComment("TODO: addModuleValidation 926e3274-bd4d-42de-9b2d-c118a9000532")
return JsIf(moduleExistsCond, JsBlock(moduleNotFoundThrow))
}
private fun makePlainInvocation(
moduleId: String,
function: JsExpression,
importedModules: List<StaticContext.ImportedModule>,
program: JsProgram
): JsInvocation {
val invocationArgs = importedModules.map { makePlainModuleRef(it, program) }
val moduleRef = makePlainModuleRef(moduleId, program)
val testModuleDefined = JsAstUtils.isset(moduleRef)
val selfArg = JsConditional(testModuleDefined, moduleRef.deepCopy(), JsObjectLiteral(false))
return JsInvocation(phpNameRef("call_user_func"), listOf(function, selfArg) + invocationArgs)
// return PHPInvocation(function, listOf(selfArg) + invocationArgs)
}
private fun makePlainModuleRef(module: StaticContext.ImportedModule, program: JsProgram): JsExpression {
return module.plainReference ?: makePlainModuleRef(module.externalName, program)
}
private fun makePlainModuleRef(moduleId: String, program: JsProgram): JsExpression {
// TODO: we could use `this.moduleName` syntax. However, this does not work for `kotlin` module in Rhino, since
// we run kotlin.js in a parent scope. Consider better solution
return if (Namer.requiresEscaping(moduleId)) {
JsArrayAccess(phpThisRef(), program.getStringLiteral(moduleId))
}
else {
val name = program.scope.declareName(moduleId)
name.makePHPVarRef()
}
}
}
| apache-2.0 | 06511756b34d9adae9398f6a48bf14bf | 44.983607 | 144 | 0.684611 | 4.588332 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/mediasend/v2/MediaSelectionRepository.kt | 1 | 14936 | package org.thoughtcrime.securesms.mediasend.v2
import android.content.Context
import android.net.Uri
import androidx.annotation.WorkerThread
import io.reactivex.rxjava3.core.Maybe
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.schedulers.Schedulers
import org.signal.core.util.BreakIteratorCompat
import org.signal.core.util.ThreadUtil
import org.signal.core.util.logging.Log
import org.signal.imageeditor.core.model.EditorModel
import org.thoughtcrime.securesms.contacts.paged.ContactSearchKey
import org.thoughtcrime.securesms.conversation.MessageSendType
import org.thoughtcrime.securesms.database.AttachmentDatabase.TransformProperties
import org.thoughtcrime.securesms.database.SignalDatabase
import org.thoughtcrime.securesms.database.ThreadDatabase
import org.thoughtcrime.securesms.database.model.Mention
import org.thoughtcrime.securesms.database.model.StoryType
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.keyvalue.StorySend
import org.thoughtcrime.securesms.mediasend.CompositeMediaTransform
import org.thoughtcrime.securesms.mediasend.ImageEditorModelRenderMediaTransform
import org.thoughtcrime.securesms.mediasend.Media
import org.thoughtcrime.securesms.mediasend.MediaRepository
import org.thoughtcrime.securesms.mediasend.MediaSendActivityResult
import org.thoughtcrime.securesms.mediasend.MediaTransform
import org.thoughtcrime.securesms.mediasend.MediaUploadRepository
import org.thoughtcrime.securesms.mediasend.SentMediaQualityTransform
import org.thoughtcrime.securesms.mediasend.VideoEditorFragment
import org.thoughtcrime.securesms.mediasend.VideoTrimTransform
import org.thoughtcrime.securesms.mms.MediaConstraints
import org.thoughtcrime.securesms.mms.OutgoingMediaMessage
import org.thoughtcrime.securesms.mms.OutgoingSecureMediaMessage
import org.thoughtcrime.securesms.mms.SentMediaQuality
import org.thoughtcrime.securesms.mms.Slide
import org.thoughtcrime.securesms.providers.BlobProvider
import org.thoughtcrime.securesms.recipients.Recipient
import org.thoughtcrime.securesms.scribbles.ImageEditorFragment
import org.thoughtcrime.securesms.sms.MessageSender
import org.thoughtcrime.securesms.sms.MessageSender.PreUploadResult
import org.thoughtcrime.securesms.stories.Stories
import org.thoughtcrime.securesms.util.MessageUtil
import java.util.Collections
import java.util.Optional
import java.util.concurrent.TimeUnit
private val TAG = Log.tag(MediaSelectionRepository::class.java)
class MediaSelectionRepository(context: Context) {
private val context: Context = context.applicationContext
private val mediaRepository = MediaRepository()
val uploadRepository = MediaUploadRepository(this.context)
val isMetered: Observable<Boolean> = MeteredConnectivity.isMetered(this.context)
fun populateAndFilterMedia(media: List<Media>, mediaConstraints: MediaConstraints, maxSelection: Int, isStory: Boolean): Single<MediaValidator.FilterResult> {
return Single.fromCallable {
val populatedMedia = mediaRepository.getPopulatedMedia(context, media)
MediaValidator.filterMedia(context, populatedMedia, mediaConstraints, maxSelection, isStory)
}.subscribeOn(Schedulers.io())
}
/**
* Tries to send the selected media, performing proper transformations for edited images and videos.
*/
fun send(
selectedMedia: List<Media>,
stateMap: Map<Uri, Any>,
quality: SentMediaQuality,
message: CharSequence?,
isSms: Boolean,
isViewOnce: Boolean,
singleContact: ContactSearchKey.RecipientSearchKey?,
contacts: List<ContactSearchKey.RecipientSearchKey>,
mentions: List<Mention>,
sendType: MessageSendType
): Maybe<MediaSendActivityResult> {
if (isSms && contacts.isNotEmpty()) {
throw IllegalStateException("Provided recipients to send to, but this is SMS!")
}
if (selectedMedia.isEmpty()) {
throw IllegalStateException("No selected media!")
}
val isSendingToStories = singleContact?.isStory == true || contacts.any { it.isStory }
val sentMediaQuality = if (isSendingToStories) SentMediaQuality.STANDARD else quality
return Maybe.create<MediaSendActivityResult> { emitter ->
val trimmedBody: String = if (isViewOnce) "" else getTruncatedBody(message?.toString()?.trim()) ?: ""
val trimmedMentions: List<Mention> = if (isViewOnce) emptyList() else mentions
val modelsToTransform: Map<Media, MediaTransform> = buildModelsToTransform(selectedMedia, stateMap, sentMediaQuality)
val oldToNewMediaMap: Map<Media, Media> = MediaRepository.transformMediaSync(context, selectedMedia, modelsToTransform)
val updatedMedia = oldToNewMediaMap.values.toList()
for (media in updatedMedia) {
Log.w(TAG, media.uri.toString() + " : " + media.transformProperties.map { t: TransformProperties -> "" + t.isVideoTrim }.orElse("null"))
}
val singleRecipient: Recipient? = singleContact?.let { Recipient.resolved(it.recipientId) }
val storyType: StoryType = if (singleRecipient?.isDistributionList == true) {
SignalDatabase.distributionLists.getStoryType(singleRecipient.requireDistributionListId())
} else {
StoryType.NONE
}
if (isSms || MessageSender.isLocalSelfSend(context, singleRecipient, isSms)) {
Log.i(TAG, "SMS or local self-send. Skipping pre-upload.")
emitter.onSuccess(MediaSendActivityResult.forTraditionalSend(singleRecipient!!.id, updatedMedia, trimmedBody, sendType, isViewOnce, trimmedMentions, StoryType.NONE))
} else {
val splitMessage = MessageUtil.getSplitMessage(context, trimmedBody, sendType.calculateCharacters(trimmedBody).maxPrimaryMessageSize)
val splitBody = splitMessage.body
if (splitMessage.textSlide.isPresent) {
val slide: Slide = splitMessage.textSlide.get()
uploadRepository.startUpload(
MediaBuilder.buildMedia(
uri = requireNotNull(slide.uri),
mimeType = slide.contentType,
date = System.currentTimeMillis(),
size = slide.fileSize,
borderless = slide.isBorderless,
videoGif = slide.isVideoGif
),
singleRecipient
)
}
val clippedVideosForStories: List<Media> = if (isSendingToStories) {
updatedMedia.filter {
Stories.MediaTransform.getSendRequirements(it) == Stories.MediaTransform.SendRequirements.REQUIRES_CLIP
}.map { media ->
Stories.MediaTransform.clipMediaToStoryDuration(media)
}.flatten()
} else emptyList()
uploadRepository.applyMediaUpdates(oldToNewMediaMap, singleRecipient)
uploadRepository.updateCaptions(updatedMedia)
uploadRepository.updateDisplayOrder(updatedMedia)
uploadRepository.getPreUploadResults { uploadResults ->
if (contacts.isNotEmpty()) {
sendMessages(contacts, splitBody, uploadResults, trimmedMentions, isViewOnce, clippedVideosForStories)
uploadRepository.deleteAbandonedAttachments()
emitter.onComplete()
} else if (uploadResults.isNotEmpty()) {
emitter.onSuccess(MediaSendActivityResult.forPreUpload(singleRecipient!!.id, uploadResults, splitBody, sendType, isViewOnce, trimmedMentions, storyType))
} else {
Log.w(TAG, "Got empty upload results! isSms: $isSms, updatedMedia.size(): ${updatedMedia.size}, isViewOnce: $isViewOnce, target: $singleContact")
emitter.onSuccess(MediaSendActivityResult.forTraditionalSend(singleRecipient!!.id, updatedMedia, trimmedBody, sendType, isViewOnce, trimmedMentions, storyType))
}
}
}
}.subscribeOn(Schedulers.io()).cast(MediaSendActivityResult::class.java)
}
private fun getTruncatedBody(body: String?): String? {
return if (!Stories.isFeatureEnabled() || body.isNullOrEmpty()) {
body
} else {
val iterator = BreakIteratorCompat.getInstance()
iterator.setText(body)
iterator.take(Stories.MAX_CAPTION_SIZE).toString()
}
}
fun deleteBlobs(media: List<Media>) {
media
.map(Media::getUri)
.filter(BlobProvider::isAuthority)
.forEach { BlobProvider.getInstance().delete(context, it) }
}
fun cleanUp(selectedMedia: List<Media>) {
deleteBlobs(selectedMedia)
uploadRepository.cancelAllUploads()
uploadRepository.deleteAbandonedAttachments()
}
fun isLocalSelfSend(recipient: Recipient?, isSms: Boolean): Boolean {
return MessageSender.isLocalSelfSend(context, recipient, isSms)
}
@WorkerThread
private fun buildModelsToTransform(
selectedMedia: List<Media>,
stateMap: Map<Uri, Any>,
quality: SentMediaQuality
): Map<Media, MediaTransform> {
val modelsToRender: MutableMap<Media, MediaTransform> = mutableMapOf()
selectedMedia.forEach {
val state = stateMap[it.uri]
if (state is ImageEditorFragment.Data) {
val model: EditorModel? = state.readModel()
if (model != null && model.isChanged) {
modelsToRender[it] = ImageEditorModelRenderMediaTransform(model)
}
}
if (state is VideoEditorFragment.Data && state.isDurationEdited) {
modelsToRender[it] = VideoTrimTransform(state)
}
if (quality == SentMediaQuality.HIGH) {
val existingTransform: MediaTransform? = modelsToRender[it]
modelsToRender[it] = if (existingTransform == null) {
SentMediaQualityTransform(quality)
} else {
CompositeMediaTransform(existingTransform, SentMediaQualityTransform(quality))
}
}
}
return modelsToRender
}
@WorkerThread
private fun sendMessages(
contacts: List<ContactSearchKey.RecipientSearchKey>,
body: String,
preUploadResults: Collection<PreUploadResult>,
mentions: List<Mention>,
isViewOnce: Boolean,
storyClips: List<Media>
) {
val nonStoryMessages: MutableList<OutgoingSecureMediaMessage> = ArrayList(contacts.size)
val storyPreUploadMessages: MutableMap<PreUploadResult, MutableList<OutgoingSecureMediaMessage>> = mutableMapOf()
val storyClipMessages: MutableList<OutgoingSecureMediaMessage> = ArrayList()
val distributionListPreUploadSentTimestamps: MutableMap<PreUploadResult, Long> = mutableMapOf()
val distributionListStoryClipsSentTimestamps: MutableMap<MediaKey, Long> = mutableMapOf()
for (contact in contacts) {
val recipient = Recipient.resolved(contact.recipientId)
val isStory = contact.isStory || recipient.isDistributionList
if (isStory && !recipient.isMyStory) {
SignalStore.storyValues().setLatestStorySend(StorySend.newSend(recipient))
}
val storyType: StoryType = when {
recipient.isDistributionList -> SignalDatabase.distributionLists.getStoryType(recipient.requireDistributionListId())
isStory -> StoryType.STORY_WITH_REPLIES
else -> StoryType.NONE
}
val message = OutgoingMediaMessage(
recipient,
body,
emptyList(),
if (recipient.isDistributionList) distributionListPreUploadSentTimestamps.getOrPut(preUploadResults.first()) { System.currentTimeMillis() } else System.currentTimeMillis(),
-1,
TimeUnit.SECONDS.toMillis(recipient.expiresInSeconds.toLong()),
isViewOnce,
ThreadDatabase.DistributionTypes.DEFAULT,
storyType,
null,
false,
null,
emptyList(),
emptyList(),
mentions,
mutableSetOf(),
mutableSetOf(),
null
)
if (isStory) {
preUploadResults.filterNot { result -> storyClips.any { it.uri == result.media.uri } }.forEach {
val list = storyPreUploadMessages[it] ?: mutableListOf()
list.add(
OutgoingSecureMediaMessage(message).withSentTimestamp(
if (recipient.isDistributionList) {
distributionListPreUploadSentTimestamps.getOrPut(it) { System.currentTimeMillis() }
} else {
System.currentTimeMillis()
}
)
)
storyPreUploadMessages[it] = list
// XXX We must do this to avoid sending out messages to the same recipient with the same
// sentTimestamp. If we do this, they'll be considered dupes by the receiver.
ThreadUtil.sleep(5)
}
storyClips.forEach {
storyClipMessages.add(
OutgoingSecureMediaMessage(
OutgoingMediaMessage(
recipient,
body,
listOf(MediaUploadRepository.asAttachment(context, it)),
if (recipient.isDistributionList) distributionListStoryClipsSentTimestamps.getOrPut(it.asKey()) { System.currentTimeMillis() } else System.currentTimeMillis(),
-1,
TimeUnit.SECONDS.toMillis(recipient.expiresInSeconds.toLong()),
isViewOnce,
ThreadDatabase.DistributionTypes.DEFAULT,
storyType,
null,
false,
null,
emptyList(),
emptyList(),
mentions,
mutableSetOf(),
mutableSetOf(),
null
)
)
)
// XXX We must do this to avoid sending out messages to the same recipient with the same
// sentTimestamp. If we do this, they'll be considered dupes by the receiver.
ThreadUtil.sleep(5)
}
} else {
nonStoryMessages.add(OutgoingSecureMediaMessage(message))
// XXX We must do this to avoid sending out messages to the same recipient with the same
// sentTimestamp. If we do this, they'll be considered dupes by the receiver.
ThreadUtil.sleep(5)
}
}
if (nonStoryMessages.isNotEmpty()) {
Log.d(TAG, "Sending ${nonStoryMessages.size} preupload messages to chats")
MessageSender.sendMediaBroadcast(
context,
nonStoryMessages,
preUploadResults,
true
)
}
if (storyPreUploadMessages.isNotEmpty()) {
Log.d(TAG, "Sending ${storyPreUploadMessages.size} preload messages to stories")
storyPreUploadMessages.forEach { (preUploadResult, messages) ->
MessageSender.sendMediaBroadcast(context, messages, Collections.singleton(preUploadResult), nonStoryMessages.isEmpty())
}
}
if (storyClipMessages.isNotEmpty()) {
Log.d(TAG, "Sending ${storyClipMessages.size} video clip messages to stories")
MessageSender.sendStories(context, storyClipMessages, null, null)
}
}
private fun Media.asKey(): MediaKey {
return MediaKey(this, this.transformProperties)
}
data class MediaKey(val media: Media, val mediaTransform: Optional<TransformProperties>)
}
| gpl-3.0 | 96a55a246ed086e36ebacadab6eb6fe8 | 40.604457 | 180 | 0.710096 | 4.720607 | false | false | false | false |
androidx/androidx | compose/runtime/runtime-lint/src/main/java/androidx/compose/runtime/lint/RuntimeIssueRegistry.kt | 3 | 2101 | /*
* 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.
*/
@file:Suppress("UnstableApiUsage")
package androidx.compose.runtime.lint
import com.android.tools.lint.client.api.IssueRegistry
import com.android.tools.lint.client.api.Vendor
import com.android.tools.lint.detector.api.CURRENT_API
/**
* [IssueRegistry] containing runtime specific lint issues.
*/
class RuntimeIssueRegistry : IssueRegistry() {
// Tests are run with this version. We ensure that with ApiLintVersionsTest
override val api = 13
override val minApi = CURRENT_API
override val issues get() = listOf(
ComposableCoroutineCreationDetector.CoroutineCreationDuringComposition,
ComposableFlowOperatorDetector.FlowOperatorInvokedInComposition,
ComposableLambdaParameterDetector.ComposableLambdaParameterNaming,
ComposableLambdaParameterDetector.ComposableLambdaParameterPosition,
ComposableNamingDetector.ComposableNaming,
ComposableStateFlowValueDetector.StateFlowValueCalledInComposition,
CompositionLocalNamingDetector.CompositionLocalNaming,
MutableCollectionMutableStateDetector.MutableCollectionMutableState,
ProduceStateDetector.ProduceStateDoesNotAssignValue,
RememberDetector.RememberReturnType,
UnrememberedStateDetector.UnrememberedState
)
override val vendor = Vendor(
vendorName = "Jetpack Compose",
identifier = "androidx.compose.runtime",
feedbackUrl = "https://issuetracker.google.com/issues/new?component=612128"
)
}
| apache-2.0 | a2e93ae14661cb286ad12a72de9534aa | 41.02 | 83 | 0.769158 | 4.87471 | false | false | false | false |
djkovrik/YapTalker | app/src/main/java/com/sedsoftware/yaptalker/presentation/feature/settings/SettingsFragment.kt | 1 | 2382 | package com.sedsoftware.yaptalker.presentation.feature.settings
import android.content.SharedPreferences
import android.os.Bundle
import android.preference.Preference
import android.preference.PreferenceCategory
import android.preference.PreferenceFragment
import android.preference.PreferenceGroup
import com.afollestad.materialdialogs.prefs.MaterialListPreference
import com.sedsoftware.yaptalker.R
import com.sedsoftware.yaptalker.presentation.extensions.string
import com.sedsoftware.yaptalker.presentation.feature.blacklist.BlacklistActivity
class SettingsFragment : PreferenceFragment(), SharedPreferences.OnSharedPreferenceChangeListener {
private val sharedPreferences by lazy {
preferenceScreen.sharedPreferences
}
private val prefScreen by lazy {
preferenceScreen
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
addPreferencesFromResource(R.xml.preferences)
val count = prefScreen.preferenceCount
for (i in 0 until count) {
val category = prefScreen.getPreference(i)
if (category is PreferenceCategory) {
val group = category as PreferenceGroup
val groupCount = group.preferenceCount
(0 until groupCount)
.map { group.getPreference(it) }
.forEach { setListPreferenceSummary(sharedPreferences, it) }
}
}
sharedPreferences.registerOnSharedPreferenceChangeListener(this)
findPreference(activity?.string(R.string.pref_key_blacklist))
.setOnPreferenceClickListener {
startActivity(BlacklistActivity.getIntent(activity))
true
}
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
val preference = findPreference(key)
preference?.let { setListPreferenceSummary(sharedPreferences, preference) }
}
private fun setListPreferenceSummary(sharedPreferences: SharedPreferences, pref: Preference) {
if (pref is MaterialListPreference) {
val value = sharedPreferences.getString(pref.getKey(), "")
val index = pref.findIndexOfValue(value)
if (index >= 0) {
pref.setSummary(pref.entries[index])
}
}
}
}
| apache-2.0 | 5d175e3e0d17f59741acbd287124e002 | 34.029412 | 99 | 0.697733 | 5.753623 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/new/tests/testData/newJ2k/field/needInitializer.kt | 13 | 262 | class Init {
var field1 = "str"
var field2: String? = null
var field3 = 1
var field4 = 0
init {
val prop1: String
prop1 = "aaa"
var prop2: String
val prop3: Int
prop3 = 1
var prop4: Int
}
} | apache-2.0 | 7e20f2b926df7a7db7255cc16b7d291c | 16.533333 | 30 | 0.48855 | 3.493333 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/sequence/src/org/jetbrains/kotlin/idea/debugger/sequence/trace/impl/handler/OnEachCall.kt | 4 | 1303 | // Copyright 2000-2022 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.debugger.sequence.trace.impl.handler
import com.intellij.debugger.streams.trace.impl.handler.type.GenericType
import com.intellij.debugger.streams.wrapper.CallArgument
import com.intellij.debugger.streams.wrapper.IntermediateStreamCall
import com.intellij.debugger.streams.wrapper.StreamCallType
import com.intellij.debugger.streams.wrapper.impl.CallArgumentImpl
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.debugger.sequence.trace.dsl.KotlinSequenceTypes
class OnEachCall(private val elementsType: GenericType, lambda: String) : IntermediateStreamCall {
private val args: List<CallArgument>
init {
args = listOf(CallArgumentImpl(KotlinSequenceTypes.ANY.genericTypeName, lambda))
}
override fun getArguments(): List<CallArgument> = args
override fun getName(): String = "onEach"
override fun getType(): StreamCallType = StreamCallType.INTERMEDIATE
override fun getTextRange(): TextRange = TextRange.EMPTY_RANGE
override fun getTypeBefore(): GenericType = elementsType
override fun getTypeAfter(): GenericType = elementsType
} | apache-2.0 | c99b2046835de8663302547e03f09e80 | 41.064516 | 158 | 0.797391 | 4.637011 | false | true | false | false |
GunoH/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/ExternalSystemEventDispatcher.kt | 9 | 3742 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.execution
import com.intellij.build.BuildEventDispatcher
import com.intellij.build.BuildProgressListener
import com.intellij.build.events.BuildEvent
import com.intellij.build.output.BuildOutputInstantReaderImpl
import com.intellij.build.output.BuildOutputParser
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId
import com.intellij.util.SmartList
import org.jetbrains.annotations.ApiStatus
import java.util.concurrent.CompletableFuture
import java.util.function.Consumer
@ApiStatus.Experimental
class ExternalSystemEventDispatcher(taskId: ExternalSystemTaskId,
progressListener: BuildProgressListener?,
appendOutputToMainConsole: Boolean) : BuildEventDispatcher {
constructor(taskId: ExternalSystemTaskId, progressListener: BuildProgressListener?) : this(taskId, progressListener, true)
private lateinit var outputMessageDispatcher: ExternalSystemOutputMessageDispatcher
private var isStdOut: Boolean = true
override fun setStdOut(stdOut: Boolean) {
this.isStdOut = stdOut
outputMessageDispatcher.stdOut = stdOut
}
init {
val buildOutputParsers = SmartList<BuildOutputParser>()
if (progressListener != null) {
ExternalSystemOutputParserProvider.EP_NAME.extensions.forEach {
if (taskId.projectSystemId == it.externalSystemId) {
buildOutputParsers.addAll(it.getBuildOutputParsers(taskId))
}
}
var foundFactory: ExternalSystemOutputDispatcherFactory? = null
EP_NAME.extensions.forEach {
if (taskId.projectSystemId == it.externalSystemId) {
if (foundFactory != null) {
throw RuntimeException("'" + EP_NAME.name + "' extension should be one per external system")
}
foundFactory = it
}
}
outputMessageDispatcher = foundFactory?.create(taskId, progressListener, appendOutputToMainConsole, buildOutputParsers)
?: DefaultOutputMessageDispatcher(taskId, progressListener, buildOutputParsers)
}
}
override fun onEvent(buildId: Any, event: BuildEvent) {
outputMessageDispatcher.onEvent(buildId, event)
}
override fun invokeOnCompletion(consumer: Consumer<in Throwable?>) {
outputMessageDispatcher.invokeOnCompletion(consumer)
}
override fun append(csq: CharSequence) = apply {
outputMessageDispatcher.append(csq)
}
override fun append(csq: CharSequence, start: Int, end: Int) = apply {
outputMessageDispatcher.append(csq, start, end)
}
override fun append(c: Char) = apply {
outputMessageDispatcher.append(c)
}
override fun close() {
outputMessageDispatcher.close()
}
companion object {
private val EP_NAME = ExtensionPointName.create<ExternalSystemOutputDispatcherFactory>("com.intellij.externalSystemOutputDispatcher")
}
private class DefaultOutputMessageDispatcher(
buildProgressListener: BuildProgressListener,
val outputReader: BuildOutputInstantReaderImpl
) : AbstractOutputMessageDispatcher(buildProgressListener),
Appendable by outputReader {
constructor(buildId: Any, buildProgressListener: BuildProgressListener, parsers: List<BuildOutputParser>) :
this(buildProgressListener, BuildOutputInstantReaderImpl(buildId, buildId, buildProgressListener, parsers))
override var stdOut = true
override fun closeAndGetFuture(): CompletableFuture<Unit> {
return outputReader.closeAndGetFuture()
}
}
}
| apache-2.0 | 0212a4b80db3d9a6656b8ebdd4622e10 | 38.389474 | 140 | 0.750935 | 5.292786 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/gradle/gradle/src/org/jetbrains/kotlin/idea/gradle/configuration/GradlePropertiesFileFacade.kt | 7 | 2613 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradle.configuration
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.IntellijInternalApi
import com.intellij.openapi.vfs.LocalFileSystem
import org.jetbrains.plugins.gradle.model.ExternalProject
import java.util.*
import kotlin.io.path.Path
import kotlin.io.path.exists
import kotlin.io.path.readText
import kotlin.io.path.writeText
@IntellijInternalApi
class GradlePropertiesFileFacade(private val baseDir: String) {
fun readProperty(propertyName: String): String? {
val baseVirtualDir = LocalFileSystem.getInstance().findFileByPath(baseDir) ?: return null
for (propertyFileName in GRADLE_PROPERTY_FILES) {
val propertyFile = baseVirtualDir.findChild(propertyFileName) ?: continue
Properties().also { it.load(propertyFile.inputStream) }.getProperty(propertyName)?.let {
return it
}
}
return null
}
fun addCodeStyleProperty(value: String) {
addProperty(KOTLIN_CODE_STYLE_GRADLE_SETTING, value)
}
fun addNotImportedCommonSourceSetsProperty() {
addProperty(KOTLIN_NOT_IMPORTED_COMMON_SOURCE_SETS_SETTING, true.toString())
}
private fun addProperty(key: String, value: String) {
val projectPropertiesPath = Path(baseDir, GRADLE_PROPERTIES_FILE_NAME)
val keyValue = "$key=$value"
val updatedText = if (projectPropertiesPath.exists()) {
projectPropertiesPath.readText() + System.lineSeparator() + keyValue
} else {
keyValue
}
projectPropertiesPath.writeText(updatedText)
}
companion object {
fun forProject(project: Project) = GradlePropertiesFileFacade(project.basePath!!)
fun forExternalProject(externalProject: ExternalProject) = GradlePropertiesFileFacade(externalProject.projectDir.path)
const val KOTLIN_CODE_STYLE_GRADLE_SETTING = "kotlin.code.style"
const val KOTLIN_NOT_IMPORTED_COMMON_SOURCE_SETS_SETTING = "kotlin.import.noCommonSourceSets"
private const val GRADLE_PROPERTIES_FILE_NAME = "gradle.properties"
private const val GRADLE_PROPERTIES_LOCAL_FILE_NAME = "local.properties"
private val GRADLE_PROPERTY_FILES = listOf(GRADLE_PROPERTIES_LOCAL_FILE_NAME, GRADLE_PROPERTIES_FILE_NAME)
}
}
fun readGradleProperty(project: Project, key: String): String? {
return GradlePropertiesFileFacade.forProject(project).readProperty(key)
} | apache-2.0 | 60a18c4f2ccc0828e38b9bde70fdbd05 | 35.305556 | 126 | 0.724837 | 4.560209 | false | false | false | false |
GunoH/intellij-community | python/src/com/jetbrains/python/packaging/common/util.kt | 1 | 1703 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.jetbrains.python.packaging.common
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.jetbrains.python.packaging.PyPIPackageRanking
import com.jetbrains.python.packaging.conda.CondaPackageManager
import com.jetbrains.python.packaging.management.PythonPackageManager
import com.jetbrains.python.packaging.pip.PipPythonPackageManager
import com.jetbrains.python.sdk.PythonSdkUtil
import org.jetbrains.annotations.ApiStatus
object PackageManagerHolder {
private val cache = mutableMapOf<String, PythonPackageManager>()
fun forSdk(project: Project, sdk: Sdk): PythonPackageManager? {
if (sdk.homePath in cache) return cache[sdk.homePath] // todo[akniazev] replace with sdk key
val manager = when {
PythonSdkUtil.isConda(sdk) -> CondaPackageManager(project, sdk) // todo[akniazev] extract to an extension point
else -> PipPythonPackageManager(project, sdk)
}
cache[sdk.homePath!!] = manager
return manager
}
}
@ApiStatus.Experimental
interface PythonPackageManagementListener {
fun packagesChanged(sdk: Sdk)
}
internal val RANKING_AWARE_PACKAGE_NAME_COMPARATOR: java.util.Comparator<String> = Comparator { name1, name2 ->
val ranking = PyPIPackageRanking.packageRank
val rank1 = ranking[name1.lowercase()]
val rank2 = ranking[name2.lowercase()]
return@Comparator when {
rank1 != null && rank2 == null -> -1
rank1 == null && rank2 != null -> 1
rank1 != null && rank2 != null -> rank2 - rank1
else -> String.CASE_INSENSITIVE_ORDER.compare(name1, name2)
}
} | apache-2.0 | 3b5f248ac8d648c5b0c6ee4001a9043f | 37.727273 | 120 | 0.76101 | 3.969697 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/editor/LazyKtBlockExpressionTest.kt | 4 | 1493 | // Copyright 2000-2022 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.editor
import com.intellij.testFramework.EditorTestUtil
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
@RunWith(JUnit38ClassRunner::class)
class LazyKtBlockExpressionTest : LazyElementTypeTestBase<KtBlockExpression>(KtBlockExpression::class.java) {
fun testSimpleReparse() = noReparse(inIf(" { a<caret>b }"), 'c')
fun testSimpleNotReparse() = reparse(inIf(" { a-<caret>b }"), '>')
fun testSplitArrow() = reparse(inIf("{ a: Int -<caret>> }"), ' ')
fun testDeleteArrow() = reparse(inIf("{ a: Int -<caret>> }"), EditorTestUtil.BACKSPACE_FAKE_CHAR)
fun testImbalance1() = noReparse(inIf(" { {}<caret> }"), EditorTestUtil.BACKSPACE_FAKE_CHAR)
fun testImbalance2() = noReparse(inIf(" { }<caret>"), EditorTestUtil.BACKSPACE_FAKE_CHAR)
fun testBlockWithArrowInside() = noReparse(inIf(" { { a: Int -<caret> a } }"), '>')
fun testBlockWithArrowInside2() = noReparse(inIf(" { } a: Int -<caret> a } }"), '>')
fun testBlockWithCommaAsLambdaArgument() = reparse(inIf(" { a<caret> }"), ',')
fun testBlockWithCommaAsBlockContent() = noReparse(inIf(" { a.b<caret> c.d = 3 }"), ',')
fun testBlockWithCommaAsBlockContent2() = noReparse(inIf(" { a(b<caret> c) }"), ',')
} | apache-2.0 | 8b388c8aa492cd3f909afdce2941c0e1 | 42.941176 | 158 | 0.693905 | 3.529551 | false | true | false | false |
Fotoapparat/Fotoapparat | fotoapparat/src/main/java/io/fotoapparat/parameter/camera/apply/CameraParametersApplicator.kt | 1 | 2571 | @file:Suppress("DEPRECATION")
package io.fotoapparat.parameter.camera.apply
import android.hardware.Camera
import io.fotoapparat.parameter.*
import io.fotoapparat.parameter.camera.CameraParameters
import io.fotoapparat.parameter.camera.convert.toCode
/**
* Applies a new set of [CameraParameters] to existing [Camera.Parameters].
*
* @receiver The existing [Camera.Parameters]
* @param parameters A new set of [CameraParameters].
*
* @return Same [Camera.Parameters] object which was passed, but filled with new parameters.
*/
internal fun CameraParameters.applyInto(parameters: Camera.Parameters): Camera.Parameters {
this tryApplyInto parameters
return parameters
}
private infix fun CameraParameters.tryApplyInto(parameters: Camera.Parameters) {
flashMode applyInto parameters
focusMode applyInto parameters
jpegQuality applyJpegQualityInto parameters
exposureCompensation applyExposureCompensationInto parameters
antiBandingMode applyInto parameters
previewFpsRange applyInto parameters
previewResolution applyPreviewInto parameters
sensorSensitivity applySensitivityInto parameters
pictureResolution applyPictureResolutionInto parameters
}
private infix fun Flash.applyInto(parameters: Camera.Parameters) {
parameters.flashMode = toCode()
}
private infix fun FocusMode.applyInto(parameters: Camera.Parameters) {
parameters.focusMode = toCode()
}
private infix fun Int.applyJpegQualityInto(parameters: Camera.Parameters) {
parameters.jpegQuality = this
}
private infix fun Int.applyExposureCompensationInto(parameters: Camera.Parameters) {
parameters.exposureCompensation = this
}
private infix fun AntiBandingMode.applyInto(parameters: Camera.Parameters) {
parameters.antibanding = toCode()
}
private infix fun FpsRange.applyInto(parameters: Camera.Parameters) {
parameters.setPreviewFpsRange(min, max)
}
private infix fun Int?.applySensitivityInto(parameters: Camera.Parameters) {
this?.let { sensitivity ->
parameters.findSensitivityKey()?.let { key ->
parameters.set(key, sensitivity)
}
}
}
private infix fun Resolution.applyPreviewInto(parameters: Camera.Parameters) {
parameters.setPreviewSize(width, height)
}
private infix fun Resolution.applyPictureResolutionInto(parameters: Camera.Parameters) {
parameters.setPictureSize(width, height)
}
private fun Camera.Parameters.findSensitivityKey() = currentSensitivityKeys.find { get(it) != null }
private val currentSensitivityKeys = listOf("iso", "iso-speed", "nv-picture-iso")
| apache-2.0 | cbdf90046b75a8d8b668cd852070a258 | 31.961538 | 100 | 0.78452 | 4.417526 | false | false | false | false |
smmribeiro/intellij-community | build/tasks/src/org/jetbrains/intellij/build/tasks/mac.kt | 1 | 2421 | // 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.
@file:Suppress("ReplaceGetOrSet", "ReplaceNegatedIsEmptyWithIsNotEmpty")
package org.jetbrains.intellij.build.tasks
import io.opentelemetry.api.common.AttributeKey
import org.jetbrains.intellij.build.io.writeNewFile
import java.nio.file.Path
fun buildMacZip(targetFile: Path,
zipRoot: String,
productJson: ByteArray,
allDist: Path,
macDist: Path,
extraFiles: Collection<Map.Entry<Path, String>>,
executableFilePatterns: List<String>,
compressionLevel: Int) {
tracer.spanBuilder("build zip archive for macOS")
.setAttribute("file", targetFile.toString())
.setAttribute("zipRoot", zipRoot)
.setAttribute(AttributeKey.stringArrayKey("executableFilePatterns"), executableFilePatterns)
.startSpan()
.use {
val fs = targetFile.fileSystem
val patterns = executableFilePatterns.map { fs.getPathMatcher("glob:$it") }
val entryCustomizer: EntryCustomizer = { entry, _, relativeFile ->
if (patterns.any { it.matches(relativeFile) }) {
entry.unixMode = executableFileUnixMode
}
}
writeNewFile(targetFile) { targetFileChannel ->
org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream(targetFileChannel).use { zipOutStream ->
zipOutStream.setLevel(compressionLevel)
zipOutStream.entry("$zipRoot/Resources/product-info.json", productJson)
val fileFilter: (Path, Path) -> Boolean = { sourceFile, relativeFile ->
val path = relativeFile.toString()
if (path.endsWith(".txt") && !path.contains('/')) {
zipOutStream.entry("$zipRoot/Resources/$relativeFile", sourceFile)
false
}
else {
true
}
}
zipOutStream.dir(allDist, "$zipRoot/", fileFilter = fileFilter, entryCustomizer = entryCustomizer)
zipOutStream.dir(macDist, "$zipRoot/", fileFilter = fileFilter, entryCustomizer = entryCustomizer)
for ((file, relativePath) in extraFiles) {
zipOutStream.entry("$zipRoot/$relativePath${if (relativePath.isEmpty()) "" else "/"}${file.fileName}", file)
}
}
}
}
} | apache-2.0 | 33c29468dc0c9056b4851e22096bf6ca | 40.050847 | 158 | 0.645188 | 5.002066 | false | false | false | false |
myunusov/maxur-mserv | maxur-mserv-core/src/main/kotlin/org/maxur/mserv/frame/domain/BaseService.kt | 1 | 3536 | package org.maxur.mserv.frame.domain
import org.maxur.mserv.core.command.Event
import org.maxur.mserv.frame.event.MicroserviceFailedEvent
import org.maxur.mserv.frame.kotlin.Locator
import kotlin.reflect.KClass
import kotlin.reflect.KFunction
import kotlin.reflect.KParameter
import kotlin.reflect.KType
import kotlin.reflect.full.isSubclassOf
/** The Base Service */
abstract class BaseService(
/** The Service Locator */
val locator: Locator) {
/** The hook on start */
var afterStart: MutableList<KFunction<Any>> = ArrayList()
/** The hook on stop */
var beforeStop: MutableList<KFunction<Any>> = ArrayList()
/** The hook on error */
var onError: MutableList<KFunction<Any>> = ArrayList()
protected var state: BaseService.State = BaseService.State.STOPPED
private set
/** The service name */
abstract var name: String
/** Start this Service */
fun start() = state.start(this)
/** Immediately shuts down this Service. */
fun stop() = state.stop(this)
/** Shutdown this service. */
protected abstract fun shutdown(): List<Event>
/** Launch this service. */
protected abstract fun launch(): List<Event>
/** Represent State of micro-service */
enum class State {
/** Running application */
STARTED {
/** {@inheritDoc} */
override fun start(service: BaseService) = emptyList<Event>()
/** {@inheritDoc} */
override fun stop(service: BaseService) = shutdown(service)
},
/** Stop application */
STOPPED {
/** {@inheritDoc} */
override fun start(service: BaseService) = launch(service)
/** {@inheritDoc} */
override fun stop(service: BaseService) = emptyList<Event>()
};
/** Start Service */
abstract fun start(service: BaseService): List<Event>
/** Stop Service */
abstract fun stop(service: BaseService): List<Event>
protected fun shutdown(service: BaseService): List<Event> = try {
service.beforeStop.forEach { call(it, service) }
val events = service.shutdown()
service.state = STOPPED
events
} catch (e: Exception) {
handleError(service, e)
}
protected fun launch(service: BaseService): List<Event> = try {
val events = service.launch()
service.state = STARTED
service.afterStart.forEach { call(it, service) }
events
} catch (e: Exception) {
handleError(service, e)
}
private fun handleError(service: BaseService, error: Exception): List<Event> {
if (service.onError.isEmpty())
throw error
service.onError.forEach { call(it, service, error) }
return listOf(MicroserviceFailedEvent())
}
private fun call(func: KFunction<Any>, vararg values: Any) {
val args = func.parameters.map { match(it, *values) }.toTypedArray()
func.call(*args)
}
private fun match(param: KParameter, vararg values: Any): Any? =
values.firstOrNull { isApplicable(param, it) } ?: Locator.bean(param)
@Suppress("UNCHECKED_CAST")
private fun isApplicable(type: KType, clazz: KClass<out Any>) =
clazz.isSubclassOf(type.classifier as KClass<Any>)
private fun isApplicable(param: KParameter, value: Any) = isApplicable(param.type, value::class)
}
} | apache-2.0 | 5d90c6ab8b50ad92ce7a28006d35cfa9 | 32.685714 | 104 | 0.611991 | 4.568475 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/search/service/Sampler.kt | 1 | 4869 | package org.evomaster.core.search.service
import com.google.inject.Inject
import org.evomaster.core.EMConfig
import org.evomaster.core.search.Action
import org.evomaster.core.search.EvaluatedIndividual
import org.evomaster.core.search.Individual
import org.evomaster.core.search.gene.optional.OptionalGene
import org.evomaster.core.search.tracer.TrackOperator
import org.slf4j.Logger
import org.slf4j.LoggerFactory
abstract class Sampler<T> : TrackOperator where T : Individual {
companion object {
private val log: Logger = LoggerFactory.getLogger(Sampler::class.java)
}
@Inject
protected lateinit var randomness: Randomness
@Inject
protected lateinit var config: EMConfig
@Inject
protected lateinit var time : SearchTimeController
@Inject
protected lateinit var apc: AdaptiveParameterControl
@Inject
protected lateinit var searchGlobalState: SearchGlobalState
/**
* Set of available actions that can be used to define a test case
*
* Key -> action name
*
* Value -> an action
*/
protected val actionCluster: MutableMap<String, Action> = mutableMapOf()
/**
* Create a new individual. Usually each call to this method
* will create a new, different individual, but there is no
* hard guarantee
*/
fun sample(forceRandomSample: Boolean = false): T {
if (log.isTraceEnabled){
log.trace("sampler will be applied")
}
val ind = if (forceRandomSample) {
sampleAtRandom()
} else if (hasSpecialInit() || randomness.nextBoolean(config.probOfSmartSampling)) {
// If there is still special init set, sample from that, otherwise depen on probability
smartSample()
} else {
sampleAtRandom()
}
samplePostProcessing(ind)
org.evomaster.core.Lazy.assert { ind.verifyValidity(); true }
return ind
}
/**
* Sample a new individual at random, but still satisfying all given constraints.
*
* Note: must guarantee to setup the [searchGlobalState] in this new individual
*/
protected abstract fun sampleAtRandom(): T
open fun samplePostProcessing(ind: T){
val state = ind.searchGlobalState ?: return
val time = state.time.percentageUsedBudget()
ind.seeAllActions().forEach { a ->
val allGenes = a.seeTopGenes().flatMap { it.flatView() }
allGenes.filterIsInstance<OptionalGene>()
.filter { it.searchPercentageActive < time }
.forEach { it.forbidSelection() }
}
}
/**
* Create a new individual, but not fully at random, but rather
* by using some domain-knowledge.
*
* Note: must guarantee to setup the [searchGlobalState] in this new individual
*/
protected open fun smartSample(): T {
//unless this method is overridden, just sample at random
return sampleAtRandom()
}
fun numberOfDistinctActions() = actionCluster.size
/**
* When the search starts, there might be some predefined individuals
* that we can sample. But we just need to sample each of them just once.
* The [smartSample] must first pick from this set.
*
* @return false if there is not left predefined individual to sample
*/
open fun hasSpecialInit() = false
open fun resetSpecialInit() {}
fun seeAvailableActions(): List<Action> {
return actionCluster.entries
.asSequence()
.sortedBy { e -> e.key }
.map { e -> e.value }
.toList()
}
/**
* this can be used to provide feedback to sampler regarding a fitness of the sampled individual (i.e., [evi]).
*/
open fun feedback(evi : EvaluatedIndividual<T>){}
/**
* get max test size during sampling
*/
fun getMaxTestSizeDuringSampler() : Int{
return when(config.maxTestSizeStrategy){
EMConfig.MaxTestSizeStrategy.SPECIFIED -> config.maxTestSize
EMConfig.MaxTestSizeStrategy.DPC_INCREASING -> apc.getExploratoryValue(config.dpcTargetTestSize, config.maxTestSize)
EMConfig.MaxTestSizeStrategy.DPC_DECREASING -> apc.getExploratoryValue(config.maxTestSize, config.dpcTargetTestSize)
}
}
/**
* extract tables with additional FK tables
*/
open fun extractFkTables(tables: Set<String>): Set<String>{
throw IllegalStateException("FK tables have not been not handled yet")
}
/**
* Return a list of pre-written individuals that will be added in the final solution.
* Those will not be evolved during the search, but still need to compute their fitness,
* eg to create valid assertions for them.
*/
open fun getPreDefinedIndividuals() = listOf<T>()
} | lgpl-3.0 | 6ab59ea53f0a79aacda81bd1caa67257 | 30.019108 | 128 | 0.65763 | 4.563261 | false | true | false | false |
anggrayudi/android-hidden-api | sample/src/main/java/com/anggrayudi/hiddenapi/sample/MainActivity.kt | 1 | 6822 | package com.anggrayudi.hiddenapi.sample
import android.content.Intent
import android.net.Uri
//import android.net.wifi.WifiLinkLayerStats
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.view.MenuItem
import android.widget.AdapterView.OnItemClickListener
import androidx.appcompat.app.AppCompatActivity
import com.anggrayudi.hiddenapi.InternalAccessor
import kotlinx.android.synthetic.main.activity_main.*
import timber.log.Timber
/**
* Created by Anggrayudi on 11/03/2016.
*
* An example class for Hidden API.
*
* If you plan to use only Android internal resources rather than internal classes or methods,
* just add <br></br>`compile 'com.anggrayudi:android-hidden-api:30.0'`<br></br> library
* to your app's module without need to replace `android.jar`. This version does not use
* Java reflection anymore, and certainly safe.
* See the [Usage](https://github.com/anggrayudi/android-hidden-api#usage).
*/
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
// Test if Editable included in custom android.jar
var editable: Editable
val items = mutableListOf(
// Model(
// /*
// formatShortElapsedTime method will show error 'Cannot resolve symbol' if you don't use custom android.jar
// Since custom android.jar v28, some methods are no longer accessible. I don't know why.
// Android Studio will say, "formatShortElapsedTime has private access".
// A workaround is you HAVE TO copy this static method into your own code.
// */
// "Formatter.formatShortElapsedTime(this, 100000000)",
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) Formatter.formatShortElapsedTime(this, 100000000) else null,
// """
// Accessing hidden method. This method only available for API 21+. If you run it on a device with API 20 and lower,
// you'll get java.lang.NoSuchMethodError exception.
// """.trimIndent()
// ),
Model(
"com.android.internal.R.string.accept",
description = "Accessing hidden String resource. We cannot access internal resources directly. "
+ "Sometimes, IDE says 'error: cannot find symbol variable accept' "
+ "once you run the app, or your app picks wrong resource id. If you want to have the internal resources, "
+ "copy them to your project or use InternalAccessor utility class. Below are the example."
),
Model(
"InternalAccessor.getString(\"accept\")",
InternalAccessor.getString("accept"),
"Accessing hidden String resource. Because above method is not working, "
+ "so we need to use InternalAccessor.getString() method."
)
)
items.add(
Model(
"InternalAccessor.getDimension(\"status_bar_height\")",
InternalAccessor.getDimension("status_bar_height").toString(),
"Accessing hidden dimension resource."
)
)
items.add(
Model(
"InternalAccessor.getColor(\"config_defaultNotificationColor\")",
InternalAccessor.getColor("config_defaultNotificationColor").toString(),
"Accessing hidden color resource."
)
)
items.add(
Model(
"Info", description = "For more information, download this app's source code on " +
"https://github.com/anggrayudi/android-hidden-api"
)
)
listView.adapter = Adapter(items)
listView.onItemClickListener = OnItemClickListener { _, _, position, _ ->
if (position == items.size - 1) {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/anggrayudi/android-hidden-api")))
}
}
if (Build.VERSION.SDK_INT >= 22) {
/*
Accessing WifiLinkLayerStats that is a hidden class.
If you want to find out which API was built to, just type method, resource or class name
to search box on http://jcs.mobile-utopia.com/servlet/Source?type=s&q=WifiLinkLayerStats
And then, look at 'Category' column.
WifiLinkLayerStats method will show error 'Cannot resolve symbol' if you don't use custom android.jar
For source code: http://jcs.mobile-utopia.com/jcs/7601_WifiLinkLayerStats.java
*/
// var wifiLinkLayer: WifiLinkLayerStats
}
// If you want to check whether WifiLinkLayerStats exists without checking API level, you can call:
val isClassExists = InternalAccessor.isClassExists("android.net.wifi.WifiLinkLayerStats")
Timber.d("isClassExists = $isClassExists")
// Check whether a method exists
val isMethodExists = InternalAccessor.isMethodExists("android.content.Intent", "getExtra")
Timber.d("isMethodExists = $isMethodExists")
// This will retrieve resource id named accelerate_cubic in com.android.internal.R.interpolator class.
Timber.d("interpolator.accelerate_cubic = %s", InternalAccessor.getResourceId(InternalAccessor.INTERPOLATOR, "accelerate_cubic"))
Timber.d("plurals.duration_hours = %s", InternalAccessor.getResourceId(InternalAccessor.PLURALS, "last_num_days"))
Timber.d("transition.no_transition = %s", InternalAccessor.getResourceId(InternalAccessor.TRANSITION, "no_transition"))
/*
DEPRECATED EXAMPLE OF InternalAccessor.Builder
// Using InternalAccessor with other code styling
InternalAccessor.Builder builder = new InternalAccessor.Builder(true);
boolean b = builder.getBoolean("config_sip_wifi_only");
String accept = builder.getString("accept");
// Because we set true to 'saveToResourcesHolder' in the Builder constructor, every value we got always
// saved to ResourcesHolder automatically. We can retrieve the holder now:
ResourcesHolder accessorHolder = builder.getResourcesHolder();
b = accessorHolder.getAsBoolean("config_sip_wifi_only");
accept = accessorHolder.getAsString("accept");
*/
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) finish()
return super.onOptionsItemSelected(item)
}
} | apache-2.0 | 140fb4ade0ce6b38f1102eb58bddcdc8 | 47.390071 | 137 | 0.649516 | 4.721107 | false | false | false | false |
google/audio-to-tactile | extras/android/java/com/google/audio_to_tactile/BleViewModel.kt | 1 | 16445 | /* Copyright 2021-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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.audio_to_tactile
import android.app.Activity
import android.bluetooth.BluetoothDevice
import android.os.Build
import android.util.Log
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.IntentSenderRequest
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.google.audio_to_tactile.ble.BleCom
import com.google.audio_to_tactile.ble.BleComCallback
import com.google.audio_to_tactile.ble.DisconnectReason
import dagger.hilt.android.lifecycle.HiltViewModel
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneOffset
import java.util.Calendar
import javax.inject.Inject
import kotlin.math.sqrt
/** Notifies MutableLiveData observers by assigning its value to itself. */
fun <T> MutableLiveData<T>.notifyObservers() { setValue(getValue()) }
/** `ViewModel` for BLE communication. */
@HiltViewModel
class BleViewModel @Inject constructor(private val bleCom: BleCom) : ViewModel() {
/** Date when the app was built. */
var appBuildDate: LocalDate? = null
private val _isConnected = MutableLiveData<Boolean>(false)
/**
* Indicates whether BLE is connected. UI fragments can `.observe` this variable for notifications
* when BLE connects or disconnects.
*/
val isConnected: LiveData<Boolean>
get() = _isConnected
/** Name used by the connected device for BLE advertising. */
val deviceBleName: String
get() = bleCom.deviceName
/** BLE address of connected device. */
val deviceBleAddress: String
get() = bleCom.deviceAddress
private val _disconnectReason = MutableLiveData<DisconnectReason>()
/** When BLE disconnects, `disconnectReason` gives a reason to explain why. */
val disconnectReason: LiveData<DisconnectReason>
get() = _disconnectReason
private val _tuning = MutableLiveData<Tuning>(Tuning())
/** Algorithm tuning knobs. */
val tuning: LiveData<Tuning>
get() = _tuning
private val _channelMap =
MutableLiveData<ChannelMap>(ChannelMap(numInputChannels = 10, numOutputChannels = 10))
/** Algorithm tuning knobs. */
val channelMap: LiveData<ChannelMap>
get() = _channelMap
private val _firmwareBuildDate = MutableLiveData<LocalDate>()
/** Date when device firmware was built. */
val firmwareBuildDate: LiveData<LocalDate>
get() = _firmwareBuildDate
private val _deviceName = MutableLiveData<String>("")
/** User-customizable device name. */
val deviceName: LiveData<String>
get() = _deviceName
private val _batteryVoltage = MutableLiveData<Float>(-1f)
/** Device battery voltage from the latest received [BatteryVoltageMessage]. */
val batteryVoltage: LiveData<Float>
get() = _batteryVoltage
private val _temperatureCelsius = MutableLiveData<Float>(-1f)
/** Device thermistor temperature from the latest received [TemperatureMessage]. */
val temperatureCelsius: LiveData<Float>
get() = _temperatureCelsius
private val _inputLevel = TimeSeries(samplePeriodMs = 30L, windowDurationMs = 6000L)
/** Mic input level time series received from [StatsRecordMessage]. */
val inputLevel: TimeSeries
get() = _inputLevel
private val _flashMemoryWriteStatus = MutableLiveData<FlashMemoryStatus>()
/** Status returned by latest attempt to write to device's flash memory */
val flashMemoryWriteStatus: LiveData<FlashMemoryStatus>
get() = _flashMemoryWriteStatus
private val _tactilePattern = MutableLiveData(TactilePattern())
/** Tactile pattern shown in the pattern editor. */
val tactilePattern: LiveData<TactilePattern>
get() = _tactilePattern
private val _tactilePatternSelectedIndex = MutableLiveData<Int>(-1)
/** The index of the currently selected tactile pattern op, or -1 if none is selected. */
val tactilePatternSelectedIndex: LiveData<Int>
get() = _tactilePatternSelectedIndex
/** The currently selected tactile pattern op, or null if none is selected. */
val tactilePatternSelectedOp: TactilePattern.Op?
get() =
_tactilePattern.value?.ops?.let { ops ->
_tactilePatternSelectedIndex.value?.let { i ->
if (i in ops.indices) { ops[i] } else { null }
}
}
data class LogLine(val timestamp: String, val message: String)
private val _logLines = MutableLiveData(mutableListOf<LogLine>())
/** Log lines, to be displayed in the Log fragment. */
val logLines: LiveData<MutableList<LogLine>>
get() = _logLines
/** Format for log timestamps. */
private val logTimestampFormat = SimpleDateFormat("HH:mm:ss.SSS")
init {
// Callbacks for responding to BLE communication events.
bleCom.callback =
object : BleComCallback {
override fun onConnect() {
_isConnected.setValue(true)
log("BLE successfully established connection.")
// On connection, ask device for an on-connection batch message. The firmware expects this
// to be the first message sent, and uses it as a cue to begin sending data to the app.
sendMessageIfConnected(GetOnConnectionBatchMessage())
}
override fun onDisconnect(reason: DisconnectReason) {
_isConnected.setValue(false)
_disconnectReason.setValue(reason)
log("BLE disconnected")
}
override fun onRead(message: Message) {
// StatsRecordMessages are received frequently, about once per second. So we don't
// log this kind of message to reduce log spam.
if (!(message is StatsRecordMessage)) {
log("Got $message")
}
when (message) {
is OnConnectionBatchMessage -> {
message.firmwareBuildDate?.let {
log("Device firmware build date: $it")
_firmwareBuildDate.setValue(it)
}
_batteryVoltage.setValue(message.batteryVoltage)
_temperatureCelsius.setValue(message.temperatureCelsius)
message.deviceName?.let { _deviceName.setValue(it) }
message.tuning?.let { _tuning.setValue(it) }
message.channelMap?.let { channelMap ->
_channelMap.value?.let {
if (it.sameNumChannelsAs(channelMap)) {
_channelMap.setValue(channelMap)
}
}
}
}
is BatteryVoltageMessage -> {
_batteryVoltage.setValue(message.voltage)
}
is TemperatureMessage -> {
_temperatureCelsius.setValue(message.celsius)
}
is StatsRecordMessage -> {
// A fudge factor for plotting: [TimeSeriesPlot] expects values in [0, 1], but the
// input amplitude is usually below 0.2. So we scale by 5 to fill the box better.
val Y_SCALE = 5.0f
// Apply sqrt to convert energy to amplitude.
val amplitude =
message.inputLevel.map { energy -> Y_SCALE * sqrt(energy) }.toFloatArray()
_inputLevel.add(System.currentTimeMillis(), amplitude)
}
is FlashMemoryStatusMessage -> {
_flashMemoryWriteStatus.setValue(message.status)
}
else -> {
// No action on other messages.
}
}
}
}
}
/** This is called by the main activity, passing the app build time as a Unix timestamp. */
fun onActivityStart(appBuildTimestamp: Long) {
if (appBuildDate == null) {
appBuildDate = LocalDateTime.ofEpochSecond(appBuildTimestamp, 0, ZoneOffset.UTC).toLocalDate()
log("App build date: $appBuildDate")
log("Android version: ${Build.VERSION.RELEASE}")
}
}
/** Adds a message to `logLines`. Also prints it to the console log. */
fun log(message: String) {
val timestamp = logTimestampFormat.format(Calendar.getInstance().getTime())
_logLines.value!!.add(LogLine(timestamp, message))
_logLines.value = _logLines.value // Notify observers.
// Print to console log. This API includes a timestamp on its own, so just log the message.
// TODO: Consider switching logging to Google Flogger.
Log.i(TAG, message)
}
/** Initiates a scan for BLE devices. */
fun scanForDevices(activity: Activity, launcher: ActivityResultLauncher<IntentSenderRequest>) {
bleCom.scanForDevices(activity, launcher)
}
/** Initiates connection to `device` */
fun connect(device: BluetoothDevice) {
log("BLE connecting to ${device.name}")
bleCom.connect(device)
}
/** Disconnects BLE, if connected. */
fun disconnect() {
bleCom.disconnect()
}
/** Tells the device to update the device name. */
fun setDeviceName(name: String) {
if (name.isNotEmpty()) {
_deviceName.value?.let {
// Before setting, check whether `name` differs to avoid infinite observer loop.
if (it == name) { return }
_deviceName.value = name
sendMessageIfConnected(DeviceNameMessage(name))
}
}
}
/** Tells the device to play a tactile pattern. */
fun playTactilePattern(pattern: ByteArray) {
if (pattern.isNotEmpty()) {
sendMessageIfConnected(TactilePatternMessage(pattern))
}
}
/** Resets all tuning knobs to default settings. */
fun tuningResetAll() {
_tuning.value?.let {
it.resetAll()
tuningNotifyObservers()
}
}
/** Resets the `knobIndex` tuning knob to its default. */
fun tuningKnobReset(knobIndex: Int) {
tuningKnobSetValue(knobIndex, Tuning.DEFAULT_TUNING_KNOBS[knobIndex])
}
/** Sets the `knobIndex` tuning knob to the given control value. */
fun tuningKnobSetValue(knobIndex: Int, value: Int) {
val knob = _tuning.value?.get(knobIndex) ?: return
if (knob.value != value) {
knob.value = value
tuningNotifyObservers()
}
}
/** Resets all channels to default settings. */
fun channelMapResetAll() {
_channelMap.value?.let {
it.resetAll()
channelMapNotifyObservers()
}
}
/** Resets channel `tactorIndex` to its defaults. */
fun channelMapReset(tactorIndex: Int) {
val channel = _channelMap.value?.get(tactorIndex) ?: return
channel.reset()
channelMapNotifyObservers()
}
/** Sets whether channel `tactorIndex` is enabled. */
fun channelMapSetEnable(tactorIndex: Int, enabled: Boolean) {
val channel = _channelMap.value?.get(tactorIndex) ?: return
channel.enabled = enabled
channelMapNotifyObservers()
}
/** Sets the source as a base-0 index for channel `tactorIndex`. */
fun channelMapSetSource(tactorIndex: Int, source: Int) {
val channel = _channelMap.value?.get(tactorIndex) ?: return
channel.source = source
channelMapNotifyObservers()
}
/** Sets the gain for channel `tactorIndex` to the given control value. */
fun channelMapSetGain(tactorIndex: Int, gain: Int) {
val channel = _channelMap.value?.get(tactorIndex) ?: return
channel.gain = gain
_channelMap.value = _channelMap.value // Notify observers.
_channelMap.value?.let {
// Send [ChannelGainUpdateMessage] over BLE to the connected device.
val testChannels = Pair(it[0].source, it[tactorIndex].source)
sendMessageIfConnected(ChannelGainUpdateMessage(it, testChannels))
}
}
/** Tells the device to play a test buzz on tactor `tactorIndex`. */
fun channelMapTest(tactorIndex: Int) {
_channelMap.value?.let {
// Send [ChannelGainUpdateMessage] over BLE to the connected device.
val testChannel = it[tactorIndex].source
sendMessageIfConnected(ChannelGainUpdateMessage(it, Pair(testChannel, testChannel)))
}
}
/** Command to prepare for bootloading, This means to stop all interrupts. */
fun prepareForBootloading() {
sendMessageIfConnected(PrepareForBluetoothBootloadingMessage())
}
/** Clears `tactilePattern` and sets the selected index to -1 (no selection). */
fun tactilePatternClear() {
_tactilePattern.value!!.ops.clear()
_tactilePatternSelectedIndex.value = -1
}
/** Reads `tactilePattern` from an InputStream with a pattern in text format. */
fun tactilePatternReadFromStream(stream: InputStream) {
try {
_tactilePatternSelectedIndex.value = -1
_tactilePattern.setValue(TactilePattern.parse(String(stream.readBytes())))
} catch (e: IOException) {
log("Error reading tactile pattern.")
e.message?.let { log(it) }
} catch (e: TactilePattern.ParseException) {
log("Error parsing tactile pattern.")
e.message?.let { log(it) }
}
}
/** Writes `tactilePattern` to an OutputStream in text format. */
fun tactilePatternWriteToStream(stream: OutputStream) {
try {
stream.write(_tactilePattern.value!!.toString().toByteArray())
} catch (e: IOException) {
log("Error writing tactile pattern.")
e.message?.let { log(it) }
}
}
/** Sends `tactilePattern` to the device for playback. */
fun tactilePatternPlay(): Boolean {
return sendMessageIfConnected(TactileExPatternMessage(_tactilePattern.value!!))
}
/** Selects the ith line of `tactilePattern`, or deselects if out of range. */
fun tactilePatternSelect(i: Int) {
val newValue = if (i in _tactilePattern.value!!.ops.indices) { i } else { -1 /* Deselect. */ }
if (_tactilePatternSelectedIndex.value!! != newValue) {
_tactilePatternSelectedIndex.value = newValue
}
}
/** If `op` is nonnull, inserts the op after the selected index, or at the end if no selection. */
fun tactilePatternInsertOp(op: TactilePattern.Op?): Boolean {
if (op == null) { return false }
val ops = _tactilePattern.value!!.ops
val selectedIndex = _tactilePatternSelectedIndex.value!!
val i = if (selectedIndex in ops.indices) { selectedIndex + 1 } else { ops.size }
ops.add(i, op)
_tactilePatternSelectedIndex.value = i
return true
}
/** Swaps the ith and jth ops of `tactilePattern`. Returns true on success. */
fun tactilePatternSwapOps(i: Int, j: Int): Boolean {
return _tactilePattern.value!!.swapOps(i, j)
}
/** Removes the selected op from `tactilePattern`. Returns the removed index on success. */
fun tactilePatternRemoveOp(): Int? {
val ops = _tactilePattern.value!!.ops
val selectedIndex = _tactilePatternSelectedIndex.value!!
if (selectedIndex in ops.indices) {
ops.removeAt(selectedIndex)
return selectedIndex
} else {
return null
}
}
/** Notifies `tactilePattern` observers. */
fun tactilePatternNotifyObservers() {
_tactilePattern.notifyObservers()
}
/** Notifies `tactilePatternSelectIndex` observers. */
fun tactilePatternSelectedIndexNotifyObservers() {
_tactilePatternSelectedIndex.notifyObservers()
}
@VisibleForTesting
fun channelMapSet(channelMap: ChannelMap) {
_channelMap.setValue(channelMap)
}
private fun tuningNotifyObservers() {
_tuning.notifyObservers()
// Send [TuningMessage] over BLE to update tuning on the connected device.
_tuning.value?.let { sendMessageIfConnected(TuningMessage(it)) }
}
private fun channelMapNotifyObservers() {
_channelMap.notifyObservers()
// Send [ChannelMapMessage] over BLE to update tuning on the connected device.
_channelMap.value?.let { sendMessageIfConnected(ChannelMapMessage(it)) }
}
/** Sends and logs `message` if BLE is connected. */
private fun sendMessageIfConnected(message: Message): Boolean {
if (isConnected.value == true) {
bleCom.write(message)
log("Sent $message")
return true
}
return false
}
private companion object {
const val TAG = "BleViewModel"
}
}
| apache-2.0 | b58deeb4566dd304fcbda25508973f81 | 34.984683 | 100 | 0.68422 | 4.320809 | false | false | false | false |
Eluinhost/anonymous | src/main/kotlin/DisguiseController.kt | 1 | 5310 | package gg.uhc.anonymous
import com.comphenix.executors.BukkitExecutors
import com.comphenix.protocol.PacketType
import com.comphenix.protocol.ProtocolManager
import com.comphenix.protocol.events.PacketAdapter
import com.comphenix.protocol.events.PacketContainer
import com.comphenix.protocol.events.PacketEvent
import com.comphenix.protocol.wrappers.PlayerInfoData
import com.comphenix.protocol.wrappers.WrappedChatComponent
import com.comphenix.protocol.wrappers.WrappedGameProfile
import com.comphenix.protocol.wrappers.WrappedSignedProperty
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerLoginEvent
import org.bukkit.plugin.Plugin
import java.util.*
import java.util.concurrent.TimeUnit
/**
* Handles disguising players on join by changing their skin/tab name/display name
*
* @param skinUUID uuid of the skin to display
* @param name name of the player to show in tab/as display name
* @param profiles used to fetch skin data to show to clients
* @param plugin used to register events/packet listeners and for logging
* @param refreshTime amount of time between trying to refresh the skin data in minutes
* @param manager used to register packet listeners for modifying skins
*/
open class DisguiseController(
protected val skinUUID: UUID,
protected val name: String,
protected val profiles: ProfileParser,
protected val plugin: Plugin,
protected val refreshTime: Long,
manager: ProtocolManager
) : Listener {
protected val wrappedName = WrappedChatComponent.fromText(name)
protected var texture: WrappedSignedProperty? = null
protected val asyncExecutor = BukkitExecutors.newAsynchronous(plugin)
/**
* A listener that calls [onTabListPacket] when receiving a [tab list packet][PacketType.Play.Server.PLAYER_INFO]
* and the player does not have the [bypass permission][SKIN_BYPASS_PERMISSION]. This means anyone with the
* permission will *see* valid skins, not that people will see the player.
*/
protected val tabListPlayersListener = object : PacketAdapter(plugin, PacketType.Play.Server.PLAYER_INFO) {
override fun onPacketSending(event: PacketEvent) {
if (!event.player.hasPermission(SKIN_BYPASS_PERMISSION)) {
onTabListPacket(event.packet)
}
}
}
/**
* Changes the textures and name for the player/s on the tab list for the receiver
*
* @param packet raw packet to be modified
*/
protected open fun onTabListPacket(packet: PacketContainer) = packet.playerInfoDataLists.write(
0,
packet.playerInfoDataLists.read(0).map {
val newProfile = WrappedGameProfile(it.profile.uuid, name)
newProfile.properties.putAll(it.profile.properties)
newProfile.properties.replaceValues("textures", if (texture == null) listOf() else listOf(texture))
PlayerInfoData(newProfile, it.ping, it.gameMode, wrappedName)
}
)
@EventHandler(priority = EventPriority.LOW) fun on(event: PlayerLoginEvent) = onPlayerLogin(event.player)
/**
* Called whenever a player logs in, simply modifies their display name so that other plugins can use it
*
* @param player the player that has just logged in
*/
protected open fun onPlayerLogin(player: Player) {
player.displayName = name
}
/**
* Attempts to update the [stored skin textures][texture] from the [provided profile fetcher][profiles]. Logs
* information via [plugin] on success/failure.
*
* *NOTE: do not call this on the main thread as [profiles] can be working over the network*
*/
protected open fun updateSkin() {
plugin.logger.info("Starting update of skin texture")
try {
val profile = profiles.getForUuid(skinUUID)
val x = profile.properties.find { it.name == "textures" }
?: throw IllegalArgumentException("Skin data missing textures property")
val newTexture = WrappedSignedProperty.fromValues(x.name, x.value, x.signature)
if (!newTexture.equals(texture)) {
texture = newTexture
plugin.logger.info("Updated skin texture")
} else {
plugin.logger.info("Skin texture already up to date")
}
} catch (ex: Throwable) {
ex.printStackTrace()
plugin.logger.warning("Failed to fetch the skin data for the uuid $skinUUID")
}
}
init {
// add listener for rewriting tab packets
manager.addPacketListener(tabListPlayersListener)
// add listener for log in events
plugin.server.pluginManager.registerEvents(this, plugin)
// force 'login event' for each player that is already online (/reload)
// we don't rebuild the tab list so these players will need to reload
// to see the new skin/names
plugin.server.onlinePlayers.forEach { onPlayerLogin(it) }
// start updating the stored texture on a schedule, we run async because network could be involved
asyncExecutor.scheduleAtFixedRate({ updateSkin() }, 0, refreshTime, TimeUnit.MINUTES)
}
}
| mit | 16d2aefcfb834b64b76ef302d46f88c4 | 40.811024 | 117 | 0.70452 | 4.462185 | false | false | false | false |
erubit-open/platform | erubit.platform/src/main/java/a/erubit/platform/course/ProgressManager.kt | 1 | 919 | package a.erubit.platform.course
import a.erubit.platform.course.lesson.Lesson
import android.content.Context
import com.google.gson.Gson
import t.SelfExpiringHashMap
import t.TinyDB
import u.C
class ProgressManager {
private val cacheMap = SelfExpiringHashMap<String, String>(1000, 10)
fun save(context: Context, lesson: Lesson) {
save(context, lesson.id!!, lesson.updateProgress())
}
private fun save(context: Context, id: String, progress: Progress) {
val json = Gson().toJson(progress)
cacheMap[id] = json
TinyDB(context.applicationContext).putString(C.PROGRESS_KEY + id, json)
}
fun load(context: Context, id: String?): String {
val cached = cacheMap[id]
return cached ?: TinyDB(context.applicationContext).getString(C.PROGRESS_KEY + id)
}
companion object {
private val progressManager = ProgressManager()
@JvmStatic
fun i(): ProgressManager {
return progressManager
}
}
}
| gpl-3.0 | 3e6784f93e69cd9d76daf6d104366655 | 23.837838 | 84 | 0.744287 | 3.548263 | false | false | false | false |
yrsegal/CommandControl | src/main/java/wiresegal/cmdctrl/common/commands/misc/CommandMan.kt | 1 | 2711 | package wiresegal.cmdctrl.common.commands.misc
import net.minecraft.command.CommandBase
import net.minecraft.command.ICommandSender
import net.minecraft.command.PlayerNotFoundException
import net.minecraft.entity.player.EntityPlayerMP
import net.minecraft.server.MinecraftServer
import net.minecraft.util.math.BlockPos
import net.minecraft.util.text.TextComponentTranslation
import wiresegal.cmdctrl.common.CommandControl
import wiresegal.cmdctrl.common.core.CTRLException
import wiresegal.cmdctrl.common.man.ManEntry
/**
* @author WireSegal
* Created at 5:48 PM on 12/5/16.
*/
object CommandMan : CommandBase() {
override fun execute(server: MinecraftServer, sender: ICommandSender, args: Array<out String>) {
if (sender is EntityPlayerMP || sender is MinecraftServer) {
val key = if (args.isEmpty()) "man" else args[0]
val command = server.commandManager.commands[key]
if (command !in server.commandManager.commands.values)
throw CTRLException("commandcontrol.man.wtfisthis", key)
if (command !in getSortedPossibleCommands(sender, server))
throw CTRLException("commandcontrol.man.youaintking", key)
val manEntry = ManEntry(sender, command, if (args.size > 1) args[1] else null)
val components = manEntry.asTextComponents
if (components.isEmpty())
throw CTRLException("commandcontrol.man.nodocs", key)
if (sender.sendCommandFeedback()) {
if (manEntry.hasSub)
sender.addChatMessage(TextComponentTranslation("commandcontrol.man.headersub", key, manEntry.subcom))
else
sender.addChatMessage(TextComponentTranslation("commandcontrol.man.header", key))
components.forEach { sender.addChatMessage(it) }
}
} else
throw PlayerNotFoundException("commandcontrol.man.handsoff")
}
fun getSortedPossibleCommands(sender: ICommandSender, server: MinecraftServer)
= server.getCommandManager().getPossibleCommands(sender).sorted()
override fun getTabCompletionOptions(server: MinecraftServer, sender: ICommandSender, args: Array<out String>, pos: BlockPos?): List<String> {
return if (args.size == 1) getListOfStringsMatchingLastWord(args, getSortedPossibleCommands(sender, server).map { it.commandName }) else emptyList()
}
override fun getRequiredPermissionLevel() = 0
override fun getCommandName() = "man"
override fun getCommandAliases() = listOf("documentation", "manual")
override fun getCommandUsage(sender: ICommandSender?) = CommandControl.translate("commandcontrol.man.usage")
}
| mit | fe26311145dbce7f1679f7ce697292a9 | 48.290909 | 156 | 0.710808 | 4.62628 | false | false | false | false |
RocketChat/Rocket.Chat.Android | app/src/main/java/chat/rocket/android/db/model/Url.kt | 2 | 719 | package chat.rocket.android.db.model
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
@Entity(tableName = "urls",
foreignKeys = [
ForeignKey(entity = MessageEntity::class, parentColumns = ["id"],
childColumns = ["messageId"], onDelete = ForeignKey.CASCADE)
],
indices = [
Index(value = ["messageId"])
])
data class UrlEntity(
val messageId: String,
val url: String,
val hostname: String?,
val title: String?,
val description: String?,
val imageUrl: String?
) : BaseMessageEntity {
@PrimaryKey(autoGenerate = true)
var urlId: Long? = null
} | mit | a34df6edbc18f44a6c136d3b97fad2c1 | 26.692308 | 80 | 0.639777 | 4.384146 | false | false | false | false |
google/private-compute-libraries | javatests/com/google/android/libraries/pcc/chronicle/remote/handler/RemoteComputeServerHandlerTest.kt | 1 | 4802 | /*
* 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.remote.handler
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.android.libraries.pcc.chronicle.api.policy.builder.policy
import com.google.android.libraries.pcc.chronicle.api.remote.ComputeRequest
import com.google.android.libraries.pcc.chronicle.api.remote.IResponseCallback
import com.google.android.libraries.pcc.chronicle.api.remote.RemoteEntity
import com.google.android.libraries.pcc.chronicle.api.remote.RemoteResponse
import com.google.android.libraries.pcc.chronicle.api.remote.serialization.Serializer
import com.google.android.libraries.pcc.chronicle.api.remote.server.RemoteComputeServer
import com.google.android.libraries.pcc.chronicle.api.storage.EntityMetadata
import com.google.android.libraries.pcc.chronicle.api.storage.WrappedEntity
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.argumentCaptor
import com.nhaarman.mockitokotlin2.doAnswer
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.runBlocking
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class RemoteComputeServerHandlerTest {
private val argumentSerializer =
mock<Serializer<ComputeArgument>> {
on { deserialize<ComputeArgument>(any()) } doAnswer
{
val input = it.arguments[0] as RemoteEntity
WrappedEntity(input.metadata, ComputeArgument(input.metadata.id))
}
}
private val resultSerializer =
mock<Serializer<ComputeResult>> {
on { serialize<ComputeResult>(any()) } doAnswer
{
@Suppress("UNCHECKED_CAST") val input = it.arguments[0] as WrappedEntity<ComputeResult>
RemoteEntity(input.metadata)
}
}
private val computeServer =
mock<RemoteComputeServer<ComputeArgument, ComputeResult>> {
on { argumentSerializer } doReturn argumentSerializer
on { serializer } doReturn resultSerializer
}
@Test
fun handle_callsRunAndSendsEachResultPage(): Unit = runBlocking {
val req =
ComputeRequest.newBuilder()
.addParameterDataTypeNames("ComputeArgument")
.setResultDataTypeName("ComputeResult")
.setMethodId(ComputeRequest.MethodId.MOIRAI_CLASSIFY)
.build()
val arguments = listOf(ComputeArgument("one"), ComputeArgument("two"))
val resultPages =
listOf(
listOf(ComputeResult("a").wrap(), ComputeResult("b").wrap()),
listOf(ComputeResult("c").wrap())
)
val onDataCaptor = argumentCaptor<RemoteResponse>()
val callback =
mock<IResponseCallback.Stub> { on { onData(onDataCaptor.capture()) } doAnswer {} }
val handler = RemoteComputeServerHandler(req, computeServer)
whenever(computeServer.run(any(), any(), any())).thenReturn(resultPages.asFlow())
handler.handle(POLICY, arguments.map { it.toRemoteEntity() }, callback)
verify(computeServer, times(1))
.run(
policy = eq(POLICY),
method = eq(ComputeRequest.MethodId.MOIRAI_CLASSIFY),
input = eq(arguments.map { it.wrap() })
)
val responses = onDataCaptor.allValues
assertThat(responses).hasSize(2)
assertThat(responses[0].entities).hasSize(2)
assertThat(responses[0].entities[0].metadata.id).isEqualTo("a")
assertThat(responses[0].entities[1].metadata.id).isEqualTo("b")
assertThat(responses[1].entities).hasSize(1)
assertThat(responses[1].entities[0].metadata.id).isEqualTo("c")
}
data class ComputeArgument(val foo: String) {
fun wrap() = WrappedEntity(EntityMetadata.newBuilder().setId(foo).build(), this)
fun toRemoteEntity() = RemoteEntity(wrap().metadata)
}
data class ComputeResult(val bar: String) {
fun wrap(): WrappedEntity<ComputeResult> =
WrappedEntity(EntityMetadata.newBuilder().setId(bar).build(), this)
}
companion object {
private val POLICY = policy("Computer", "Testing")
}
}
| apache-2.0 | a2afa39198934d44c6308bcedc2ab780 | 40.042735 | 97 | 0.742607 | 4.215979 | false | false | false | false |
Alfresco/activiti-android-app | auth-library/src/main/kotlin/com/alfresco/auth/activity/LoginActivity.kt | 1 | 6029 | package com.alfresco.auth.activity
import android.content.Context
import android.content.pm.ActivityInfo
import android.graphics.Rect
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.RelativeLayout
import androidx.annotation.StringRes
import androidx.appcompat.widget.Toolbar
import androidx.core.view.ViewCompat
import com.alfresco.android.aims.R
import com.alfresco.auth.AuthConfig
import com.alfresco.auth.Credentials
import com.alfresco.auth.fragments.*
import com.alfresco.auth.ui.AuthenticationActivity
import com.alfresco.auth.ui.observe
import com.alfresco.common.getViewModel
import com.alfresco.ui.components.Snackbar
import com.alfresco.ui.components.TextInputLayout
import java.util.ArrayDeque
abstract class LoginActivity : AuthenticationActivity<LoginViewModel>() {
override val viewModel: LoginViewModel by lazy {
getViewModel {
LoginViewModel.with(applicationContext, intent)
}
}
protected var ignoreStepEventOnce = false
private lateinit var progressView: RelativeLayout
private lateinit var toolbar: Toolbar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (savedInstanceState != null) {
ignoreStepEventOnce = true
}
if (resources.getBoolean(R.bool.isTablet)) {
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
} else {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
setContentView(R.layout.activity_auth_welcome)
setupToolbar()
progressView = findViewById(R.id.rlProgress)
ViewCompat.setElevation(progressView, 10f)
observe(viewModel.hasNavigation, ::onNavigation)
observe(viewModel.isLoading, ::onLoading)
observe(viewModel.step, ::onMoveToStep)
observe(viewModel.onSsoLogin, ::pkceLogin)
observe(viewModel.onShowHelp, ::showHelp)
observe(viewModel.onShowSettings, ::showSettings)
title = ""
}
private fun setupToolbar() {
toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
}
private fun onLoading(isLoading: Boolean) {
progressView.visibility = if (isLoading) View.VISIBLE else View.GONE
}
private fun onNavigation(hasNavigation: Boolean) {
if (hasNavigation) {
toolbar.setNavigationIcon(R.drawable.ic_arrow_back)
toolbar.setNavigationOnClickListener { onBackPressed() }
} else {
toolbar.setNavigationIcon(null)
toolbar.setNavigationOnClickListener(null)
}
}
private fun onMoveToStep(step: LoginViewModel.Step) {
if (ignoreStepEventOnce) {
ignoreStepEventOnce = false
return
}
when (step) {
LoginViewModel.Step.InputIdentityServer -> InputIdentityFragment.with(this).display()
LoginViewModel.Step.InputAppServer -> InputServerFragment.with(this).display()
LoginViewModel.Step.EnterBasicCredentials -> BasicAuthFragment.with(this).display()
LoginViewModel.Step.EnterPkceCredentials -> viewModel.ssoLogin()
LoginViewModel.Step.Cancelled -> finish();
}
}
abstract fun onCredentials(credentials: Credentials, endpoint: String, authConfig: AuthConfig)
override fun onCredentials(credentials: Credentials) {
onCredentials(credentials, viewModel.canonicalApplicationUrl, viewModel.authConfig)
}
override fun onError(error: String) {
// Hide progress view on error
viewModel.isLoading.value = false
val parentLayout: View = findViewById(android.R.id.content);
Snackbar.make(parentLayout,
Snackbar.STYLE_ERROR,
resources.getString(R.string.auth_error_title),
error,
Snackbar.LENGTH_LONG).show()
// Hacky way to set error state to match design
updateAll<TextInputLayout> {
it.setBoxStrokeColorStateList(resources.getColorStateList(R.color.alfresco_textinput_stroke_error))
}
}
protected fun onError(@StringRes messageResId: Int) {
onError(resources.getString(messageResId))
}
private fun showSettings(ignored: Int) {
AdvancedSettingsFragment.with(this).display()
}
private fun showHelp(@StringRes msgResId: Int) {
HelpFragment.with(this).message(msgResId).show()
}
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
// Dismiss keyboard on touches outside editable fields
if (event.action == MotionEvent.ACTION_DOWN) {
val v = currentFocus
if (v is EditText) {
val outRect = Rect()
v.getGlobalVisibleRect(outRect)
if (!outRect.contains(event.rawX.toInt(), event.rawY.toInt())) {
v.clearFocus()
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(v.windowToken, 0)
}
}
}
return super.dispatchTouchEvent(event)
}
private inline fun <reified T> updateAll(func: (T) -> Unit) {
val queue = ArrayDeque<ViewGroup>()
val rootView = (findViewById<ViewGroup>(android.R.id.content)).rootView as ViewGroup
var current: ViewGroup? = rootView
while (current != null) {
for (i in 0..current.childCount) {
val child = current.getChildAt(i);
if (child is ViewGroup) {
queue.add(child)
}
if (child is T) {
func(child)
}
}
current = queue.poll()
}
}
}
| lgpl-3.0 | e06b2db516543f08a48a2e521c8662dd | 32.681564 | 111 | 0.660143 | 4.929681 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/web/Authentication.kt | 1 | 2218 | /*
* 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.characters.bukkit.web
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.profile.RPKProfile
import com.rpkit.players.bukkit.profile.RPKProfileDiscriminator
import com.rpkit.players.bukkit.profile.RPKProfileName
import com.rpkit.players.bukkit.profile.RPKProfileService
import org.http4k.base64Decoded
import org.http4k.core.Credentials
import org.http4k.core.Request
import org.http4k.filter.ServerFilters
val Request.authenticatedProfile: RPKProfile?
get() = header("Authorization")
?.trim()
?.takeIf { it.startsWith("Basic") }
?.substringAfter("Basic")
?.trim()
?.base64Decoded()
?.split(":")
?.getOrElse(0) { "" }
?.split("#")
?.let {
if (it.size < 2) return@let null
val name = it[0]
val discriminator = it[1].toIntOrNull() ?: return@let null
Services[RPKProfileService::class.java]?.getProfile(RPKProfileName(name), RPKProfileDiscriminator(discriminator))?.join()
}
fun authenticated() = ServerFilters.BasicAuth("rpkit", ::authenticate)
private fun authenticate(credentials: Credentials): Boolean {
val profileService = Services[RPKProfileService::class.java] ?: return false
val parts = credentials.user.split("#")
if (parts.size < 2) return false
val name = parts[0]
val discriminator = parts[1].toIntOrNull() ?: return false
val profile = profileService.getProfile(RPKProfileName(name), RPKProfileDiscriminator(discriminator)).join() ?: return false
return profile.checkPassword(credentials.password.toCharArray())
} | apache-2.0 | b91aa4fc094d4475891230943491a7db | 39.345455 | 133 | 0.713706 | 4.34902 | false | false | false | false |
CPRTeam/CCIP-Android | app/src/main/java/app/opass/ccip/ui/schedule/ScheduleFragment.kt | 1 | 5313 | package app.opass.ccip.ui.schedule
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.distinctUntilChanged
import androidx.lifecycle.get
import androidx.lifecycle.observe
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import app.opass.ccip.R
import app.opass.ccip.extension.doOnApplyWindowInsets
import app.opass.ccip.extension.dpToPx
import app.opass.ccip.extension.updateMargin
import app.opass.ccip.model.Session
import app.opass.ccip.ui.sessiondetail.SessionDetailActivity
import app.opass.ccip.util.AlarmUtil
import app.opass.ccip.util.PreferenceUtil
class ScheduleFragment : Fragment() {
companion object {
private const val ARG_DATE = "ARG_DATE"
fun newInstance(date: String) =
ScheduleFragment().apply {
arguments = Bundle().apply {
putString(ARG_DATE, date)
}
}
}
private lateinit var adapter: ScheduleAdapter
private lateinit var mActivity: Activity
private lateinit var date: String
private lateinit var vm: ScheduleViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
mActivity = requireActivity()
date = requireArguments().getString(ARG_DATE)!!
vm = ViewModelProvider(requireParentFragment()).get()
val view = inflater.inflate(R.layout.fragment_schedule, container, false)
val emptyView = view.findViewById<TextView>(R.id.emptyView)
val scheduleView = view.findViewById<RecyclerView>(R.id.schedule)
scheduleView.layoutManager = LinearLayoutManager(mActivity)
val tagViewPool = RecyclerView.RecycledViewPool()
adapter = ScheduleAdapter(
mActivity,
tagViewPool,
::onSessionClicked,
::onToggleStarState,
::isSessionStarred
)
scheduleView.adapter = adapter
vm.groupedSessionsToShow.observe(viewLifecycleOwner) { sessionsMap ->
val grouped = sessionsMap?.get(date)?.let(::toSessionsGroupedByTime).orEmpty()
adapter.update(grouped)
val shouldShowEmptyView = sessionsMap != null && grouped.isEmpty()
val confSpansMultipleDay = sessionsMap?.size?.let { size -> size > 1 } ?: false
emptyView.isVisible = shouldShowEmptyView
emptyView.text = if (confSpansMultipleDay) {
getString(R.string.no_matching_sessions_multiple_day)
} else {
getString(R.string.no_matching_sessions)
}
}
vm.shouldShowSearchPanel
.distinctUntilChanged()
.observe(viewLifecycleOwner) {
requireView().requestApplyInsets()
}
scheduleView.doOnApplyWindowInsets { v, insets, padding, _ ->
val panelInset =
if (vm.shouldShowSearchPanel.value == true) 56F.dpToPx(resources) else 0
v.updatePadding(bottom = insets.systemGestureInsets.bottom + padding.bottom + panelInset)
}
emptyView.doOnApplyWindowInsets { v, insets, _, margin ->
val panelInset =
if (vm.shouldShowSearchPanel.value == true) 56F.dpToPx(resources) else 0
v.updateMargin(bottom = insets.systemGestureInsets.bottom + margin.bottom + panelInset)
}
return view
}
private fun onSessionClicked(session: Session) {
val intent = Intent(mActivity, SessionDetailActivity::class.java).apply {
putExtra(SessionDetailActivity.INTENT_EXTRA_SESSION_ID, session.id)
}
startActivity(intent)
}
private fun onToggleStarState(session: Session): Boolean {
val sessionIds = PreferenceUtil.loadStarredIds(mActivity).toMutableList()
val isAlreadyStarred = sessionIds.contains(session.id)
if (isAlreadyStarred) {
sessionIds.remove(session.id)
AlarmUtil.cancelSessionAlarm(mActivity, session)
} else {
sessionIds.add(session.id)
AlarmUtil.setSessionAlarm(mActivity, session)
}
PreferenceUtil.saveStarredIds(mActivity, sessionIds)
return !isAlreadyStarred
}
private fun isSessionStarred(session: Session): Boolean {
return PreferenceUtil.loadStarredIds(mActivity).contains(session.id)
}
private fun toSessionsGroupedByTime(sessions: List<Session>): List<List<Session>> {
return sessions
.filter { it.start != null }
.groupBy { it.start }
.values
.sortedBy { it[0].start }
.map { it.sortedWith(Comparator { (_, room1), (_, room2) -> room1.id.compareTo(room2.id) }) }
}
override fun onResume() {
super.onResume()
// Force RV to reload star state :(
adapter.notifyDataSetChanged()
}
}
| gpl-3.0 | 4f2eee274a1bab7d65f261a9bfa13fe4 | 38.066176 | 116 | 0.670996 | 4.83 | false | false | false | false |
quarck/CalendarNotification | app/src/main/java/com/github/quarck/calnotify/eventsstorage/EventsStorageImplV6.kt | 1 | 13097 | //
// Calendar Notifications Plus
// Copyright (C) 2016 Sergey Parshin ([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, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
package com.github.quarck.calnotify.eventsstorage
import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteConstraintException
import android.database.sqlite.SQLiteDatabase
import com.github.quarck.calnotify.Consts
import com.github.quarck.calnotify.calendar.EventAlertRecord
import com.github.quarck.calnotify.calendar.EventDisplayStatus
import com.github.quarck.calnotify.logs.DevLog
//import com.github.quarck.calnotify.logs.Logger
import java.util.*
class EventsStorageImplV6() : EventsStorageImplInterface {
@Suppress("ConvertToStringTemplate")
override fun createDb(db: SQLiteDatabase) {
val CREATE_PKG_TABLE =
"CREATE " +
"TABLE $TABLE_NAME " +
"( " +
"$KEY_EVENTID INTEGER PRIMARY KEY, " +
"$KEY_NOTIFICATIONID INTEGER, " +
"$KEY_TITLE TEXT, " +
"$KEY_DESC TEXT, " +
"$KEY_START INTEGER, " +
"$KEY_END INTEGER, " +
"$KEY_LOCATION LOCATION, " +
"$KEY_SNOOZED_UNTIL INTEGER, " +
"$KEY_LAST_EVENT_FIRE INTEGER, " +
"$KEY_IS_DISPLAYED INTEGER, " +
"$KEY_COLOR INTEGER, " +
"$KEY_ALERT_TIME INTEGER, " +
"$KEY_RESERVED_STR1 TEXT, " +
"$KEY_RESERVED_STR2 TEXT, " +
"$KEY_RESERVED_STR3 TEXT, " +
"$KEY_CALENDAR_ID INTEGER, " +
"$KEY_INSTANCE_START INTEGER, " +
"$KEY_INSTANCE_END INTEGER" +
" )"
DevLog.debug(LOG_TAG, "Creating DB TABLE using query: " + CREATE_PKG_TABLE)
db.execSQL(CREATE_PKG_TABLE)
val CREATE_INDEX = "CREATE UNIQUE INDEX $INDEX_NAME ON $TABLE_NAME ($KEY_EVENTID)"
DevLog.debug(LOG_TAG, "Creating DB INDEX using query: " + CREATE_INDEX)
db.execSQL(CREATE_INDEX)
}
override fun dropAll(db: SQLiteDatabase): Boolean {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
db.execSQL("DROP INDEX IF EXISTS " + INDEX_NAME);
return true
}
override fun addEventImpl(db: SQLiteDatabase, event: EventAlertRecord): Boolean {
DevLog.debug(LOG_TAG, "addEventImpl " + event.eventId)
if (event.notificationId == 0)
event.notificationId = nextNotificationId(db);
val values = eventRecordToContentValues(event, true)
try {
db.insertOrThrow(TABLE_NAME, // table
null, // nullColumnHack
values) // key/value -> keys = column names/ values = column
// values
}
catch (ex: SQLiteConstraintException) {
// Close Db before attempting to open it again from another method
DevLog.debug(LOG_TAG, "This entry (${event.eventId}) is already in the DB, updating!")
// persist original notification id in this case
event.notificationId = getEventImpl(db, event.eventId, event.instanceStartTime)?.notificationId ?: event.notificationId;
updateEventImpl(db, event)
}
return true
}
private fun nextNotificationId(db: SQLiteDatabase): Int {
var ret = 0;
val query = "SELECT MAX(${KEY_NOTIFICATIONID}) FROM " + TABLE_NAME
val cursor = db.rawQuery(query, null)
if (cursor != null && cursor.moveToFirst()) {
try {
ret = cursor.getString(0).toInt() + 1
}
catch (ex: Exception) {
ret = 0;
}
}
cursor?.close()
if (ret == 0)
ret = Consts.NOTIFICATION_ID_DYNAMIC_FROM;
DevLog.debug(LOG_TAG, "nextNotificationId, returning $ret")
return ret
}
override fun updateEventImpl(db: SQLiteDatabase, event: EventAlertRecord): Boolean {
val values = eventRecordToContentValues(event)
DevLog.debug(LOG_TAG, "Updating event, eventId=${event.eventId}");
db.update(TABLE_NAME, // table
values, // column/value
KEY_EVENTID + " = ?", // selections
arrayOf<String>(event.eventId.toString())) // selection args
return true
}
override fun updateEventsImpl(db: SQLiteDatabase, events: List<EventAlertRecord>): Boolean {
DevLog.debug(LOG_TAG, "Updating ${events.size} requests");
for (event in events) {
val values = eventRecordToContentValues(event)
db.update(TABLE_NAME, // table
values, // column/value
KEY_EVENTID + " = ?", // selections
arrayOf<String>(event.eventId.toString())) // selection args
}
return true
}
override fun updateEventAndInstanceTimesImpl(db: SQLiteDatabase, event: EventAlertRecord, instanceStart: Long, instanceEnd: Long): Boolean {
// V6 - instance start is not key value
updateEventImpl(db, event.copy(instanceStartTime = instanceStart, instanceEndTime = instanceEnd))
return true
}
override fun getEventImpl(db: SQLiteDatabase, eventId: Long, instanceStartTime: Long): EventAlertRecord? {
val selection =
if (instanceStartTime != 0L)
" $KEY_EVENTID = ? AND $KEY_INSTANCE_START = ?"
else
" $KEY_EVENTID = ?"
val selectionArgs =
if (instanceStartTime != 0L)
arrayOf(eventId.toString(), instanceStartTime.toString())
else
arrayOf(eventId.toString())
val cursor = db.query(TABLE_NAME, // a. table
SELECT_COLUMNS, // b. column names
selection, // c. selections
selectionArgs, // d. selections args
null, // e. group by
null, // f. having
null, // g. order by
null) // h. limit
var event: EventAlertRecord? = null
if (cursor != null) {
if (cursor.moveToFirst())
event = cursorToEventRecord(cursor)
cursor.close()
}
return event
}
override fun getEventInstancesImpl(db: SQLiteDatabase, eventId: Long): List<EventAlertRecord> {
val event = getEventImpl(db, eventId, 0L)
if (event != null)
return listOf(event)
else
return listOf<EventAlertRecord>()
}
override fun getEventsImpl(db: SQLiteDatabase): List<EventAlertRecord> {
val ret = LinkedList<EventAlertRecord>()
val cursor = db.query(TABLE_NAME, // a. table
SELECT_COLUMNS, // b. column names
null, // c. selections
null,
null, // e. group by
null, // f. h aving
null, // g. order by
null) // h. limit
if (cursor.moveToFirst()) {
do {
ret.add(cursorToEventRecord(cursor))
} while (cursor.moveToNext())
}
cursor.close()
DevLog.debug(LOG_TAG, "eventsImpl, returnint ${ret.size} requests")
return ret
}
override fun deleteEventImpl(db: SQLiteDatabase, eventId: Long, instanceStartTime: Long): Boolean {
val selection =
if (instanceStartTime != 0L)
" $KEY_EVENTID = ? AND $KEY_INSTANCE_START = ?"
else
" $KEY_EVENTID = ?"
val selectionArgs =
if (instanceStartTime != 0L)
arrayOf(eventId.toString(), instanceStartTime.toString())
else
arrayOf(eventId.toString())
db.delete(TABLE_NAME, selection, selectionArgs)
DevLog.debug(LOG_TAG, "deleteNotification ${eventId}")
return true
}
override fun updateEventsAndInstanceTimesImpl(db: SQLiteDatabase, events: Collection<EventWithNewInstanceTime>): Boolean {
throw NotImplementedError("Don't suppose to use this for V6")
}
override fun deleteEventsImpl(db: SQLiteDatabase, events: Collection<EventAlertRecord>): Int {
throw NotImplementedError("Don't suppose to use this for V6")
}
override fun addEventsImpl(db: SQLiteDatabase, events: List<EventAlertRecord>): Boolean {
throw NotImplementedError("Don't suppose to use this for V6")
}
private fun eventRecordToContentValues(event: EventAlertRecord, includeId: Boolean = false): ContentValues {
val values = ContentValues();
if (includeId)
values.put(KEY_EVENTID, event.eventId);
values.put(KEY_CALENDAR_ID, event.calendarId)
values.put(KEY_NOTIFICATIONID, event.notificationId);
values.put(KEY_TITLE, event.title);
values.put(KEY_DESC, ""); // we have no description anymore
values.put(KEY_START, event.startTime);
values.put(KEY_END, event.endTime);
values.put(KEY_INSTANCE_START, event.instanceStartTime);
values.put(KEY_INSTANCE_END, event.instanceEndTime);
values.put(KEY_LOCATION, event.location);
values.put(KEY_SNOOZED_UNTIL, event.snoozedUntil);
values.put(KEY_LAST_EVENT_FIRE, event.lastStatusChangeTime);
values.put(KEY_IS_DISPLAYED, event.displayStatus.code);
values.put(KEY_COLOR, event.color)
values.put(KEY_ALERT_TIME, event.alertTime)
return values;
}
private fun cursorToEventRecord(cursor: Cursor): EventAlertRecord {
return EventAlertRecord(
calendarId = (cursor.getLong(0) as Long?) ?: -1L,
eventId = cursor.getLong(1),
notificationId = cursor.getInt(2),
title = cursor.getString(3),
desc = "",
startTime = cursor.getLong(4),
endTime = cursor.getLong(5),
instanceStartTime = cursor.getLong(6),
instanceEndTime = cursor.getLong(7),
location = cursor.getString(8),
snoozedUntil = cursor.getLong(9),
lastStatusChangeTime = cursor.getLong(10),
displayStatus = EventDisplayStatus.fromInt(cursor.getInt(11)),
color = cursor.getInt(12),
alertTime = cursor.getLong(13),
isRepeating = false,
isAllDay = false
)
}
companion object {
private const val LOG_TAG = "EventsStorageImplV6"
private const val TABLE_NAME = "requests"
private const val INDEX_NAME = "eventsIdx"
private const val KEY_CALENDAR_ID = "i1"
private const val KEY_EVENTID = "eventId"
private const val KEY_NOTIFICATIONID = "notificationId"
private const val KEY_TITLE = "title"
private const val KEY_DESC = "description"
private const val KEY_START = "start"
private const val KEY_END = "end"
private const val KEY_INSTANCE_START = "i2"
private const val KEY_INSTANCE_END = "i3"
private const val KEY_LOCATION = "location"
private const val KEY_SNOOZED_UNTIL = "snoozeUntil"
private const val KEY_IS_DISPLAYED = "displayed"
private const val KEY_LAST_EVENT_FIRE = "lastFire"
private const val KEY_COLOR = "color"
private const val KEY_ALERT_TIME = "alertTime"
private const val KEY_RESERVED_STR1 = "s1"
private const val KEY_RESERVED_STR2 = "s2"
private const val KEY_RESERVED_STR3 = "s3"
private val SELECT_COLUMNS = arrayOf<String>(
KEY_CALENDAR_ID,
KEY_EVENTID,
KEY_NOTIFICATIONID,
KEY_TITLE,
KEY_START,
KEY_END,
KEY_INSTANCE_START,
KEY_INSTANCE_END,
KEY_LOCATION,
KEY_SNOOZED_UNTIL,
KEY_LAST_EVENT_FIRE,
KEY_IS_DISPLAYED,
KEY_COLOR,
KEY_ALERT_TIME
)
}
}
| gpl-3.0 | dd8fddf38912884521adf2b6fc12bb41 | 35.179558 | 144 | 0.577079 | 4.555478 | false | false | false | false |
MaibornWolff/codecharta | analysis/filter/EdgeFilter/src/main/kotlin/de/maibornwolff/codecharta/filter/edgefilter/ParserDialog.kt | 1 | 1353 | package de.maibornwolff.codecharta.filter.edgefilter
import com.github.kinquirer.KInquirer
import com.github.kinquirer.components.promptInput
import de.maibornwolff.codecharta.tools.interactiveparser.ParserDialogInterface
import mu.KotlinLogging
private val logger = KotlinLogging.logger {}
class ParserDialog {
companion object : ParserDialogInterface {
private const val EXTENSION = "cc.json"
override fun collectParserArgs(): List<String> {
val inputFileName = KInquirer.promptInput(message = "What is the $EXTENSION file that has to be parsed?")
logger.info { "File path: $inputFileName" }
val defaultOutputFileName = getOutputFileName(inputFileName)
val outputFileName: String = KInquirer.promptInput(
message = "What is the name of the output file?",
hint = defaultOutputFileName,
default = defaultOutputFileName
)
val defaultPathSeparator = "/"
val pathSeparator: String = KInquirer.promptInput(
message = "What is the path separator?",
hint = defaultPathSeparator,
default = defaultPathSeparator
)
return listOf(inputFileName, "--output-file=$outputFileName", "--path-separator=$pathSeparator")
}
}
}
| bsd-3-clause | dc8a08b1b7c3a50557841c49748e54ce | 36.583333 | 117 | 0.660015 | 5.455645 | false | false | false | false |
MaibornWolff/codecharta | analysis/import/SVNLogParser/src/main/kotlin/de/maibornwolff/codecharta/importer/svnlogparser/parser/svn/SVNLogParserStrategy.kt | 1 | 6071 | package de.maibornwolff.codecharta.importer.svnlogparser.parser.svn
import de.maibornwolff.codecharta.importer.svnlogparser.input.Modification
import de.maibornwolff.codecharta.importer.svnlogparser.parser.LogLineCollector
import de.maibornwolff.codecharta.importer.svnlogparser.parser.LogParserStrategy
import org.apache.commons.lang3.StringUtils
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatterBuilder
import java.util.function.Predicate
import java.util.stream.Collector
import java.util.stream.Stream
class SVNLogParserStrategy : LogParserStrategy {
override fun parseDate(commitLines: List<String>): OffsetDateTime {
return commitLines
.filter { this.isMetadataLine(it) }
.map { this.parseCommitDate(it) }
.first()
}
private fun parseCommitDate(metadataLine: String): OffsetDateTime {
val splittedLine =
metadataLine.split(("\\" + METADATA_SEPARATOR).toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val commitDateAsString =
splittedLine[DATE_INDEX_IN_METADATA].trim { it <= ' ' }.replace(" \\(.*\\)".toRegex(), "")
return OffsetDateTime.parse(commitDateAsString, DATE_TIME_FORMATTER)
}
override fun parseAuthor(commitLines: List<String>): String {
return commitLines
.filter { this.isMetadataLine(it) }
.map { this.parseAuthor(it) }
.first()
}
private fun isMetadataLine(commitLine: String): Boolean {
return commitLine.startsWith('r') && commitLine.count { it == METADATA_SEPARATOR } >= 3
}
private fun parseAuthor(authorLine: String): String {
val splittedLine =
authorLine.split(("\\" + METADATA_SEPARATOR).toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
return splittedLine[AUTHOR_INDEX_IN_METADATA].trim { it <= ' ' }
}
override fun parseModifications(commitLines: List<String>): List<Modification> {
return commitLines
.filter { this.isFileLine(it) }
.map { this.parseModification(it) }
}
private fun isFileLine(commitLine: String): Boolean {
val commitLineWithoutWhitespacePrefix = stripWhitespacePrefix(commitLine)
if (commitLineWithoutWhitespacePrefix.length < 3) {
return false
}
val firstChar = commitLineWithoutWhitespacePrefix[0]
val secondChar = commitLineWithoutWhitespacePrefix[1]
val thirdChar = commitLineWithoutWhitespacePrefix[2]
return isStatusLetter(firstChar) && Character.isWhitespace(secondChar) && isSlash(thirdChar)
}
internal fun parseModification(fileLine: String): Modification {
val metadataWithoutWhitespacePrefix = stripWhitespacePrefix(fileLine)
val status = Status.byCharacter(metadataWithoutWhitespacePrefix[0])
val metadataWithoutStatusLetter = metadataWithoutWhitespacePrefix.substring(1)
val trimmedFileLine = removeDefaultRepositoryFolderPrefix(metadataWithoutStatusLetter.trim { it <= ' ' })
return when (trimmedFileLine.contains(RENAME_FILE_LINE_IDENTIFIER)) {
true -> parseRenameModification(trimmedFileLine)
else -> parseStandardModification(trimmedFileLine, status)
}
}
private fun parseStandardModification(filePath: String, status: Status): Modification {
return ignoreIfRepresentsFolder(Modification(filePath, status.toModificationType()))
}
private fun parseRenameModification(filePathLine: String): Modification {
val fileNames = filePathLine.split(RENAME_FILE_LINE_IDENTIFIER)
val oldFileNameWithPrefix = fileNames.last().split(":").first()
val oldFileName = removeDefaultRepositoryFolderPrefix(oldFileNameWithPrefix)
val newFileName = fileNames.first()
return ignoreIfRepresentsFolder(Modification(newFileName, oldFileName, Modification.Type.RENAME))
}
override fun creationCommand(): String {
return "svn log --verbose"
}
override fun createLogLineCollector(): Collector<String, *, Stream<List<String>>> {
return LogLineCollector.create(SVN_COMMIT_SEPARATOR_TEST)
}
companion object {
private const val RENAME_FILE_LINE_IDENTIFIER = " (from "
private val SVN_COMMIT_SEPARATOR_TEST =
Predicate<String> { logLine ->
logLine.isNotEmpty() && StringUtils.containsOnly(
logLine,
'-'
) && logLine.length > 70
}
private val DEFAULT_REPOSITORY_FOLDER_PREFIXES = arrayOf("/branches/", "/tags/", "/trunk/", "/")
private val DATE_TIME_FORMATTER = DateTimeFormatterBuilder()
.parseCaseInsensitive()
.append(DateTimeFormatter.ISO_LOCAL_DATE)
.appendLiteral(' ')
.append(DateTimeFormatter.ISO_LOCAL_TIME)
.appendLiteral(' ')
.appendOffset("+HHMM", "")
.toFormatter()
private const val AUTHOR_INDEX_IN_METADATA = 1
private const val DATE_INDEX_IN_METADATA = 2
private const val METADATA_SEPARATOR = '|'
private fun stripWhitespacePrefix(string: String): String {
return StringUtils.stripStart(string, null)
}
private fun isStatusLetter(character: Char): Boolean {
return Status.ALL_STATUS_LETTERS.contains(character)
}
private fun isSlash(char: Char): Boolean {
return char == '/'
}
private fun removeDefaultRepositoryFolderPrefix(path: String): String {
return DEFAULT_REPOSITORY_FOLDER_PREFIXES
.firstOrNull { path.startsWith(it) }
?.let { path.substring(it.length) }
?: path
}
private fun ignoreIfRepresentsFolder(modification: Modification): Modification {
return if (!modification.filename.contains(".")) {
Modification.EMPTY
} else modification
}
}
}
| bsd-3-clause | 6ea43868b84c184b8635bcd751f945b5 | 40.582192 | 115 | 0.667106 | 4.83745 | false | false | false | false |
cketti/okhttp | okhttp-testing-support/src/main/kotlin/okhttp3/internal/io/InMemoryFileSystem.kt | 1 | 3567 | /*
* Copyright (C) 2015 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.internal.io
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.util.IdentityHashMap
import okhttp3.TestUtil.isDescendentOf
import okio.Buffer
import okio.ForwardingSink
import okio.ForwardingSource
import okio.Sink
import okio.Source
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
/** A simple file system where all files are held in memory. Not safe for concurrent use. */
class InMemoryFileSystem : FileSystem, TestRule {
private val files = mutableMapOf<File, Buffer>()
private val openSources = IdentityHashMap<Source, File>()
private val openSinks = IdentityHashMap<Sink, File>()
override fun apply(base: Statement, description: Description): Statement {
return object : Statement() {
override fun evaluate() {
base.evaluate()
ensureResourcesClosed()
}
}
}
fun ensureResourcesClosed() {
val openResources = mutableListOf<String>()
for (file in openSources.values) {
openResources.add("Source for $file")
}
for (file in openSinks.values) {
openResources.add("Sink for $file")
}
check(openResources.isEmpty()) {
"Resources acquired but not closed:\n * ${openResources.joinToString(separator = "\n * ")}"
}
}
@Throws(FileNotFoundException::class)
override fun source(file: File): Source {
val result = files[file] ?: throw FileNotFoundException()
val source: Source = result.clone()
openSources[source] = file
return object : ForwardingSource(source) {
override fun close() {
openSources.remove(source)
super.close()
}
}
}
@Throws(FileNotFoundException::class)
override fun sink(file: File) = sink(file, false)
@Throws(FileNotFoundException::class)
override fun appendingSink(file: File) = sink(file, true)
private fun sink(file: File, appending: Boolean): Sink {
var result: Buffer? = null
if (appending) {
result = files[file]
}
if (result == null) {
result = Buffer()
}
files[file] = result
val sink: Sink = result
openSinks[sink] = file
return object : ForwardingSink(sink) {
override fun close() {
openSinks.remove(sink)
super.close()
}
}
}
@Throws(IOException::class)
override fun delete(file: File) {
files.remove(file)
}
override fun exists(file: File) = files.containsKey(file)
override fun size(file: File) = files[file]?.size ?: 0L
@Throws(IOException::class)
override fun rename(from: File, to: File) {
files[to] = files.remove(from) ?: throw FileNotFoundException()
}
@Throws(IOException::class)
override fun deleteContents(directory: File) {
val i = files.keys.iterator()
while (i.hasNext()) {
val file = i.next()
if (file.isDescendentOf(directory)) i.remove()
}
}
override fun toString() = "InMemoryFileSystem"
}
| apache-2.0 | bb3e8dd0fdb2fbedb9b6e9d8ed1d4a01 | 28.237705 | 97 | 0.687132 | 4.035068 | false | false | false | false |
ansman/kotshi | api/src/main/kotlin/se/ansman/kotshi/KotshiUtils.kt | 1 | 11741 | package se.ansman.kotshi
import com.squareup.moshi.JsonDataException
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Types
import java.lang.reflect.*
/**
* A helper class for Kotshi.
*
* These functions should not be considered public and are subject to change without notice.
*/
@InternalKotshiApi
object KotshiUtils {
@JvmStatic
@InternalKotshiApi
val Type.typeArgumentsOrFail: Array<Type>
get() = (this as? ParameterizedType)?.actualTypeArguments
?: throw IllegalArgumentException(
"""
${Types.getRawType(this).simpleName} is generic and requires you to specify its type
arguments. Don't request an adapter using Type::class.java or value.javaClass but rather using
Types.newParameterizedType.
""".trimIndent()
)
@JvmStatic
@JvmOverloads
@InternalKotshiApi
fun StringBuilder?.appendNullableError(propertyName: String, jsonName: String = propertyName): StringBuilder =
(if (this == null) StringBuilder("The following properties were null: ") else append(", "))
.append(propertyName)
.apply {
if (jsonName != propertyName) {
append(" (JSON name ").append(jsonName).append(')')
}
}
@JvmStatic
@InternalKotshiApi
fun matches(
targetType: Type?,
actualType: Type?,
allowSubClasses: Boolean = false,
allowSuperClasses: Boolean = false,
): Boolean = when (targetType) {
// e.g. Array<...>
is GenericArrayType -> actualType is GenericArrayType &&
matches(targetType.genericComponentType, actualType.genericComponentType, allowSubClasses = true)
// e.g. List<...>
is ParameterizedType -> actualType is ParameterizedType &&
matches(actualType.rawType, targetType.rawType, allowSubClasses, allowSuperClasses) &&
matches(actualType.ownerType, targetType.ownerType, allowSubClasses, allowSuperClasses) &&
targetType.actualTypeArguments.size == actualType.actualTypeArguments.size &&
targetType.actualTypeArguments.allIndexed { i, e -> matches(e, actualType.actualTypeArguments[i]) }
// e.g. E : Number
is TypeVariable<*> -> targetType.bounds.all { matches(it, actualType, allowSubClasses = true) }
// e.g. out Number or in Number
is WildcardType -> targetType.lowerBounds.all { matches(it, actualType, allowSuperClasses = true) } &&
targetType.upperBounds.all { matches(it, actualType, allowSubClasses = true) }
// e.g. String
is Class<*> -> {
fun Type.rawType(): Class<*>? =
when (this) {
is GenericArrayType -> Array::class.java
is ParameterizedType -> rawType.rawType()
is TypeVariable<*> -> null // Type variables should not appear in actual type
is WildcardType -> (lowerBounds.singleOrNull() ?: upperBounds[0]).rawType()
is Class<*> -> this
else -> null
}
val rawType = actualType?.rawType()
rawType != null && when {
allowSubClasses -> targetType.isAssignableFrom(rawType)
allowSuperClasses -> rawType.isAssignableFrom(targetType)
else -> targetType == rawType
}
}
null -> actualType == null
// Unknown type
else -> false
}
private inline fun <E> Array<E>.allIndexed(predicate: (index: Int, element: E) -> Boolean): Boolean {
var i = 0
while (i < size) {
if (!predicate(i, get(i))) {
return false
}
++i
}
return true
}
@JvmStatic
@JvmOverloads
@InternalKotshiApi
fun <T : Annotation> Class<T>.createJsonQualifierImplementation(annotationArguments: Map<String, Any> = emptyMap()): T {
require(isAnnotation) { "$this must be an annotation." }
@Suppress("UNCHECKED_CAST")
return Proxy.newProxyInstance(classLoader, arrayOf<Class<*>>(this), object : InvocationHandler {
private val annotationMethods = declaredMethods
.onEach { method ->
val value = annotationArguments[method.name]
if (value == null) {
require(method.defaultValue != null) {
"Annotation value for method ${method.name} is missing"
}
} else {
val expectedType = when (val returnType = method.returnType) {
Boolean::class.java -> Boolean::class.javaObjectType
Byte::class.java -> Byte::class.javaObjectType
Char::class.java -> Char::class.javaObjectType
Double::class.java -> Double::class.javaObjectType
Float::class.java -> Float::class.javaObjectType
Int::class.java -> Int::class.javaObjectType
Long::class.java -> Long::class.javaObjectType
Short::class.java -> Short::class.javaObjectType
Void::class.java -> Void::class.javaObjectType
else -> returnType
}
require(expectedType.isInstance(value)) {
"Expected value for method ${method.name} to be of type $expectedType but was ${value.javaClass}"
}
}
}
.apply { sortBy { it.name } }
init {
val extraArguments =
annotationArguments.keys - annotationMethods.mapTo(HashSet(annotationMethods.size)) { it.name }
require(extraArguments.isEmpty()) {
"Found annotation values for unknown methods: $extraArguments"
}
}
override fun invoke(proxy: Any, method: Method, args: Array<out Any>?): Any =
when (method.name) {
"annotationType" -> this@createJsonQualifierImplementation
"equals" -> args!![0] === proxy || isInstance(args!![0]) && annotationMethods.all { m ->
annotationValuesEquals(m.invoke(args[0]), annotationArguments[m.name] ?: m.defaultValue)
}
// For the implementation see https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/annotation/Annotation.html#hashCode()
"hashCode" -> annotationMethods.sumOf { m ->
(m.name.hashCode() * 127) xor (annotationArguments[m.name] ?: m.defaultValue).annotationValueHashCode()
}
"toString" -> buildString {
append('@').append(name)
append('(')
var appendSeparator = false
for (m in annotationMethods) {
if (appendSeparator) {
append(", ")
}
val value = annotationArguments[m.name] ?: m.defaultValue
append(m.name).append('=').append(value.annotationValueToString())
appendSeparator = true
}
append(')')
"@$name(${annotationArguments.entries.joinToString()})"
}
else -> annotationArguments[method.name] ?: method.defaultValue
}
private fun annotationValuesEquals(v1: Any?, v2: Any?): Boolean =
when (v1) {
is BooleanArray -> v2 is BooleanArray && v1.contentEquals(v2)
is ByteArray -> v2 is ByteArray && v1.contentEquals(v2)
is CharArray -> v2 is CharArray && v1.contentEquals(v2)
is ShortArray -> v2 is ShortArray && v1.contentEquals(v2)
is IntArray -> v2 is IntArray && v1.contentEquals(v2)
is LongArray -> v2 is LongArray && v1.contentEquals(v2)
is FloatArray -> v2 is FloatArray && v1.contentEquals(v2)
is DoubleArray -> v2 is DoubleArray && v1.contentEquals(v2)
is Array<*> -> v2 is Array<*> && v1.contentEquals(v2)
else -> v1 == v2
}
private fun Any.annotationValueHashCode(): Int =
when (this) {
is BooleanArray -> contentHashCode()
is ByteArray -> contentHashCode()
is CharArray -> contentHashCode()
is ShortArray -> contentHashCode()
is IntArray -> contentHashCode()
is LongArray -> contentHashCode()
is FloatArray -> contentHashCode()
is DoubleArray -> contentHashCode()
is Array<*> -> contentHashCode()
else -> hashCode()
}
private fun Any.annotationValueToString(): String =
when (this) {
is BooleanArray -> contentToString()
is ByteArray -> contentToString()
is CharArray -> contentToString()
is ShortArray -> contentToString()
is IntArray -> contentToString()
is LongArray -> contentToString()
is FloatArray -> contentToString()
is DoubleArray -> contentToString()
is Array<*> -> contentToString()
else -> toString()
}
}) as T
}
@JvmStatic
@InternalKotshiApi
fun JsonReader.nextFloat(): Float =
nextDouble().toFloat().also {
// Double check for infinity after float conversion; many doubles > Float.MAX
if (!isLenient && it.isInfinite()) {
throw JsonDataException("JSON forbids NaN and infinities: $it at path $path")
}
}
@JvmStatic
@InternalKotshiApi
fun JsonReader.nextByte(): Byte = nextIntInRange("a byte", -128, 255).toByte()
@JvmStatic
fun JsonReader.nextShort(): Short = nextIntInRange("a short", -32768, 32767).toShort()
@JvmStatic
@InternalKotshiApi
fun JsonReader.nextChar(): Char =
nextString()
.also {
if (it.length != 1) {
throw JsonDataException("Expected a char but was $it at path $path")
}
}
.single()
@JvmStatic
@InternalKotshiApi
fun JsonWriter.byteValue(byte: Byte): JsonWriter = value(byte.toInt() and 0xff)
@JvmStatic
@InternalKotshiApi
fun JsonWriter.byteValue(byte: Byte?): JsonWriter = if (byte == null) nullValue() else byteValue(byte)
@JvmStatic
@InternalKotshiApi
fun JsonWriter.value(char: Char): JsonWriter = value(char.toString())
@JvmStatic
@InternalKotshiApi
fun JsonWriter.value(char: Char?): JsonWriter = if (char == null) nullValue() else value(char)
@JvmStatic
private fun JsonReader.nextIntInRange(typeMessage: String, min: Int, max: Int): Int =
nextInt().also {
if (it !in min..max) {
throw JsonDataException("Expected $typeMessage but was $it at path $path")
}
}
} | apache-2.0 | d19ea3bad72a3f75bae75bc076aea990 | 43.477273 | 158 | 0.53837 | 5.413094 | false | false | false | false |
mua-uniandes/weekly-problems | atcoder/abc146/abc146_b.kt | 1 | 609 | import java.io.BufferedReader
import java.io.InputStreamReader
fun main() {
val input = BufferedReader( InputStreamReader( System.`in` ) );
val N = input.readLine().toInt();
val S = input.readLine();
val hashMap = HashMap<Char, Int>();
val abecedario = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var i = 0;
while( i < abecedario.length ) {
hashMap.put( abecedario[ i ], i )
i++;
}
i = 0;
var newWord = "";
while( i < S.length ) {
newWord += abecedario[ ( hashMap.get( S[ i ] )!! + N ) % abecedario.length ] ;
i++;
}
print( newWord )
} | gpl-3.0 | 384eeb51d49a061fdf27c5c80caf3d97 | 25.521739 | 88 | 0.566502 | 3.460227 | false | false | false | false |
mua-uniandes/weekly-problems | codeforces/1472/C/1472C.kt | 1 | 585 | import java.io.BufferedReader
import java.io.InputStreamReader
fun main() {
val In = BufferedReader(InputStreamReader(System.`in`))
val cases = In.readLine()!!.toInt()
for(t in 1..cases) {
val N = In.readLine()!!.toInt()
val arr = In.readLine()!!.split(" ").map { it.toDouble() }
val max = DoubleArray(N) { 0.0 }
for(i in N-1 downTo 0 ) {
max[i] = arr[i]
var j = i + arr[i]
if(j < N)
max[i] += max[j.toInt()]
}
max.sortDescending()
println(max[0].toInt())
}
} | gpl-3.0 | ba4c43bf9e762583445a556b27942eb4 | 28.3 | 66 | 0.505983 | 3.567073 | false | false | false | false |
Magneticraft-Team/Magneticraft | ignore/test/guide/components/Link.kt | 2 | 1239 | package com.cout970.magneticraft.guide.components
import com.cout970.magneticraft.guide.BookPage
import com.cout970.magneticraft.guide.IPageComponent
import com.cout970.magneticraft.guide.LinkInfo
import com.cout970.magneticraft.util.vector.Vec2d
@Suppress("unused")
class Link(val target: LinkInfo, val base: PageComponent) : PageComponent(base.position) {
override val id: String = "link"
override val size = base.size
override fun toGuiComponent(parent: BookPage.Gui): IPageComponent = Gui(parent)
private inner class Gui(parent: BookPage.Gui) : PageComponent.Gui(parent) {
// val entryTarget = target.getEntryTarget()
val base = [email protected](parent)
override fun initGui() {
super.initGui()
base.initGui()
}
override fun draw(mouse: Vec2d, time: Double) {
base.draw(mouse, time)
}
override fun postDraw(mouse: Vec2d, time: Double) {
//TODO: Override with link target?
base.postDraw(mouse, time)
}
override fun onLeftClick(mouse: Vec2d): Boolean {
// parent.gui.mc.displayGuiScreen(GuiGuideBook(entryTarget))
return true
}
}
} | gpl-2.0 | 72f41b082e860759f41741bdb2c68f98 | 29.243902 | 90 | 0.663438 | 3.933333 | false | false | false | false |
FrancYescO/PokemonGoBot | src/main/kotlin/ink/abb/pogo/scraper/services/BotService.kt | 1 | 2455 | /**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package ink.abb.pogo.scraper.services
import ink.abb.pogo.scraper.Bot
import ink.abb.pogo.scraper.Context
import ink.abb.pogo.scraper.Settings
import ink.abb.pogo.scraper.startBot
import ink.abb.pogo.scraper.util.credentials.GoogleAutoCredentials
import ink.abb.pogo.scraper.util.io.SettingsJSONWriter
import okhttp3.OkHttpClient
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import java.util.concurrent.CountDownLatch
import javax.annotation.PreDestroy
import kotlin.concurrent.thread
@Service
class BotService {
@Autowired
lateinit var http: OkHttpClient
private val bots: MutableList<Bot> = mutableListOf()
val settingsJSONWriter = SettingsJSONWriter()
fun submitBot(name: String): Settings {
val settings = settingsJSONWriter.load(name)
addBot(startBot(settings, http))
settingsJSONWriter.save(settings) // Is this needed after starting?
return settings
}
@Synchronized
fun addBot(bot: Bot) {
bots.add(bot)
}
@Synchronized
fun removeBot(bot: Bot) {
bots.remove(bot)
}
fun getJSONConfigBotNames(): List<String> {
return settingsJSONWriter.getJSONConfigBotNames()
}
fun getBotContext(name: String): Context {
val bot = bots.find { it.settings.name == name }
bot ?: throw IllegalArgumentException("Bot $name doesn't exists !")
return bot.ctx
}
@Synchronized
fun getAllBotSettings(): List<Settings> {
return bots.map { it.settings.copy(credentials = GoogleAutoCredentials(), restApiPassword = "") }
}
@Synchronized
fun doWithBot(name: String, action: (bot: Bot) -> Unit): Boolean {
val bot = bots.find { it.settings.name == name } ?: return false
action(bot)
return true
}
@PreDestroy
@Synchronized
fun stopAllBots() {
val latch = CountDownLatch(bots.size)
bots.forEach {
thread {
it.stop()
latch.countDown()
}
}
latch.await()
}
}
| gpl-3.0 | b7a6218865022dd651f99738d5c9edd2 | 25.978022 | 105 | 0.67943 | 4.360568 | false | false | false | false |
f-droid/fdroidclient | libs/database/src/main/java/org/fdroid/index/v1/IndexV1Updater.kt | 1 | 3733 | @file:Suppress("DEPRECATION")
package org.fdroid.index.v1
import mu.KotlinLogging
import org.fdroid.CompatibilityChecker
import org.fdroid.database.DbV1StreamReceiver
import org.fdroid.database.FDroidDatabase
import org.fdroid.database.FDroidDatabaseInt
import org.fdroid.database.Repository
import org.fdroid.download.DownloaderFactory
import org.fdroid.index.IndexFormatVersion
import org.fdroid.index.IndexFormatVersion.ONE
import org.fdroid.index.IndexUpdateListener
import org.fdroid.index.IndexUpdateResult
import org.fdroid.index.IndexUpdater
import org.fdroid.index.RepoUriBuilder
import org.fdroid.index.TempFileProvider
import org.fdroid.index.defaultRepoUriBuilder
import org.fdroid.index.setIndexUpdateListener
internal const val SIGNED_FILE_NAME = "index-v1.jar"
public class IndexV1Updater(
database: FDroidDatabase,
private val tempFileProvider: TempFileProvider,
private val downloaderFactory: DownloaderFactory,
private val repoUriBuilder: RepoUriBuilder = defaultRepoUriBuilder,
private val compatibilityChecker: CompatibilityChecker,
private val listener: IndexUpdateListener? = null,
) : IndexUpdater() {
private val log = KotlinLogging.logger {}
public override val formatVersion: IndexFormatVersion = ONE
private val db: FDroidDatabaseInt = database as FDroidDatabaseInt
override fun update(
repo: Repository,
certificate: String?,
fingerprint: String?,
): IndexUpdateResult {
// Normally, we shouldn't allow repository downgrades and assert the condition below.
// However, F-Droid is concerned that late v2 bugs will require users to downgrade to v1,
// as it happened already with the migration from v0 to v1.
if (repo.formatVersion != null && repo.formatVersion != ONE) {
log.error { "Format downgrade for ${repo.address}" }
}
val uri = repoUriBuilder.getUri(repo, SIGNED_FILE_NAME)
val file = tempFileProvider.createTempFile()
val downloader = downloaderFactory.createWithTryFirstMirror(repo, uri, file).apply {
cacheTag = repo.lastETag
setIndexUpdateListener(listener, repo)
}
try {
downloader.download()
if (!downloader.hasChanged()) return IndexUpdateResult.Unchanged
val eTag = downloader.cacheTag
val verifier = IndexV1Verifier(file, certificate, fingerprint)
db.runInTransaction {
val (cert, _) = verifier.getStreamAndVerify { inputStream ->
listener?.onUpdateProgress(repo, 0, 0)
val streamReceiver = DbV1StreamReceiver(db, repo.repoId, compatibilityChecker)
val streamProcessor =
IndexV1StreamProcessor(streamReceiver, certificate, repo.timestamp)
streamProcessor.process(inputStream)
}
// update certificate, if we didn't have any before
val repoDao = db.getRepositoryDao()
if (certificate == null) {
repoDao.updateRepository(repo.repoId, cert)
}
// update RepositoryPreferences with timestamp and ETag (for v1)
val updatedPrefs = repo.preferences.copy(
lastUpdated = System.currentTimeMillis(),
lastETag = eTag,
)
repoDao.updateRepositoryPreferences(updatedPrefs)
}
} catch (e: OldIndexException) {
if (e.isSameTimestamp) return IndexUpdateResult.Unchanged
else throw e
} finally {
file.delete()
}
return IndexUpdateResult.Processed
}
}
| gpl-3.0 | 3c95ebae0779c13327a1f9d9e921a09b | 41.420455 | 98 | 0.672381 | 4.867014 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/ui/preferences/components/GridOverridesPreview.kt | 1 | 1355 | package app.lawnchair.ui.preferences.components
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import app.lawnchair.DeviceProfileOverrides
import app.lawnchair.preferences.preferenceManager
import com.android.launcher3.InvariantDeviceProfile
@Composable
fun GridOverridesPreview(
modifier: Modifier = Modifier,
updateGridOptions: DeviceProfileOverrides.DBGridInfo.() -> Unit
) {
DummyLauncherBox(modifier = modifier) {
WallpaperPreview(modifier = Modifier.fillMaxSize())
DummyLauncherLayout(
idp = createPreviewIdp(updateGridOptions),
modifier = Modifier.fillMaxSize()
)
}
}
@Composable
fun createPreviewIdp(updateGridOptions: DeviceProfileOverrides.DBGridInfo.() -> Unit): InvariantDeviceProfile {
val context = LocalContext.current
val prefs = preferenceManager()
val newIdp by remember {
derivedStateOf {
val options = DeviceProfileOverrides.DBGridInfo(prefs)
updateGridOptions(options)
InvariantDeviceProfile(context, options)
}
}
return newIdp
}
| gpl-3.0 | 7f99c1e7a9830b11b4bfd18ff6ddb294 | 32.04878 | 111 | 0.757196 | 4.721254 | false | false | false | false |
shaeberling/euler | kotlin/src/com/s13g/aoc/aoc2019/Day6.kt | 1 | 1560 | package com.s13g.aoc.aoc2019
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
import kotlin.math.min
/** https://adventofcode.com/2019/day/6 */
class Day6 : Solver {
private var map = mutableMapOf<String, Node>()
override fun solve(lines: List<String>): Result {
map =
lines.map { l -> l.split(")") }
.map { s -> Pair(s[1], Node(s[1], s[0])) }.toMap().toMutableMap()
augmentData()
val solutionA = map.keys.map { n -> countOrbits(n) }.sum()
val solutionB = distance(map["YOU"]!!.orb, map["SAN"]!!.orb, "YOU")
return Result("$solutionA", "$solutionB")
}
private fun countOrbits(node: String): Int {
return if (node == "COM") 0 else 1 + countOrbits(map[node]!!.orb)
}
private fun augmentData() {
map["COM"] = Node("COM")
for (entry in map.filter { !it.value.orb.isBlank() }) {
entry.value.conns.add(map[entry.value.orb]!!)
map[entry.value.orb]!!.conns.add(entry.value)
}
}
private fun distance(from: String, to: String, orig: String): Int? {
if (from == to) return 0
var result: Int? = null
for (conn in map[from]!!.conns.filter { it.name != orig && !it.name.isBlank() }) {
result = bMin(result, distance(conn.name, to, from))
}
if (result != null) result++
return result
}
private fun bMin(a: Int?, b: Int?): Int? {
val min = min(a ?: Int.MAX_VALUE, b ?: Int.MAX_VALUE)
return if (min == Int.MAX_VALUE) null else min
}
data class Node(val name: String, val orb: String = "") {
val conns = mutableSetOf<Node>()
}
} | apache-2.0 | d31d38f7fcc5f915ccb2c4bb70503cdc | 29.607843 | 86 | 0.602564 | 3.190184 | false | false | false | false |
google/horologist | sample/src/main/java/com/google/android/horologist/rotary/RotaryScrollMenuList.kt | 1 | 13526 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.rotary
import androidx.compose.foundation.background
import androidx.compose.foundation.focusable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringArrayResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.Card
import androidx.wear.compose.material.Chip
import androidx.wear.compose.material.ChipDefaults
import androidx.wear.compose.material.CompactChip
import androidx.wear.compose.material.ScalingLazyColumn
import androidx.wear.compose.material.ScalingLazyColumnDefaults
import androidx.wear.compose.material.ScalingLazyListScope
import androidx.wear.compose.material.ScalingLazyListState
import androidx.wear.compose.material.Text
import androidx.wear.compose.material.rememberScalingLazyListState
import com.google.android.horologist.base.ui.components.Title
import com.google.android.horologist.composables.SectionedList
import com.google.android.horologist.compose.rotaryinput.rememberDisabledHaptic
import com.google.android.horologist.compose.rotaryinput.rememberRotaryHapticFeedback
import com.google.android.horologist.compose.rotaryinput.rotaryWithFling
import com.google.android.horologist.compose.rotaryinput.rotaryWithScroll
import com.google.android.horologist.compose.rotaryinput.rotaryWithSnap
import com.google.android.horologist.compose.rotaryinput.toRotaryScrollAdapter
import com.google.android.horologist.sample.R
import com.google.android.horologist.sample.Screen
import kotlin.random.Random
@Composable
fun RotaryMenuScreen(
modifier: Modifier = Modifier,
navigateToRoute: (String) -> Unit,
scalingLazyListState: ScalingLazyListState = rememberScalingLazyListState(),
focusRequester: FocusRequester = remember { FocusRequester() }
) {
SectionedList(
focusRequester = focusRequester,
scalingLazyListState = scalingLazyListState,
modifier = modifier
) {
section(
listOf(
Pair(
R.string.rotarymenu_scroll_list,
Screen.RotaryScrollScreen.route
),
Pair(
R.string.rotarymenu_scroll_with_fling,
Screen.RotaryScrollWithFlingScreen.route
)
)
) {
header {
Title(
text = stringResource(R.string.rotarymenu_scroll),
modifier = Modifier.padding(vertical = 8.dp)
)
}
loaded { item ->
Chip(
label = {
Text(text = stringResource(item.first))
},
modifier = Modifier.fillMaxWidth(),
onClick = { navigateToRoute(item.second) },
colors = ChipDefaults.primaryChipColors()
)
}
}
section(
listOf(
Pair(
R.string.rotarymenu_snap_list,
Screen.RotarySnapListScreen.route
)
)
) {
header {
Title(
text = stringResource(R.string.rotarymenu_snap),
modifier = Modifier.padding(vertical = 8.dp)
)
}
loaded { item ->
Chip(
label = {
Text(text = stringResource(item.first))
},
modifier = Modifier.fillMaxWidth(),
onClick = { navigateToRoute(item.second) },
colors = ChipDefaults.primaryChipColors()
)
}
}
}
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
}
@Composable
fun RotaryScrollScreen(
scalingLazyListState: ScalingLazyListState = rememberScalingLazyListState(),
focusRequester: FocusRequester = remember { FocusRequester() }
) {
ItemsListWithModifier(
modifier = Modifier
.rotaryWithScroll(focusRequester, scalingLazyListState)
.focusRequester(focusRequester)
.focusable(),
scrollableState = scalingLazyListState
) {
ChipsList {}
}
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
}
@Composable
fun RotaryScrollWithFlingOrSnapScreen(
isFling: Boolean,
isSnap: Boolean
) {
val focusRequester = remember { FocusRequester() }
var showList by remember { mutableStateOf(false) }
var hapticsEnabled by remember { mutableStateOf(true) }
var itemTypeIndex by remember { mutableStateOf(0) }
val randomHeights: List<Int> = remember { (0..300).map { Random.nextInt(1, 10) } }
val tenSmallOneBig: List<Int> = remember { (0..4).map { 1 }.plus(20).plus((0..4).map { 1 }) }
if (showList) {
val scalingLazyListState: ScalingLazyListState = rememberScalingLazyListState()
val rotaryHapticFeedback =
if (hapticsEnabled) rememberRotaryHapticFeedback() else rememberDisabledHaptic()
ItemsListWithModifier(
modifier = Modifier
.let {
if (isSnap) it.rotaryWithSnap(
focusRequester,
scalingLazyListState.toRotaryScrollAdapter(),
rotaryHapticFeedback
)
else if (isFling) it.rotaryWithFling(
focusRequester = focusRequester,
scrollableState = scalingLazyListState,
rotaryHaptics = rotaryHapticFeedback
)
else it.rotaryWithScroll(
focusRequester = focusRequester,
scrollableState = scalingLazyListState,
rotaryHaptics = rotaryHapticFeedback
)
}
.focusRequester(focusRequester)
.focusable(),
scrollableState = scalingLazyListState
) {
when (itemTypeIndex) {
0 -> ChipsList { showList = false }
1 -> CardsList(2) { showList = false }
2 -> CardsList(10) { showList = false }
3 -> CardsList(10, randomHeights = randomHeights) { showList = false }
4 -> CardsList(10, itemCount = 10, randomHeights = tenSmallOneBig) {
showList = false
}
else -> {}
}
}
LaunchedEffect(Unit) {
focusRequester.requestFocus()
}
} else {
ScrollPreferences(
itemTypeIndex = itemTypeIndex,
hapticsEnabled = hapticsEnabled,
onShowListClicked = { showList = true },
onItemTypeIndexChanged = { itemTypeIndex = it },
onHapticsToggled = { hapticsEnabled = !hapticsEnabled }
)
}
}
@Composable
private fun ScrollPreferences(
itemTypeIndex: Int,
hapticsEnabled: Boolean,
onShowListClicked: () -> Unit,
onItemTypeIndexChanged: (Int) -> Unit,
onHapticsToggled: () -> Unit
) {
val itemTypes = stringArrayResource(R.array.rotarymenu_item_sizes).toList()
ScalingLazyColumn(
modifier = Modifier
.fillMaxSize()
) {
item {
Text(
text = stringResource(R.string.rotarymenu_chips_size),
textAlign = TextAlign.Center
)
}
item {
Chip(
onClick = {
onItemTypeIndexChanged((itemTypeIndex + 1) % itemTypes.size)
},
colors = ChipDefaults.primaryChipColors(),
border = ChipDefaults.chipBorder(),
content = {
Text(
text = itemTypes[itemTypeIndex],
textAlign = TextAlign.Center,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
}
)
}
item {
Chip(
onClick = {
onHapticsToggled()
},
colors = ChipDefaults.primaryChipColors(),
border = ChipDefaults.chipBorder(),
content = {
Text(
text = stringResource(
if (hapticsEnabled) R.string.rotarymenu_haptics_on
else R.string.rotarymenu_haptics_off
),
textAlign = TextAlign.Center,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
)
}
item {
CompactChip(
onClick = { onShowListClicked() },
label = {
Text(
text = stringResource(R.string.rotarymenu_show_list),
textAlign = TextAlign.Center
)
}
)
}
}
}
@Composable
private fun ItemsListWithModifier(
modifier: Modifier,
scrollableState: ScalingLazyListState,
items: ScalingLazyListScope.() -> Unit
) {
val flingBehavior = ScalingLazyColumnDefaults.snapFlingBehavior(state = scrollableState)
ScalingLazyColumn(
modifier = modifier,
state = scrollableState,
flingBehavior = flingBehavior,
scalingParams = ScalingLazyColumnDefaults.scalingParams(),
horizontalAlignment = Alignment.Start,
verticalArrangement = Arrangement.spacedBy(
space = 4.dp,
alignment = Alignment.Top
),
content = items
)
}
private fun ScalingLazyListScope.CardsList(
maxLines: Int = 10,
itemCount: Int = 300,
randomHeights: List<Int>? = null,
onItemClicked: () -> Unit
) {
val colors = listOf(Color.Green, Color.Yellow, Color.Cyan, Color.Magenta)
items(itemCount) {
Card(
modifier = Modifier.fillMaxWidth(),
onClick = onItemClicked
) {
Column {
Row {
Box(
modifier = Modifier
.size(15.dp)
.clip(CircleShape)
.background(color = colors[it % colors.size])
)
Text(text = "#$it")
}
Text(
maxLines = randomHeights?.let { height -> height[it] } ?: maxLines,
text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat"
)
}
}
}
}
internal fun ScalingLazyListScope.ChipsList(
onItemClicked: () -> Unit
) {
val colors = listOf(Color.Green, Color.Yellow, Color.Cyan, Color.Magenta)
items(300) {
Chip(
modifier = Modifier.fillMaxWidth(),
onClick = onItemClicked,
label = { Text("List item $it") },
colors = ChipDefaults.secondaryChipColors(),
icon = {
Box(
modifier = Modifier
.size(15.dp)
.clip(CircleShape)
.background(color = colors[it % 4])
)
}
)
}
}
| apache-2.0 | ca5ca7ba0c8e8b4259240a5a780f211a | 35.165775 | 491 | 0.587092 | 5.192322 | false | false | false | false |
jlangch/kt-config | src/main/kotlin/org/jlang/kt_config/impl/namespace.kt | 1 | 4046 | /*
* Copyright 2017 JLang
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jlang.kt_config.impl
enum class TokenType {
EOF, // end-of-file
IDENTIFIER, // abc
PATH, // abc.def.ghi
STRING, // "..." or '...'
ANY, // anything
EQUALS, // '='
LBRACE, // '{'
RBRACE, // '}'
LBRACK, // '['
RBRACK, // ']'
COMMA // ','
}
class Position(val row: Int = 1, val col: Int = 1) {
override fun toString(): String = "($row, $col)"
}
class Token(val type: TokenType, val data: String, val pos: Position) {
constructor(type: TokenType, ch: Character)
: this(type, ch.char.toString(), ch.pos)
companion object {
fun eof(pos: Position): Token = Token(TokenType.EOF, "", pos)
}
fun eof() = isType(TokenType.EOF)
fun isType(vararg types: TokenType): Boolean = types.any { it == type }
fun isNotType(vararg types: TokenType): Boolean = types.all { it != type }
override fun toString(): String = "\"$data\" ($type) at $pos"
}
data class Character(val char: Char?, val pos: Position) {
fun eof() = char == null
fun isEscapeChar(): Boolean = char == '\\'
fun isChar(vararg chars: Char): Boolean = chars.any { it == char }
fun isNotChar(vararg chars: Char): Boolean = chars.all { it != char }
override fun toString(): String {
return when (char) {
null -> "<eof> at $pos"
'\n' -> "<lf> at $pos"
'\r' -> "<cr> at $pos"
'\t' -> "<tab> at $pos"
else -> "$char at " + pos
}
}
}
class StringReader(private val text: String): Iterator<Character> {
private val TAB_WIDTH = 4
private var cursor = 0
private var textPos = Position()
override fun hasNext(): Boolean = true
override fun next(): Character = Character(nextChar(), textPos).also { c -> updatePosition(c) }
private fun nextChar(): Char? = if (cursor < text.length) text[cursor++] else null
private fun updatePosition(ch: Character): Unit {
textPos = incPosition(textPos, ch.char)
}
private fun incPosition(pos: Position, ch: Char?): Position {
return when (ch) {
null -> pos
'\n' -> Position(pos.row + 1, 1)
'\r' -> pos
'\t' -> Position(pos.row, pos.col + TAB_WIDTH)
else -> Position(pos.row, pos.col + 1)
}
}
}
fun composePath(base: String, key: String, index: Int): String {
return composePath(base, composePath(key, index))
}
fun composePath(key: String, index: Int): String {
return composePath(key, index.toString())
}
fun composePath(base: String, path: String): String {
return if (base.isEmpty()) path else base + "." + path
}
fun splitPath(path: String): List<String> = path.split('.')
fun isListPath(path: String): Boolean {
val numberRegex = Regex("^[0-9]+${'$'}")
val tail = splitPath(path).last()
return tail == "size" || numberRegex.matches(tail)
}
fun getPrefixedEnvironmentVariables(prefix: String): Map<String,String> =
System.getenv()
.filterValues { v -> v != null }
.mapKeys { entry -> prefix + "." + entry.key }
fun getPrefixedSystemProperties(prefix: String): Map<String,String> =
System.getProperties()
.filterValues { v -> v != null }
.mapValues { entry -> entry.value.toString() }
.mapKeys { entry -> prefix + "." + entry.key }
| apache-2.0 | ae93fca403f1a257b5a45cfaabc758bd | 28.75 | 99 | 0.585764 | 3.868069 | false | false | false | false |
google/horologist | network-awareness/src/main/java/com/google/android/horologist/networks/status/NetworkRepositoryImpl.kt | 1 | 7723 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.networks.status
import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.net.LinkProperties
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import androidx.activity.ComponentActivity
import com.google.android.horologist.networks.ExperimentalHorologistNetworksApi
import com.google.android.horologist.networks.data.NetworkInfo
import com.google.android.horologist.networks.data.NetworkStatus
import com.google.android.horologist.networks.data.Networks
import com.google.android.horologist.networks.data.Status
import com.google.android.horologist.networks.data.id
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import java.net.InetAddress
import java.time.Instant
import java.util.concurrent.ConcurrentHashMap
@SuppressLint("MissingPermission")
@ExperimentalHorologistNetworksApi
public class NetworkRepositoryImpl(
private val connectivityManager: ConnectivityManager,
private val coroutineScope: CoroutineScope
) : NetworkRepository {
private val networks = ConcurrentHashMap<String, Network>()
private val networkBuilders = ConcurrentHashMap<String, NetworkStatusBuilder>()
private val linkAddresses = ConcurrentHashMap<InetAddress, String>()
private var priorityNetwork: Network? = null
private var initialised = false
private val _networkStatus: MutableStateFlow<Networks>
override val networkStatus: StateFlow<Networks>
get() = _networkStatus
private val networkCallback = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
networks[network.id] = network
getOrBuild(network, Status.Available)
postUpdate()
}
override fun onLost(network: Network) {
val networkString = network.id
getOrBuild(network, Status.Lost)
coroutineScope.launch {
delay(5000)
if (networkBuilders[networkString]?.status == Status.Lost) {
networks.remove(networkString)
}
}
postUpdate()
}
override fun onLosing(network: Network, maxMsToLive: Int) {
getOrBuild(network, Status.Losing(Instant.now().plusMillis(maxMsToLive.toLong())))
postUpdate()
}
override fun onCapabilitiesChanged(
network: Network,
networkCapabilities: NetworkCapabilities
) {
getOrBuild(network).apply {
this.networkCapabilities = networkCapabilities
}
postUpdate()
}
override fun onLinkPropertiesChanged(
network: Network,
networkLinkProperties: LinkProperties
) {
getOrBuild(network).apply {
linkProperties = networkLinkProperties
networkLinkProperties.linkAddresses.forEach {
linkAddresses[it.address] = network.id
}
}
postUpdate()
}
}
override fun updateNetworkAvailability(network: Network) {
val id = network.id
if (!networks.contains(id)) {
networks[id] = network
getOrBuild(network, Status.Available).apply {
networkCapabilities = connectivityManager.getNetworkCapabilities(network)
}
postUpdate()
}
}
init {
@Suppress("DEPRECATION")
connectivityManager.allNetworks.forEach { network ->
getOrBuild(network).apply {
connectivityManager.getNetworkCapabilities(network)?.let {
this.networkCapabilities = it
}
connectivityManager.getLinkProperties(network)?.let {
this.linkProperties = it
}
}
}
val networkRequest = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addTransportType(NetworkCapabilities.TRANSPORT_BLUETOOTH)
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build()
connectivityManager.registerNetworkCallback(networkRequest, networkCallback)
_networkStatus = MutableStateFlow(buildStatus())
initialised = true
}
private fun getOrBuild(network: Network, status: Status? = null): NetworkStatusBuilder {
return networkBuilders.getOrPut(
network.id
) {
NetworkStatusBuilder(network = network, id = network.toString())
}.apply {
if (status != null) {
this.status = status
}
}
}
private fun postUpdate() {
if (initialised) {
_networkStatus.value = buildStatus()
}
}
public fun close() {
connectivityManager.unregisterNetworkCallback(networkCallback)
}
private fun buildStatus(): Networks {
val allNetworks = networkBuilders.filter { (_, builder) ->
builder.status != Status.Lost
}.values.map { it.buildNetworkStatus() }
val priorityNetwork = priorityNetwork
if (priorityNetwork != null) {
val priorityNetworkStatus = allNetworks.find { it.id == priorityNetwork.id }
if (priorityNetworkStatus != null) {
return Networks(
activeNetwork = priorityNetworkStatus,
networks = allNetworks
)
}
}
val connectedNetwork = connectivityManager.activeNetwork
val activeNetwork = allNetworks.find { it.id == connectedNetwork?.id }
return Networks(
activeNetwork = activeNetwork,
networks = allNetworks
)
}
override fun networkByAddress(localAddress: InetAddress): NetworkStatus? {
val network = linkAddresses[localAddress]?.let {
networkBuilders[it]?.buildNetworkStatus()
}
// TODO assume null is bluetooth if available
@Suppress("FoldInitializerAndIfToElvis")
if (network == null) {
return networkBuilders.values.firstOrNull { it.type is NetworkInfo.Bluetooth }
?.buildNetworkStatus()
}
return network
}
public companion object {
@ExperimentalHorologistNetworksApi
public fun fromContext(
application: Context,
coroutineScope: CoroutineScope
): NetworkRepositoryImpl {
val connectivityManager =
application.getSystemService(ComponentActivity.CONNECTIVITY_SERVICE) as ConnectivityManager
return NetworkRepositoryImpl(
connectivityManager,
coroutineScope
)
}
}
}
| apache-2.0 | 947580b2dbeacf8b17e2410f096fd1cf | 33.172566 | 107 | 0.649618 | 5.473423 | false | false | false | false |
vase4kin/TeamCityApp | features/drawer/src/main/java/teamcityapp/features/drawer/view/BaseDrawerItem.kt | 1 | 3281 | /*
* Copyright 2020 Andrey Tolpeev
*
* 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 teamcityapp.features.drawer.view
import teamcityapp.features.drawer.R
import teamcityapp.libraries.storage.models.UserAccount
abstract class BaseDrawerItem(
open val id: Int,
open val type: DrawerType
)
const val TYPE_ACCOUNT = 0
const val TYPE_MENU = 1
const val TYPE_ACCOUNTS_DIVIDER = 2
const val TYPE_DIVIDER = 3
const val TYPE_BOTTOM = 4
enum class DrawerType(val type: Int) {
ACCOUNT(TYPE_ACCOUNT),
ABOUT(TYPE_MENU),
NEW_ACCOUNT(TYPE_MENU),
MANAGE_ACCOUNTS(TYPE_MENU),
ACCOUNTS_DIVIDER(TYPE_ACCOUNTS_DIVIDER),
DIVIDER(TYPE_DIVIDER),
BOTTOM(TYPE_BOTTOM),
SETTINGS(TYPE_MENU),
AGENTS(TYPE_MENU)
}
class AccountDrawerItem(
val account: UserAccount
) : BaseDrawerItem(
account.hashCode(),
DrawerType.ACCOUNT
)
abstract class MenuDrawerItem(
override val id: Int,
override val type: DrawerType,
val imageRes: Int,
val stringRes: Int
) : BaseDrawerItem(id, type)
private const val ID_NEW_ACCOUNT = "ID_NEW_ACCOUNT"
private const val ID_MANAGE_ACCOUNTS = "ID_MANAGE_ACCOUNTS"
private const val ID_ABOUT = "ID_ABOUT"
private const val ID_ACCOUNTS_DIVIDER = "ID_ACCOUNTS_DIVIDER"
private const val ID_DIVIDER = "ID_DIVIDER"
private const val ID_BOTTOM = "ID_BOTTOM"
private const val ID_SETTINGS = "ID_SETTINGS"
private const val ID_AGENTS = "ID_SETTINGS"
class AccountsDividerDrawerItem : BaseDrawerItem(
ID_ACCOUNTS_DIVIDER.hashCode(),
DrawerType.ACCOUNTS_DIVIDER
)
class DividerDrawerItem : BaseDrawerItem(
ID_DIVIDER.hashCode(),
DrawerType.DIVIDER
)
class BottomDrawerItem : BaseDrawerItem(
ID_BOTTOM.hashCode(),
DrawerType.BOTTOM
)
class NewAccountDrawerItem : MenuDrawerItem(
id = ID_NEW_ACCOUNT.hashCode(),
type = DrawerType.NEW_ACCOUNT,
imageRes = R.drawable.ic_accounts_add,
stringRes = R.string.text_add_account
)
class ManageAccountsDrawerItem : MenuDrawerItem(
id = ID_MANAGE_ACCOUNTS.hashCode(),
type = DrawerType.MANAGE_ACCOUNTS,
imageRes = R.drawable.ic_accounts,
stringRes = R.string.text_manage_accounts
)
class AboutDrawerItem : MenuDrawerItem(
id = ID_ABOUT.hashCode(),
type = DrawerType.ABOUT,
imageRes = R.drawable.ic_info_outline_black_24dp,
stringRes = R.string.drawer_item_about
)
class SettingsDrawerItem : MenuDrawerItem(
id = ID_SETTINGS.hashCode(),
type = DrawerType.SETTINGS,
imageRes = R.drawable.ic_settings_black_24dp,
stringRes = R.string.drawer_item_settings
)
class AgentsDrawerItem : MenuDrawerItem(
id = ID_AGENTS.hashCode(),
type = DrawerType.AGENTS,
imageRes = R.drawable.ic_directions_railway_black_24dp,
stringRes = R.string.drawer_item_agents
)
| apache-2.0 | c286a98f29339675cc4a4b90bed2262e | 27.284483 | 75 | 0.73057 | 3.70316 | false | false | false | false |
beyama/winter | winter-testing/src/test/kotlin/io/jentz/winter/testing/ComponentBuilderExtTest.kt | 1 | 1158 | package io.jentz.winter.testing
import io.jentz.winter.graph
import io.kotlintest.shouldBe
import org.junit.jupiter.api.Test
import org.mockito.Spy
import javax.inject.Named
@Suppress("unused")
class ComponentBuilderExtTest {
private val testField = 12
@Mock
@Named("mock field")
private val mockField = "mock field"
@field:Spy
@field:Named("spy field")
private val spyField = "spy field"
@Mock
@Named("mock property")
val mockProperty = "mock property"
@Test
fun `#property should register property by KProperty1 instance`() {
graph {
val source = this@ComponentBuilderExtTest
property(source, source::class.getDeclaredMemberProperty("testField"))
}.instance<Int>().shouldBe(12)
}
@Test
fun `#bindAllMocks should provide all Mock or Spy annotated fields`() {
val graph = graph { bindAllMocks(this@ComponentBuilderExtTest) }
graph.instance<String>("mock field").shouldBe("mock field")
graph.instance<String>("spy field").shouldBe("spy field")
graph.instance<String>("mock property").shouldBe("mock property")
}
}
| apache-2.0 | 476ab9621794de244ffe382cc692b30c | 26.571429 | 82 | 0.676166 | 4.257353 | false | true | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.