content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.flexpoker.pushnotificationhandlers
import com.flexpoker.framework.pushnotifier.PushNotificationHandler
import com.flexpoker.pushnotifications.TickActionOnTimerPushNotification
import com.flexpoker.util.MessagingConstants
import org.springframework.messaging.simp.SimpMessageSendingOperations
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Component
import javax.inject.Inject
@Component
class TickActionOnTimerPushNotificationHandler @Inject constructor(private val messagingTemplate: SimpMessageSendingOperations) :
PushNotificationHandler<TickActionOnTimerPushNotification> {
@Async
override fun handle(pushNotification: TickActionOnTimerPushNotification) {
messagingTemplate.convertAndSend(
String.format(MessagingConstants.TICK_ACTION_ON_TIMER, pushNotification.gameId, pushNotification.tableId),
pushNotification.number)
}
} | src/main/kotlin/com/flexpoker/pushnotificationhandlers/TickActionOnTimerPushNotificationHandler.kt | 1752631915 |
/*
* Copyright (C) 2018 Andrzej Ressel ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.jereksel.libresubstratum.utils
object ListUtils {
fun <T> List<T>.replace(filter: (T) -> Boolean, map: (T) -> (T)): List<T> {
val i = indexOfFirst(filter)
return replace(i, map)
}
fun <T> List<T>.replace(i: Int, map: (T) -> (T)): List<T> {
val before = take(i)
val el = get(i)
val after = drop(i+1)
return before + map(el) + after
}
} | app/src/main/kotlin/com/jereksel/libresubstratum/utils/ListUtils.kt | 1852111051 |
/*
* Copyright 2016-2020 JetBrains s.r.o.
* Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file.
*/
import jetbrains.buildServer.configs.kotlin.v2019_2.Project
fun Project.additionalConfiguration() {
} | .teamcity/additionalConfiguration.kt | 2734477717 |
package net.nemerosa.ontrack.graphql.support
import net.nemerosa.ontrack.graphql.schema.UserError
import net.nemerosa.ontrack.model.exceptions.InputException
import javax.validation.ConstraintViolation
class MutationInputValidationException(
val violations: Set<ConstraintViolation<*>>
) : InputException(
asString(violations)
) {
companion object {
fun asString(violations: Set<ConstraintViolation<*>?>): String =
violations.filterNotNull().joinToString(", ") { cv ->
"${cv.propertyPath}: ${cv.message}"
}
fun asUserError(cv: ConstraintViolation<*>) = UserError(
message = cv.message,
exception = MutationInputValidationException::class.java.name,
location = cv.propertyPath.toString()
)
}
}
| ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/support/MutationInputValidationException.kt | 1402559998 |
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.gradle.plugin.konan
import groovy.lang.Closure
import org.gradle.api.Task
import org.gradle.api.file.FileCollection
import org.gradle.api.internal.project.ProjectInternal
import org.jetbrains.kotlin.gradle.plugin.tasks.*
import org.jetbrains.kotlin.konan.target.Family
import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.konan.target.KonanTarget.WASM32
import java.io.File
abstract class KonanCompileConfig<T: KonanCompileTask>(name: String,
type: Class<T>,
project: ProjectInternal,
targets: Iterable<String>)
: KonanBuildingConfig<T>(name, type, project, targets), KonanCompileSpec {
protected abstract val typeForDescription: String
override fun generateTaskDescription(task: T) =
"Build the Kotlin/Native $typeForDescription '${task.name}' for target '${task.konanTarget}'"
override fun generateAggregateTaskDescription(task: Task) =
"Build the Kotlin/Native $typeForDescription '${task.name}' for all supported and declared targets"
override fun generateTargetAliasTaskDescription(task: Task, targetName: String) =
"Build the Kotlin/Native $typeForDescription '${task.name}' for target '$targetName'"
override fun srcDir(dir: Any) = forEach { it.srcDir(dir) }
override fun srcFiles(vararg files: Any) = forEach { it.srcFiles(*files) }
override fun srcFiles(files: Collection<Any>) = forEach { it.srcFiles(files) }
override fun nativeLibrary(lib: Any) = forEach { it.nativeLibrary(lib) }
override fun nativeLibraries(vararg libs: Any) = forEach { it.nativeLibraries(*libs) }
override fun nativeLibraries(libs: FileCollection) = forEach { it.nativeLibraries(libs) }
@Deprecated("Use commonSourceSets instead", ReplaceWith("commonSourceSets(sourceSetName)"))
override fun commonSourceSet(sourceSetName: String) = forEach { it.commonSourceSets(sourceSetName) }
override fun commonSourceSets(vararg sourceSetNames: String) = forEach { it.commonSourceSets(*sourceSetNames) }
override fun enableMultiplatform(flag: Boolean) = forEach { it.enableMultiplatform(flag) }
override fun linkerOpts(values: List<String>) = forEach { it.linkerOpts(values) }
override fun linkerOpts(vararg values: String) = forEach { it.linkerOpts(*values) }
override fun enableDebug(flag: Boolean) = forEach { it.enableDebug(flag) }
override fun noStdLib(flag: Boolean) = forEach { it.noStdLib(flag) }
override fun noMain(flag: Boolean) = forEach { it.noMain(flag) }
override fun enableOptimizations(flag: Boolean) = forEach { it.enableOptimizations(flag) }
override fun enableAssertions(flag: Boolean) = forEach { it.enableAssertions(flag) }
override fun entryPoint(entryPoint: String) = forEach { it.entryPoint(entryPoint) }
override fun measureTime(flag: Boolean) = forEach { it.measureTime(flag) }
override fun dependencies(closure: Closure<Unit>) = forEach { it.dependencies(closure) }
}
open class KonanProgram(name: String,
project: ProjectInternal,
targets: Iterable<String> = project.konanExtension.targets
) : KonanCompileConfig<KonanCompileProgramTask>(name,
KonanCompileProgramTask::class.java,
project,
targets
) {
override val typeForDescription: String
get() = "executable"
override val defaultBaseDir: File
get() = project.konanBinBaseDir
}
open class KonanDynamic(name: String,
project: ProjectInternal,
targets: Iterable<String> = project.konanExtension.targets)
: KonanCompileConfig<KonanCompileDynamicTask>(name,
KonanCompileDynamicTask::class.java,
project,
targets
) {
override val typeForDescription: String
get() = "dynamic library"
override val defaultBaseDir: File
get() = project.konanBinBaseDir
override fun targetIsSupported(target: KonanTarget): Boolean = target != WASM32
}
open class KonanFramework(name: String,
project: ProjectInternal,
targets: Iterable<String> = project.konanExtension.targets)
: KonanCompileConfig<KonanCompileFrameworkTask>(name,
KonanCompileFrameworkTask::class.java,
project,
targets
) {
override val typeForDescription: String
get() = "framework"
override val defaultBaseDir: File
get() = project.konanBinBaseDir
override fun targetIsSupported(target: KonanTarget): Boolean =
target.family.isAppleFamily
}
open class KonanLibrary(name: String,
project: ProjectInternal,
targets: Iterable<String> = project.konanExtension.targets)
: KonanCompileConfig<KonanCompileLibraryTask>(name,
KonanCompileLibraryTask::class.java,
project,
targets
) {
override val typeForDescription: String
get() = "library"
override val defaultBaseDir: File
get() = project.konanLibsBaseDir
}
open class KonanBitcode(name: String,
project: ProjectInternal,
targets: Iterable<String> = project.konanExtension.targets)
: KonanCompileConfig<KonanCompileBitcodeTask>(name,
KonanCompileBitcodeTask::class.java,
project,
targets
) {
override val typeForDescription: String
get() = "bitcode"
override fun generateTaskDescription(task: KonanCompileBitcodeTask) =
"Generates bitcode for the artifact '${task.name}' and target '${task.konanTarget}'"
override fun generateAggregateTaskDescription(task: Task) =
"Generates bitcode for the artifact '${task.name}' for all supported and declared targets'"
override fun generateTargetAliasTaskDescription(task: Task, targetName: String) =
"Generates bitcode for the artifact '${task.name}' for '$targetName'"
override val defaultBaseDir: File
get() = project.konanBitcodeBaseDir
} | tools/kotlin-native-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/plugin/konan/KonanCompileConfig.kt | 1916824071 |
package ch.bailu.aat_gtk.view.map.control
import ch.bailu.aat_gtk.app.GtkAppContext
import ch.bailu.aat_gtk.config.Layout
import ch.bailu.aat_gtk.config.Strings
import ch.bailu.aat_gtk.lib.extensions.margin
import ch.bailu.aat_gtk.lib.extensions.setMarkup
import ch.bailu.aat_lib.gpx.GpxInformation
import ch.bailu.aat_lib.gpx.GpxPointNode
import ch.bailu.aat_lib.html.MarkupBuilderGpx
import ch.bailu.gtk.GTK
import ch.bailu.gtk.gtk.*
import ch.bailu.gtk.type.Str
class NodeInfo {
private val markupBuilder = MarkupBuilderGpx(GtkAppContext.storage, PangoMarkupConfig)
private val label = Label(Str.NULL).apply {
margin(Layout.margin)
}
private val scrolled = ScrolledWindow().apply {
child = label
setSizeRequest(Layout.windowWidth-Layout.barSize*2-Layout.margin*2,Layout.windowHeight/5)
}
val box = Box(Orientation.VERTICAL,0).apply {
addCssClass(Strings.mapControl)
margin(Layout.margin)
append(scrolled)
valign = Align.START
halign = Align.CENTER
visible = GTK.FALSE
}
fun showCenter() {
box.halign = Align.CENTER
box.visible = GTK.TRUE
}
fun showLeft() {
box.halign = Align.START
box.visible = GTK.TRUE
}
fun showRight() {
box.halign = Align.END
box.visible = GTK.TRUE
}
fun hide() {
box.visible = GTK.FALSE
}
fun displayNode(info: GpxInformation, node: GpxPointNode, index: Int) {
markupBuilder.appendInfo(info, index)
markupBuilder.appendNode(node, info)
markupBuilder.appendAttributes(node.attributes)
label.setMarkup(markupBuilder.toString())
markupBuilder.clear()
}
}
| aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/view/map/control/NodeInfo.kt | 4247153800 |
/*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2020 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.rpc
import android.graphics.Bitmap
import android.os.Parcel
import android.os.Parcelable
class ImageWrapper(var image: Bitmap?, var projectName: String?, var path: String?) : Parcelable {
private constructor(parcel: Parcel) : this(parcel.readValue(Bitmap::class.java.classLoader) as Bitmap?,
parcel.readString(), parcel.readString())
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, arg1: Int) {
dest.writeValue(image)
dest.writeString(projectName)
dest.writeString(path)
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<ImageWrapper> = object : Parcelable.Creator<ImageWrapper> {
override fun createFromParcel(parcel: Parcel) = ImageWrapper(parcel)
override fun newArray(size: Int) = arrayOfNulls<ImageWrapper>(size)
}
}
}
| android/BOINC/app/src/main/java/edu/berkeley/boinc/rpc/ImageWrapper.kt | 93134835 |
package com.github.rssreader.base.presentation.presenter
interface Presenter<in T> {
fun attachTo(view: T)
fun destroy()
} | app/src/main/java/com/github/rssreader/base/presentation/presenter/Presenter.kt | 1942461386 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin
import com.demonwav.mcdev.framework.EdtInterceptor
import com.demonwav.mcdev.platform.mixin.inspection.reference.UnnecessaryQualifiedMemberReferenceInspection
import org.intellij.lang.annotations.Language
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
@ExtendWith(EdtInterceptor::class)
@DisplayName("Unnecessary Qualified Member Reference Inspection Tests")
class UnnecessaryQualifiedMemberReferenceInspectionTest : BaseMixinTest() {
private fun doTest(@Language("JAVA") code: String) {
buildProject {
dir("test") {
java("UnnecessaryQualifiedMemberReferenceMixin.java", code)
}
}
fixture.enableInspections(UnnecessaryQualifiedMemberReferenceInspection::class)
fixture.checkHighlighting(false, false, true)
}
@Test
@DisplayName("Unnecessary Qualification")
fun unnecessaryQualification() {
doTest(
"""
package test;
import com.demonwav.mcdev.mixintestdata.unnecessaryQualifiedMemberReference.MixedIn;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
@Mixin(MixedIn.class)
class UnnecessaryQualifiedMemberReferenceMixin {
@Inject(method = <weak_warning descr="Unnecessary qualified reference to 'method' in target class">"Ltest/MixedIn;method"</weak_warning>, at = @At("HEAD"))
public void onMethod() {
}
}
"""
)
}
@Test
@DisplayName("No unnecessary Qualification")
fun noUnnecessaryQualification() {
doTest(
"""
package test;
import com.demonwav.mcdev.mixintestdata.unnecessaryQualifiedMemberReference.MixedIn;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
@Mixin(MixedIn.class)
class UnnecessaryQualifiedMemberReferenceMixin {
@Inject(method = "method", at = @At("HEAD"))
public void onMethod() {
}
}
"""
)
}
@Test
@DisplayName("Unnecessary Qualification Multiple Targets")
fun unnecessaryQualificationMultipleTargets() {
doTest(
"""
package test;
import com.demonwav.mcdev.mixintestdata.unnecessaryQualifiedMemberReference.MixedIn;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
@Mixin(MixedIn.class)
class UnnecessaryQualifiedMemberReferenceMixin {
@Inject(method = {<weak_warning descr="Unnecessary qualified reference to 'method' in target class">"Ltest/MixedIn;method"</weak_warning>, "otherMethod"}, at = @At("HEAD"))
public void onMethod() {
}
}
"""
)
}
@Test
@DisplayName("No Unnecessary Qualification Multiple Targets")
fun noUnnecessaryQualificationMultipleTargets() {
doTest(
"""
package test;
import com.demonwav.mcdev.mixintestdata.unnecessaryQualifiedMemberReference.MixedIn;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
@Mixin(MixedIn.class)
class UnnecessaryQualifiedMemberReferenceMixin {
@Inject(method = {"method", "otherMethod"}, at = @At("HEAD"))
public void onMethod() {
}
}
"""
)
}
}
| src/test/kotlin/platform/mixin/UnnecessaryQualifiedMemberReferenceInspectionTest.kt | 2947695921 |
package io.gitlab.arturbosch.tinbo.notes
import io.gitlab.arturbosch.tinbo.api.config.TinboMode
/**
* @author Artur Bosch
*/
object NotesMode : TinboMode {
override val id: String = "note"
override val helpIds: Array<String> = arrayOf(id, "edit", "share", "mode")
override val editAllowed: Boolean = true
override val isSummarizable: Boolean = false
}
| tinbo-notes/src/main/kotlin/io/gitlab/arturbosch/tinbo/notes/NotesMode.kt | 1524651041 |
package co.nums.intellij.aem.service
import co.nums.intellij.aem.messages.AemPluginBundle
import com.intellij.ide.IdeBundle
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.openapi.ui.Messages
object ApplicationRestarter {
fun askForApplicationRestart() {
if (showRestartDialog() == Messages.YES) {
ApplicationManagerEx.getApplicationEx().restart(true)
}
}
@Messages.YesNoResult
private fun showRestartDialog(): Int {
val action = if (ApplicationManagerEx.getApplicationEx().isRestartCapable) "restart" else "shutdown"
return Messages.showYesNoDialog(
AemPluginBundle.message("ide.restart.required.message", ApplicationNamesInfo.getInstance().fullProductName),
AemPluginBundle.message("ide.restart.required.title"),
IdeBundle.message("ide.$action.action"),
IdeBundle.message("ide.postpone.action"),
Messages.getQuestionIcon()
)
}
}
| src/main/kotlin/co/nums/intellij/aem/service/ApplicationRestarter.kt | 3070651468 |
package com.tamsiree.rxdemo.activity
import android.annotation.SuppressLint
import android.os.AsyncTask
import android.os.Bundle
import com.tamsiree.rxdemo.R
import com.tamsiree.rxui.activity.ActivityBase
import kotlinx.android.synthetic.main.activity_tloading_view.*
class ActivityTLoadingView : ActivityBase() {
private val WAIT_DURATION = 5000
private var dummyWait: DummyWait? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tloading_view)
}
override fun initView() {
rxTitle.setLeftFinish(this)
btn_reset.setOnClickListener { resetLoader() }
}
override fun initData() {
loadData()
}
private fun loadData() {
if (dummyWait != null) {
dummyWait!!.cancel(true)
}
dummyWait = DummyWait()
dummyWait!!.execute()
}
private fun postLoadData() {
txt_name.text = "神秘商人"
txt_title.text = "只有有缘人能够相遇"
txt_phone.text = "时限 24 小时"
txt_email.text = "说着一口苦涩难懂的语言 ddjhklfsalkjhghjkl"
image_icon.setImageResource(R.drawable.circle_dialog)
}
private fun resetLoader() {
txt_name.resetLoader()
txt_title.resetLoader()
txt_phone.resetLoader()
txt_email.resetLoader()
image_icon.resetLoader()
loadData()
}
@SuppressLint("StaticFieldLeak")
internal inner class DummyWait : AsyncTask<Void?, Void?, Void?>() {
override fun doInBackground(vararg params: Void?): Void? {
try {
Thread.sleep(WAIT_DURATION.toLong())
} catch (e: InterruptedException) {
e.printStackTrace()
}
return null
}
override fun onPostExecute(result: Void?) {
super.onPostExecute(result)
postLoadData()
}
}
override fun onDestroy() {
super.onDestroy()
if (dummyWait != null) {
dummyWait!!.cancel(true)
}
}
} | RxDemo/src/main/java/com/tamsiree/rxdemo/activity/ActivityTLoadingView.kt | 808611547 |
package com.tamsiree.rxkit
import android.app.ActivityManager
import android.content.Context
/**
* @author tamsiree
* @date 2016/9/24
*/
object RxServiceTool {
/**
* 获取服务是否开启
*
* @param context 上下文
* @param className 完整包名的服务类名
* @return `true`: 是<br></br>`false`: 否
*/
@JvmStatic
fun isRunningService(context: Context, className: String): Boolean {
// 进程的管理者,活动的管理者
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
// 获取正在运行的服务,最多获取1000个
val runningServices = activityManager.getRunningServices(1000)
// 遍历集合
for (runningServiceInfo in runningServices) {
val service = runningServiceInfo.service
if (className == service.className) {
return true
}
}
return false
}
} | RxKit/src/main/java/com/tamsiree/rxkit/RxServiceTool.kt | 2957803252 |
/*
* Copyright (c) 2019 by Nicolas Märchy
*
* This file is part of Sporttag PSA.
*
* Sporttag PSA 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.
*
* Sporttag PSA 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 Sporttag PSA. If not, see <http://www.gnu.org/licenses/>.
*
* Diese Datei ist Teil von Sporttag PSA.
*
* Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren
* veröffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber
* OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License für weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*
*
*/
package ch.schulealtendorf.psa.shared.rulebook
import ch.schulealtendorf.psa.dto.participation.GenderDto
import ch.schulealtendorf.psa.dto.participation.athletics.BALLZIELWURF
import ch.schulealtendorf.psa.shared.rulebook.rules.RuleSet
/**
* Defines all the rules that can be applied to a target throwing.
*
* @author nmaerchy
* @version 1.0.0
*/
class TargetThrowingRuleSet : RuleSet<FormulaModel, Int>() {
/**
* @return true if the rules of this rule set can be used, otherwise false
*/
override val whenever: (FormulaModel) -> Boolean = { it.discipline == BALLZIELWURF }
init {
addRule(
object : FormulaRule() {
override val formula: (Double) -> Int = { (4.4 * ((it - 0) pow 1.27)).toInt() }
override val whenever: (FormulaModel) -> Boolean =
{ it.gender == GenderDto.FEMALE && it.distance == "4m" }
}
)
addRule(
object : FormulaRule() {
override val formula: (Double) -> Int = { (5.3 * ((it - 0) pow 1.27)).toInt() }
override val whenever: (FormulaModel) -> Boolean =
{ it.gender == GenderDto.FEMALE && it.distance == "5m" }
}
)
addRule(
object : FormulaRule() {
override val formula: (Double) -> Int = { (4.3 * ((it - 0) pow 1.25)).toInt() }
override val whenever: (FormulaModel) -> Boolean =
{ it.gender == GenderDto.MALE && it.distance == "4m" }
}
)
addRule(
object : FormulaRule() {
override val formula: (Double) -> Int = { (5.3 * ((it - 0) pow 1.25)).toInt() }
override val whenever: (FormulaModel) -> Boolean =
{ it.gender == GenderDto.MALE && it.distance == "5m" }
}
)
}
}
| app/shared/src/main/kotlin/ch/schulealtendorf/psa/shared/rulebook/TargetThrowingRuleSet.kt | 844056331 |
package org.wikipedia.talk
import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.view.menu.MenuBuilder
import androidx.appcompat.view.menu.MenuPopupHelper
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.wikipedia.Constants
import org.wikipedia.R
import org.wikipedia.analytics.eventplatform.EditHistoryInteractionEvent
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.history.HistoryEntry
import org.wikipedia.page.ExclusiveBottomSheetPresenter
import org.wikipedia.page.Namespace
import org.wikipedia.page.PageActivity
import org.wikipedia.page.PageTitle
import org.wikipedia.page.linkpreview.LinkPreviewDialog
import org.wikipedia.staticdata.UserTalkAliasData
import org.wikipedia.usercontrib.UserContribListActivity
import org.wikipedia.util.FeedbackUtil
import org.wikipedia.util.ResourceUtil
import org.wikipedia.util.log.L
@SuppressLint("RestrictedApi")
object UserTalkPopupHelper {
fun show(activity: AppCompatActivity, bottomSheetPresenter: ExclusiveBottomSheetPresenter,
title: PageTitle, anon: Boolean, anchorView: View,
invokeSource: Constants.InvokeSource, historySource: Int, revisionId: Long? = null, pageId: Int? = null) {
val pos = IntArray(2)
anchorView.getLocationInWindow(pos)
show(activity, bottomSheetPresenter, title, anon, pos[0], pos[1], invokeSource, historySource, revisionId = revisionId, pageId = pageId)
}
fun show(activity: AppCompatActivity, bottomSheetPresenter: ExclusiveBottomSheetPresenter,
title: PageTitle, anon: Boolean, x: Int, y: Int, invokeSource: Constants.InvokeSource,
historySource: Int, showContribs: Boolean = true, revisionId: Long? = null, pageId: Int? = null) {
if (title.namespace() == Namespace.USER_TALK || title.namespace() == Namespace.TALK) {
activity.startActivity(TalkTopicsActivity.newIntent(activity, title, invokeSource))
} else if (title.namespace() == Namespace.USER) {
val rootView = activity.window.decorView
val anchorView = View(activity)
anchorView.x = (x - rootView.left).toFloat()
anchorView.y = (y - rootView.top).toFloat()
(rootView as ViewGroup).addView(anchorView)
val helper = getPopupHelper(activity, title, anon, anchorView, invokeSource, historySource,
showContribs, revisionId = revisionId, pageId = pageId)
helper.setOnDismissListener {
rootView.removeView(anchorView)
}
helper.show()
} else {
bottomSheetPresenter.show(activity.supportFragmentManager,
LinkPreviewDialog.newInstance(HistoryEntry(title, historySource), null))
}
}
private fun showThankDialog(activity: Activity, title: PageTitle, revisionId: Long, pageId: Int) {
val parent = FrameLayout(activity)
val editHistoryInteractionEvent = EditHistoryInteractionEvent(title.wikiSite.dbName(), pageId)
val dialog =
AlertDialog.Builder(activity)
.setView(parent)
.setPositiveButton(R.string.thank_dialog_positive_button_text) { _, _ ->
sendThanks(activity, title.wikiSite, revisionId, title, editHistoryInteractionEvent)
}
.setNegativeButton(R.string.thank_dialog_negative_button_text) { _, _ ->
editHistoryInteractionEvent.logThankCancel()
}
.create()
dialog.layoutInflater.inflate(R.layout.view_thank_dialog, parent)
dialog.setOnShowListener {
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(ResourceUtil.getThemedColor(activity, R.attr.secondary_text_color))
}
dialog.show()
}
private fun sendThanks(activity: Activity, wikiSite: WikiSite, revisionId: Long?, title: PageTitle,
editHistoryInteractionEvent: EditHistoryInteractionEvent) {
CoroutineScope(Dispatchers.Default).launch(CoroutineExceptionHandler { _, throwable ->
L.e(throwable)
editHistoryInteractionEvent.logThankFail()
}) {
val token = ServiceFactory.get(wikiSite).getToken().query?.csrfToken()
if (revisionId != null && token != null) {
ServiceFactory.get(wikiSite).postThanksToRevision(revisionId, token)
FeedbackUtil.showMessage(activity, activity.getString(R.string.thank_success_message, title.text))
editHistoryInteractionEvent.logThankSuccess()
}
}
}
private fun getPopupHelper(activity: Activity, title: PageTitle, anon: Boolean,
anchorView: View, invokeSource: Constants.InvokeSource,
historySource: Int, showContribs: Boolean = true,
revisionId: Long? = null, pageId: Int? = null): MenuPopupHelper {
val builder = MenuBuilder(activity)
activity.menuInflater.inflate(R.menu.menu_user_talk_popup, builder)
builder.setCallback(object : MenuBuilder.Callback {
override fun onMenuItemSelected(menu: MenuBuilder, item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_user_profile_page -> {
val entry = HistoryEntry(title, historySource)
activity.startActivity(PageActivity.newIntentForNewTab(activity, entry, title))
}
R.id.menu_user_talk_page -> {
val newTitle = PageTitle(UserTalkAliasData.valueFor(title.wikiSite.languageCode), title.text, title.wikiSite)
activity.startActivity(TalkTopicsActivity.newIntent(activity, newTitle, invokeSource))
}
R.id.menu_user_contributions_page -> {
activity.startActivity(UserContribListActivity.newIntent(activity, title.text))
}
R.id.menu_user_thank -> {
if (pageId != null && revisionId != null) {
showThankDialog(activity, title, revisionId, pageId)
}
}
}
return true
}
override fun onMenuModeChange(menu: MenuBuilder) { }
})
builder.findItem(R.id.menu_user_profile_page).isVisible = !anon
builder.findItem(R.id.menu_user_contributions_page).isVisible = showContribs
builder.findItem(R.id.menu_user_thank).isVisible = revisionId != null && !anon
val helper = MenuPopupHelper(activity, builder, anchorView)
helper.setForceShowIcon(true)
return helper
}
}
| app/src/main/java/org/wikipedia/talk/UserTalkPopupHelper.kt | 2378673771 |
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.util.cache
import com.bumptech.glide.disklrucache.DiskLruCache
import de.vanita5.twittnuker.BuildConfig
import de.vanita5.twittnuker.util.DebugLog
import de.vanita5.twittnuker.util.JsonSerializer
import java.io.File
import java.io.IOException
class JsonCache(cacheDir: File) {
private val cache: DiskLruCache? by lazy {
try {
return@lazy DiskLruCache.open(cacheDir, BuildConfig.VERSION_CODE, 1, 100 * 1048576)
} catch (e: IOException) {
DebugLog.w(tr = e)
return@lazy null
}
}
fun <T> getList(key: String, cls: Class<T>): List<T>? {
val value = cache?.get(key) ?: return null
return try {
value.getFile(0)?.inputStream()?.use {
JsonSerializer.parseList(it, cls)
}
} catch (e: IOException) {
DebugLog.w(tr = e)
null
}
}
fun <T> saveList(key: String, list: List<T>?, cls: Class<T>) {
if (list == null) {
cache?.remove(key)
return
}
val editor = cache?.edit(key) ?: return
try {
editor.getFile(0)?.outputStream()?.use {
JsonSerializer.serialize(list, it, cls)
}
editor.commit()
} catch (e: IOException) {
DebugLog.w(tr = e)
} finally {
editor.abortUnlessCommitted()
}
}
} | twittnuker/src/main/kotlin/de/vanita5/twittnuker/util/cache/JsonCache.kt | 3776025717 |
package org.wikipedia.auth
import android.accounts.*
import android.content.Context
import android.os.Bundle
import androidx.core.os.bundleOf
import org.wikipedia.R
import org.wikipedia.analytics.LoginFunnel
import org.wikipedia.auth.AccountUtil.account
import org.wikipedia.auth.AccountUtil.accountType
import org.wikipedia.login.LoginActivity
class WikimediaAuthenticator(private val context: Context) : AbstractAccountAuthenticator(context) {
override fun editProperties(response: AccountAuthenticatorResponse, accountType: String): Bundle {
return unsupportedOperation()
}
override fun addAccount(response: AccountAuthenticatorResponse, accountType: String,
authTokenType: String?, requiredFeatures: Array<String>?,
options: Bundle?): Bundle {
return if (!supportedAccountType(accountType) || account() != null) {
unsupportedOperation()
} else addAccount(response)
}
override fun confirmCredentials(response: AccountAuthenticatorResponse,
account: Account, options: Bundle?): Bundle {
return unsupportedOperation()
}
override fun getAuthToken(response: AccountAuthenticatorResponse, account: Account,
authTokenType: String, options: Bundle?): Bundle {
return unsupportedOperation()
}
override fun getAuthTokenLabel(authTokenType: String): String? {
return if (supportedAccountType(authTokenType)) context.getString(R.string.wikimedia) else null
}
override fun updateCredentials(response: AccountAuthenticatorResponse, account: Account,
authTokenType: String?, options: Bundle?): Bundle {
return unsupportedOperation()
}
override fun hasFeatures(response: AccountAuthenticatorResponse,
account: Account, features: Array<String>): Bundle {
return bundleOf(AccountManager.KEY_BOOLEAN_RESULT to false)
}
private fun supportedAccountType(type: String?): Boolean {
return accountType() == type
}
private fun addAccount(response: AccountAuthenticatorResponse): Bundle {
val intent = LoginActivity.newIntent(context, LoginFunnel.SOURCE_SYSTEM)
.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response)
return bundleOf(AccountManager.KEY_INTENT to intent)
}
private fun unsupportedOperation(): Bundle {
return bundleOf(AccountManager.KEY_ERROR_CODE to AccountManager.ERROR_CODE_UNSUPPORTED_OPERATION,
AccountManager.KEY_ERROR_MESSAGE to "") // HACK: the docs indicate that this is a required key bit it's not displayed to the user.
}
}
| app/src/main/java/org/wikipedia/auth/WikimediaAuthenticator.kt | 1239886189 |
package site.paulo.localchat.extension
import rx.Subscription
import rx.subscriptions.CompositeSubscription
fun Subscription.addTo(compositeSubscription: CompositeSubscription) {
compositeSubscription.add(this)
}
| app/src/main/kotlin/site/paulo/localchat/extension/SubscriptionExtension.kt | 1267108007 |
/*
* 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.
*/
@file:RequiresApi(27)
package androidx.benchmark
import android.app.Activity
import android.app.KeyguardManager
import androidx.annotation.RequiresApi
internal fun Activity.requestDismissKeyguard() {
// technically this could be API 26, but only used on 27
val keyguardManager = getSystemService(Activity.KEYGUARD_SERVICE) as KeyguardManager
keyguardManager.requestDismissKeyguard(this, null)
}
internal fun Activity.setShowWhenLocked() {
setShowWhenLocked(true)
}
internal fun Activity.setTurnScreenOn() {
setShowWhenLocked(true)
}
| benchmark/benchmark-common/src/main/java/androidx/benchmark/Api27.kt | 2888658269 |
/**
* ownCloud Android client application
*
* @author Abel García de Prada
* Copyright (C) 2020 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* 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.owncloud.android.domain.shares.usecases
import com.owncloud.android.domain.exceptions.UnauthorizedException
import com.owncloud.android.domain.sharing.shares.ShareRepository
import com.owncloud.android.domain.sharing.shares.model.ShareType
import com.owncloud.android.domain.sharing.shares.usecases.CreatePrivateShareAsyncUseCase
import io.mockk.every
import io.mockk.spyk
import io.mockk.verify
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class CreatePrivateShareAsyncUseCaseTest {
private val shareRepository: ShareRepository = spyk()
private val useCase = CreatePrivateShareAsyncUseCase((shareRepository))
private val useCaseParams = CreatePrivateShareAsyncUseCase.Params("", ShareType.USER, "", 1, "")
@Test
fun createPrivateShareOk() {
val useCaseResult = useCase.execute(useCaseParams)
assertTrue(useCaseResult.isSuccess)
assertFalse(useCaseResult.isError)
assertEquals(Unit, useCaseResult.getDataOrNull())
verify(exactly = 1) { shareRepository.insertPrivateShare("", ShareType.USER, "", 1, "") }
}
@Test
fun createPrivateShareWithUnauthorizedException() {
every { shareRepository.insertPrivateShare(any(), any(), any(), any(), any()) } throws UnauthorizedException()
val useCaseResult = useCase.execute(useCaseParams)
assertFalse(useCaseResult.isSuccess)
assertTrue(useCaseResult.isError)
assertNull(useCaseResult.getDataOrNull())
assertTrue(useCaseResult.getThrowableOrNull() is UnauthorizedException)
verify(exactly = 1) { shareRepository.insertPrivateShare("", ShareType.USER, "", 1, "") }
}
@Test
fun createPrivateShareWithNotValidShareTypeException() {
val useCaseParamsNotValid1 = useCaseParams.copy(shareType = null)
val useCaseResult1 = useCase.execute(useCaseParamsNotValid1)
assertFalse(useCaseResult1.isSuccess)
assertTrue(useCaseResult1.isError)
assertNull(useCaseResult1.getDataOrNull())
assertTrue(useCaseResult1.getThrowableOrNull() is IllegalArgumentException)
val useCaseParamsNotValid2 = useCaseParams.copy(shareType = ShareType.CONTACT)
val useCaseResult2 = useCase.execute(useCaseParamsNotValid2)
assertFalse(useCaseResult2.isSuccess)
assertTrue(useCaseResult2.isError)
assertNull(useCaseResult2.getDataOrNull())
assertTrue(useCaseResult2.getThrowableOrNull() is IllegalArgumentException)
verify(exactly = 0) { shareRepository.insertPrivateShare(any(), any(), any(), any(), any()) }
}
}
| owncloudDomain/src/test/java/com/owncloud/android/domain/shares/usecases/CreatePrivateShareAsyncUseCaseTest.kt | 3334106212 |
/*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* 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.tealcube.minecraft.bukkit.mythicdrops.utils
import com.google.common.collect.Multimap
import com.google.common.collect.MultimapBuilder
import com.tealcube.minecraft.bukkit.mythicdrops.MythicDropsPlugin
import com.tealcube.minecraft.bukkit.mythicdrops.api.MythicDrops
import com.tealcube.minecraft.bukkit.mythicdrops.api.enchantments.MythicEnchantment
import com.tealcube.minecraft.bukkit.mythicdrops.api.relations.Relation
import com.tealcube.minecraft.bukkit.mythicdrops.api.relations.RelationManager
import com.tealcube.minecraft.bukkit.mythicdrops.api.tiers.Tier
import com.tealcube.minecraft.bukkit.mythicdrops.safeRandom
import com.tealcube.minecraft.bukkit.mythicdrops.stripColors
import io.pixeloutlaw.minecraft.spigot.hilt.getDisplayName
import org.bukkit.attribute.Attribute
import org.bukkit.attribute.AttributeModifier
import org.bukkit.enchantments.Enchantment
import org.bukkit.inventory.ItemStack
import kotlin.math.max
import kotlin.math.min
object ItemBuildingUtil {
private val mythicDrops: MythicDrops by lazy {
MythicDropsPlugin.getInstance()
}
private val spaceRegex = " ".toRegex()
fun getSafeEnchantments(
isSafe: Boolean,
enchantments: Collection<MythicEnchantment>,
itemStack: ItemStack
): Collection<MythicEnchantment> {
return enchantments.filter {
if (isSafe) {
it.enchantment.canEnchantItem(itemStack)
} else {
true
}
}
}
fun getBaseEnchantments(itemStack: ItemStack, tier: Tier): Map<Enchantment, Int> {
if (tier.enchantments.baseEnchantments.isEmpty()) {
return emptyMap()
}
val safeEnchantments = getSafeEnchantments(
tier.enchantments.isSafeBaseEnchantments,
tier.enchantments.baseEnchantments,
itemStack
)
return safeEnchantments.map { mythicEnchantment ->
val enchantment = mythicEnchantment.enchantment
val isAllowHighEnchantments = tier.enchantments.isAllowHighBaseEnchantments
val levelRange = getEnchantmentLevelRange(isAllowHighEnchantments, mythicEnchantment, enchantment)
when {
!tier.enchantments.isSafeBaseEnchantments -> enchantment to levelRange.safeRandom()
tier.enchantments.isAllowHighBaseEnchantments -> {
enchantment to levelRange.safeRandom()
}
else -> enchantment to getAcceptableEnchantmentLevel(
enchantment,
levelRange.safeRandom()
)
}
}.toMap()
}
fun getBonusEnchantments(itemStack: ItemStack, tier: Tier): Map<Enchantment, Int> {
if (tier.enchantments.bonusEnchantments.isEmpty()) {
return emptyMap()
}
val bonusEnchantmentsToAdd =
(tier.enchantments.minimumBonusEnchantments..tier.enchantments.maximumBonusEnchantments).random()
var tierBonusEnchantments =
getSafeEnchantments(
tier.enchantments.isSafeBonusEnchantments,
tier.enchantments.bonusEnchantments, itemStack
)
val bonusEnchantments = mutableMapOf<Enchantment, Int>()
repeat(bonusEnchantmentsToAdd) {
if (tierBonusEnchantments.isEmpty()) {
return@repeat
}
val mythicEnchantment = tierBonusEnchantments.random()
if (mythicDrops.settingsManager.configSettings.options.isOnlyRollBonusEnchantmentsOnce) {
tierBonusEnchantments -= mythicEnchantment
}
val enchantment = mythicEnchantment.enchantment
val randomizedLevelOfEnchantment =
bonusEnchantments[enchantment]?.let {
min(
mythicEnchantment.maximumLevel,
it + mythicEnchantment.getRandomLevel()
)
}
?: mythicEnchantment.getRandomLevel()
val trimmedLevel = if (!tier.enchantments.isAllowHighBonusEnchantments) {
getAcceptableEnchantmentLevel(enchantment, randomizedLevelOfEnchantment)
} else {
randomizedLevelOfEnchantment
}
bonusEnchantments[enchantment] = trimmedLevel
}
return bonusEnchantments.toMap()
}
fun getRelations(itemStack: ItemStack, relationManager: RelationManager): List<Relation> {
val name = itemStack.getDisplayName() ?: "" // empty string has no relations
return name.stripColors().split(spaceRegex).dropLastWhile { it.isEmpty() }
.mapNotNull { relationManager.getById(it) }
}
fun getRelationEnchantments(
itemStack: ItemStack,
tier: Tier,
relationManager: RelationManager
): Map<Enchantment, Int> {
val relationMythicEnchantments = getRelations(itemStack, relationManager).flatMap { it.enchantments }
val safeEnchantments =
getSafeEnchantments(tier.enchantments.isSafeRelationEnchantments, relationMythicEnchantments, itemStack)
if (safeEnchantments.isEmpty()) {
return emptyMap()
}
val relationEnchantments = mutableMapOf<Enchantment, Int>()
safeEnchantments.forEach { mythicEnchantment ->
val enchantment = mythicEnchantment.enchantment
val randomizedLevelOfEnchantment = relationEnchantments[enchantment]?.let {
min(
mythicEnchantment.maximumLevel,
it + mythicEnchantment.getRandomLevel()
)
} ?: mythicEnchantment.getRandomLevel()
val trimmedLevel = if (!tier.enchantments.isAllowHighRelationEnchantments) {
getAcceptableEnchantmentLevel(enchantment, randomizedLevelOfEnchantment)
} else {
randomizedLevelOfEnchantment
}
relationEnchantments[enchantment] = trimmedLevel
}
return relationEnchantments.toMap()
}
@Suppress("UnstableApiUsage")
fun getBaseAttributeModifiers(tier: Tier): Multimap<Attribute, AttributeModifier> {
val baseAttributeModifiers: Multimap<Attribute, AttributeModifier> =
MultimapBuilder.hashKeys().arrayListValues().build()
if (tier.attributes.baseAttributes.isEmpty()) {
return baseAttributeModifiers
}
tier.attributes.baseAttributes.forEach {
val (attribute, attributeModifier) = it.toAttributeModifier()
baseAttributeModifiers.put(attribute, attributeModifier)
}
return baseAttributeModifiers
}
@Suppress("UnstableApiUsage")
fun getBonusAttributeModifiers(tier: Tier): Multimap<Attribute, AttributeModifier> {
val bonusAttributeModifiers: Multimap<Attribute, AttributeModifier> =
MultimapBuilder.hashKeys().arrayListValues().build()
if (tier.attributes.bonusAttributes.isEmpty()) {
return bonusAttributeModifiers
}
val bonusAttributes = tier.attributes.bonusAttributes.toMutableSet()
val bonusAttributesToAdd =
(tier.attributes.minimumBonusAttributes..tier.attributes.maximumBonusAttributes).random()
repeat(bonusAttributesToAdd) {
if (bonusAttributes.isEmpty()) {
return@repeat
}
val mythicAttribute = bonusAttributes.random()
if (mythicDrops.settingsManager.configSettings.options.isOnlyRollBonusAttributesOnce) {
bonusAttributes -= mythicAttribute
}
val (attribute, attributeModifier) = mythicAttribute.toAttributeModifier()
bonusAttributeModifiers.put(attribute, attributeModifier)
}
return bonusAttributeModifiers
}
private fun getEnchantmentLevelRange(
isAllowHighEnchantments: Boolean,
mythicEnchantment: MythicEnchantment,
enchantment: Enchantment
): IntRange {
val minimumLevel = if (isAllowHighEnchantments) {
max(mythicEnchantment.minimumLevel.coerceAtLeast(1), enchantment.startLevel)
} else {
mythicEnchantment.minimumLevel.coerceAtLeast(1).coerceAtMost(enchantment.startLevel)
}
val maximumLevel = if (isAllowHighEnchantments) {
mythicEnchantment.maximumLevel.coerceAtLeast(1)
.coerceAtMost(MythicEnchantment.HIGHEST_ENCHANTMENT_LEVEL)
} else {
mythicEnchantment.maximumLevel.coerceAtLeast(1).coerceAtMost(enchantment.maxLevel)
}
// we need to do this calculation below because sometimes minimumLevel and maximumLevel can
// not match up :^)
return min(minimumLevel, maximumLevel)..max(minimumLevel, maximumLevel)
}
private fun getAcceptableEnchantmentLevel(enchantment: Enchantment, level: Int): Int =
level.coerceAtLeast(enchantment.startLevel).coerceAtMost(enchantment.maxLevel)
}
| src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/utils/ItemBuildingUtil.kt | 2214789401 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.focus
import androidx.compose.foundation.layout.Box
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusStateImpl.Active
import androidx.compose.ui.focus.FocusStateImpl.ActiveParent
import androidx.compose.ui.focus.FocusStateImpl.Captured
import androidx.compose.ui.focus.FocusStateImpl.Deactivated
import androidx.compose.ui.focus.FocusStateImpl.DeactivatedParent
import androidx.compose.ui.focus.FocusStateImpl.Inactive
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@SmallTest
@RunWith(AndroidJUnit4::class)
class RequestFocusTest {
@get:Rule
val rule = createComposeRule()
@Test
fun active_isUnchanged() {
// Arrange.
val focusModifier = FocusModifier(Active)
rule.setFocusableContent {
Box(Modifier.focusTarget(focusModifier))
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(focusModifier.focusState).isEqualTo(Active)
}
}
@Test
fun captured_isUnchanged() {
// Arrange.
val focusModifier = FocusModifier(Captured)
rule.setFocusableContent {
Box(Modifier.focusTarget(focusModifier))
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(focusModifier.focusState).isEqualTo(Captured)
}
}
@Test
fun deactivated_isUnchanged() {
// Arrange.
val focusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier
.focusProperties { canFocus = false }
.focusTarget(focusModifier)
)
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(focusModifier.focusState).isEqualTo(Deactivated)
}
}
@Test(expected = IllegalArgumentException::class)
fun activeParent_withNoFocusedChild_throwsException() {
// Arrange.
val focusModifier = FocusModifier(ActiveParent)
rule.setFocusableContent {
Box(Modifier.focusTarget(focusModifier))
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
}
@Test
fun activeParent_propagateFocus() {
// Arrange.
val focusModifier = FocusModifier(ActiveParent)
val childFocusModifier = FocusModifier(Active)
rule.setFocusableContent {
Box(Modifier.focusTarget(focusModifier)) {
Box(Modifier.focusTarget(childFocusModifier))
}
}
rule.runOnIdle {
focusModifier.focusedChild = childFocusModifier
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(focusModifier.focusState).isEqualTo(Active)
assertThat(focusModifier.focusedChild).isNull()
assertThat(childFocusModifier.focusState).isEqualTo(Inactive)
}
}
@Test(expected = IllegalArgumentException::class)
fun deactivatedParent_withNoFocusedChild_throwsException() {
// Arrange.
val focusModifier = FocusModifier(DeactivatedParent)
rule.setFocusableContent {
Box(Modifier.focusTarget(focusModifier))
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
}
@Test
fun deactivatedParent_propagateFocus() {
// Arrange.
val focusModifier = FocusModifier(ActiveParent)
val childFocusModifier = FocusModifier(Active)
rule.setFocusableContent {
Box(Modifier
.focusProperties { canFocus = false }
.focusTarget(focusModifier)
) {
Box(Modifier.focusTarget(childFocusModifier))
}
}
rule.runOnIdle {
focusModifier.focusedChild = childFocusModifier
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
// Unchanged.
assertThat(focusModifier.focusState).isEqualTo(DeactivatedParent)
assertThat(childFocusModifier.focusState).isEqualTo(Active)
}
}
@Test
fun deactivatedParent_activeChild_propagateFocus() {
// Arrange.
val focusModifier = FocusModifier(ActiveParent)
val childFocusModifier = FocusModifier(Active)
val grandchildFocusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier
.focusProperties { canFocus = false }
.focusTarget(focusModifier)
) {
Box(Modifier.focusTarget(childFocusModifier)) {
Box(Modifier.focusTarget(grandchildFocusModifier))
}
}
}
rule.runOnIdle {
focusModifier.focusedChild = childFocusModifier
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(focusModifier.focusState).isEqualTo(DeactivatedParent)
assertThat(childFocusModifier.focusState).isEqualTo(Active)
assertThat(childFocusModifier.focusedChild).isNull()
assertThat(grandchildFocusModifier.focusState).isEqualTo(Inactive)
}
}
@Test
fun inactiveRoot_propagateFocusSendsRequestToOwner_systemCanGrantFocus() {
// Arrange.
val rootFocusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier.focusTarget(rootFocusModifier))
}
// Act.
rule.runOnIdle {
rootFocusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(rootFocusModifier.focusState).isEqualTo(Active)
}
}
@Test
fun inactiveRootWithChildren_propagateFocusSendsRequestToOwner_systemCanGrantFocus() {
// Arrange.
val rootFocusModifier = FocusModifier(Inactive)
val childFocusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier.focusTarget(rootFocusModifier)) {
Box(Modifier.focusTarget(childFocusModifier))
}
}
// Act.
rule.runOnIdle {
rootFocusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(rootFocusModifier.focusState).isEqualTo(Active)
assertThat(childFocusModifier.focusState).isEqualTo(Inactive)
}
}
@Test
fun inactiveNonRootWithChildren() {
// Arrange.
val parentFocusModifier = FocusModifier(Active)
val focusModifier = FocusModifier(Inactive)
val childFocusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier.focusTarget(parentFocusModifier)) {
Box(Modifier.focusTarget(focusModifier)) {
Box(Modifier.focusTarget(childFocusModifier))
}
}
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(parentFocusModifier.focusState).isEqualTo(ActiveParent)
assertThat(focusModifier.focusState).isEqualTo(Active)
assertThat(childFocusModifier.focusState).isEqualTo(Inactive)
}
}
@Test
fun rootNode() {
// Arrange.
val rootFocusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier.focusTarget(rootFocusModifier))
}
// Act.
rule.runOnIdle {
rootFocusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(rootFocusModifier.focusState).isEqualTo(Active)
}
}
@Test
fun rootNodeWithChildren() {
// Arrange.
val rootFocusModifier = FocusModifier(Inactive)
val childFocusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier.focusTarget(rootFocusModifier)) {
Box(Modifier.focusTarget(childFocusModifier))
}
}
// Act.
rule.runOnIdle {
rootFocusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(rootFocusModifier.focusState).isEqualTo(Active)
}
}
@Test
fun parentNodeWithNoFocusedAncestor() {
// Arrange.
val grandParentFocusModifier = FocusModifier(Inactive)
val parentFocusModifier = FocusModifier(Inactive)
val childFocusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier.focusTarget(grandParentFocusModifier)) {
Box(Modifier.focusTarget(parentFocusModifier)) {
Box(Modifier.focusTarget(childFocusModifier))
}
}
}
// Act.
rule.runOnIdle {
parentFocusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(parentFocusModifier.focusState).isEqualTo(Active)
}
}
@Test
fun parentNodeWithNoFocusedAncestor_childRequestsFocus() {
// Arrange.
val grandParentFocusModifier = FocusModifier(Inactive)
val parentFocusModifier = FocusModifier(Inactive)
val childFocusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier.focusTarget(grandParentFocusModifier)) {
Box(Modifier.focusTarget(parentFocusModifier)) {
Box(Modifier.focusTarget(childFocusModifier))
}
}
}
// Act.
rule.runOnIdle {
childFocusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(parentFocusModifier.focusState).isEqualTo(ActiveParent)
}
}
@Test
fun childNodeWithNoFocusedAncestor() {
// Arrange.
val grandParentFocusModifier = FocusModifier(Inactive)
val parentFocusModifier = FocusModifier(Inactive)
val childFocusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier.focusTarget(grandParentFocusModifier)) {
Box(Modifier.focusTarget(parentFocusModifier)) {
Box(Modifier.focusTarget(childFocusModifier))
}
}
}
// Act.
rule.runOnIdle {
childFocusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(childFocusModifier.focusState).isEqualTo(Active)
}
}
@Test
fun requestFocus_parentIsFocused() {
// Arrange.
val parentFocusModifier = FocusModifier(Active)
val focusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier.focusTarget(parentFocusModifier)) {
Box(Modifier.focusTarget(focusModifier))
}
}
// After executing requestFocus, siblingNode will be 'Active'.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(parentFocusModifier.focusState).isEqualTo(ActiveParent)
assertThat(focusModifier.focusState).isEqualTo(Active)
}
}
@Test
fun requestFocus_childIsFocused() {
// Arrange.
val parentFocusModifier = FocusModifier(ActiveParent)
val focusModifier = FocusModifier(Active)
rule.setFocusableContent {
Box(Modifier.focusTarget(parentFocusModifier)) {
Box(Modifier.focusTarget(focusModifier))
}
}
rule.runOnIdle {
parentFocusModifier.focusedChild = focusModifier
}
// Act.
rule.runOnIdle {
parentFocusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(parentFocusModifier.focusState).isEqualTo(Active)
assertThat(focusModifier.focusState).isEqualTo(Inactive)
}
}
@Test
fun requestFocus_childHasCapturedFocus() {
// Arrange.
val parentFocusModifier = FocusModifier(ActiveParent)
val focusModifier = FocusModifier(Captured)
rule.setFocusableContent {
Box(Modifier.focusTarget(parentFocusModifier)) {
Box(Modifier.focusTarget(focusModifier))
}
}
rule.runOnIdle {
parentFocusModifier.focusedChild = focusModifier
}
// Act.
rule.runOnIdle {
parentFocusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(parentFocusModifier.focusState).isEqualTo(ActiveParent)
assertThat(focusModifier.focusState).isEqualTo(Captured)
}
}
@Test
fun requestFocus_siblingIsFocused() {
// Arrange.
val parentFocusModifier = FocusModifier(ActiveParent)
val focusModifier = FocusModifier(Inactive)
val siblingModifier = FocusModifier(Active)
rule.setFocusableContent {
Box(Modifier.focusTarget(parentFocusModifier)) {
Box(Modifier.focusTarget(focusModifier))
Box(Modifier.focusTarget(siblingModifier))
}
}
rule.runOnIdle {
parentFocusModifier.focusedChild = siblingModifier
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(parentFocusModifier.focusState).isEqualTo(ActiveParent)
assertThat(focusModifier.focusState).isEqualTo(Active)
assertThat(siblingModifier.focusState).isEqualTo(Inactive)
}
}
@Test
fun requestFocus_siblingHasCapturedFocused() {
// Arrange.
val parentFocusModifier = FocusModifier(ActiveParent)
val focusModifier = FocusModifier(Inactive)
val siblingModifier = FocusModifier(Captured)
rule.setFocusableContent {
Box(Modifier.focusTarget(parentFocusModifier)) {
Box(Modifier.focusTarget(focusModifier))
Box(Modifier.focusTarget(siblingModifier))
}
}
rule.runOnIdle {
parentFocusModifier.focusedChild = siblingModifier
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(parentFocusModifier.focusState).isEqualTo(ActiveParent)
assertThat(focusModifier.focusState).isEqualTo(Inactive)
assertThat(siblingModifier.focusState).isEqualTo(Captured)
}
}
@Test
fun requestFocus_cousinIsFocused() {
// Arrange.
val grandParentModifier = FocusModifier(ActiveParent)
val parentModifier = FocusModifier(Inactive)
val focusModifier = FocusModifier(Inactive)
val auntModifier = FocusModifier(ActiveParent)
val cousinModifier = FocusModifier(Active)
rule.setFocusableContent {
Box(Modifier.focusTarget(grandParentModifier)) {
Box(Modifier.focusTarget(parentModifier)) {
Box(Modifier.focusTarget(focusModifier))
}
Box(Modifier.focusTarget(auntModifier)) {
Box(Modifier.focusTarget(cousinModifier))
}
}
}
rule.runOnIdle {
grandParentModifier.focusedChild = auntModifier
auntModifier.focusedChild = cousinModifier
}
// Verify Setup.
rule.runOnIdle {
assertThat(cousinModifier.focusState).isEqualTo(Active)
assertThat(focusModifier.focusState).isEqualTo(Inactive)
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(cousinModifier.focusState).isEqualTo(Inactive)
assertThat(focusModifier.focusState).isEqualTo(Active)
}
}
@Test
fun requestFocus_grandParentIsFocused() {
// Arrange.
val grandParentModifier = FocusModifier(Active)
val parentModifier = FocusModifier(Inactive)
val focusModifier = FocusModifier(Inactive)
rule.setFocusableContent {
Box(Modifier.focusTarget(grandParentModifier)) {
Box(Modifier.focusTarget(parentModifier)) {
Box(Modifier.focusTarget(focusModifier))
}
}
}
// Act.
rule.runOnIdle {
focusModifier.requestFocus()
}
// Assert.
rule.runOnIdle {
assertThat(grandParentModifier.focusState).isEqualTo(ActiveParent)
assertThat(parentModifier.focusState).isEqualTo(ActiveParent)
assertThat(focusModifier.focusState).isEqualTo(Active)
}
}
} | compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/focus/RequestFocusTest.kt | 4128532033 |
package abi42_0_0.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 abi42_0_0.expo.modules.interfaces.imageloader.ImageLoaderInterface
import abi42_0_0.org.unimodules.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
}
}
| android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/expo/modules/imageloader/ImageLoaderModule.kt | 1293856620 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.parser
import com.intellij.lang.LighterASTNode
import com.intellij.lang.PsiBuilder
import com.intellij.lang.PsiBuilderUtil
import com.intellij.lang.WhitespacesAndCommentsBinder
import com.intellij.lang.parser.GeneratedParserUtilBase
import com.intellij.lexer.Lexer
import com.intellij.openapi.util.Key
import com.intellij.psi.TokenType
import com.intellij.psi.tree.IElementType
import com.intellij.psi.tree.TokenSet
import com.intellij.util.BitUtil
import com.intellij.util.containers.Stack
import org.rust.lang.core.parser.RustParserDefinition.Companion.EOL_COMMENT
import org.rust.lang.core.parser.RustParserDefinition.Companion.OUTER_BLOCK_DOC_COMMENT
import org.rust.lang.core.parser.RustParserDefinition.Companion.OUTER_EOL_DOC_COMMENT
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.RsElementTypes.*
import org.rust.stdext.makeBitMask
import kotlin.math.max
@Suppress("UNUSED_PARAMETER")
object RustParserUtil : GeneratedParserUtilBase() {
enum class PathParsingMode {
/**
* Accepts paths like `Foo::<i32>`
* Should be used to parse references to values
*/
VALUE,
/**
* Accepts paths like `Foo<i32>`, `Foo::<i32>`, Fn(i32) -> i32 and Fn::(i32) -> i32
* Should be used to parse type and trait references
*/
TYPE,
/**
* Accepts paths like `Foo`
* Should be used to parse paths where type args cannot be specified: `use` items, macro calls, etc.
*/
NO_TYPE_ARGS
}
enum class TypeQualsMode { ON, OFF }
enum class StructLiteralsMode { ON, OFF }
/**
* Controls the difference between
*
* ```
* // bit and
* let _ = {1} & x;
* ```
* and
*
* ```
* // two statements: block expression {1} and unary reference expression &x
* {1} & x;
* ```
*
* See `Restrictions::RESTRICTION_STMT_EXPR` in libsyntax
*/
enum class StmtMode { ON, OFF }
enum class RestrictedConstExprMode { ON, OFF }
enum class ConditionMode { ON, OFF }
enum class MacroCallParsingMode(
val attrsAndVis: Boolean,
val semicolon: Boolean,
val pin: Boolean,
val forbidExprSpecialMacros: Boolean
) {
ITEM(attrsAndVis = false, semicolon = true, pin = true, forbidExprSpecialMacros = false),
BLOCK(attrsAndVis = true, semicolon = true, pin = false, forbidExprSpecialMacros = true),
EXPR(attrsAndVis = true, semicolon = false, pin = true, forbidExprSpecialMacros = false)
}
private val FLAGS: Key<Int> = Key("RustParserUtil.FLAGS")
private var PsiBuilder.flags: Int
get() = getUserData(FLAGS) ?: DEFAULT_FLAGS
set(value) = putUserData(FLAGS, value)
private val FLAG_STACK: Key<Stack<Int>> = Key("RustParserUtil.FLAG_STACK")
private var PsiBuilder.flagStack: Stack<Int>
get() = getUserData(FLAG_STACK) ?: Stack<Int>(0)
set(value) = putUserData(FLAG_STACK, value)
private fun PsiBuilder.pushFlag(flag: Int, mode: Boolean) {
val stack = flagStack
stack.push(flags)
flagStack = stack
flags = BitUtil.set(flags, flag, mode)
}
private fun PsiBuilder.pushFlags(vararg flagsAndValues: Pair<Int, Boolean>) {
val stack = flagStack
stack.push(flags)
flagStack = stack
for (flagAndValue in flagsAndValues) {
flags = BitUtil.set(flags, flagAndValue.first, flagAndValue.second)
}
}
private fun PsiBuilder.popFlag() {
flags = flagStack.pop()
}
private fun Int.setFlag(flag: Int, mode: Boolean): Int =
BitUtil.set(this, flag, mode)
private val STRUCT_ALLOWED: Int = makeBitMask(1)
private val TYPE_QUAL_ALLOWED: Int = makeBitMask(2)
private val STMT_EXPR_MODE: Int = makeBitMask(3)
private val PATH_MODE_VALUE: Int = makeBitMask(4)
private val PATH_MODE_TYPE: Int = makeBitMask(5)
private val PATH_MODE_NO_TYPE_ARGS: Int = makeBitMask(6)
private val MACRO_BRACE_PARENS: Int = makeBitMask(7)
private val MACRO_BRACE_BRACKS: Int = makeBitMask(8)
private val MACRO_BRACE_BRACES: Int = makeBitMask(9)
private val RESTRICTED_CONST_EXPR_MODE: Int = makeBitMask(10)
private val CONDITION_MODE: Int = makeBitMask(11)
private fun setPathMod(flags: Int, mode: PathParsingMode): Int {
val flag = when (mode) {
PathParsingMode.VALUE -> PATH_MODE_VALUE
PathParsingMode.TYPE -> PATH_MODE_TYPE
PathParsingMode.NO_TYPE_ARGS -> PATH_MODE_NO_TYPE_ARGS
}
return flags and (PATH_MODE_VALUE or PATH_MODE_TYPE or PATH_MODE_NO_TYPE_ARGS).inv() or flag
}
private fun getPathMod(flags: Int): PathParsingMode = when {
BitUtil.isSet(flags, PATH_MODE_VALUE) -> PathParsingMode.VALUE
BitUtil.isSet(flags, PATH_MODE_TYPE) -> PathParsingMode.TYPE
BitUtil.isSet(flags, PATH_MODE_NO_TYPE_ARGS) -> PathParsingMode.NO_TYPE_ARGS
else -> error("Path parsing mode not set")
}
private fun setMacroBraces(flags: Int, mode: MacroBraces): Int {
val flag = when (mode) {
MacroBraces.PARENS -> MACRO_BRACE_PARENS
MacroBraces.BRACKS -> MACRO_BRACE_BRACKS
MacroBraces.BRACES -> MACRO_BRACE_BRACES
}
return flags and (MACRO_BRACE_PARENS or MACRO_BRACE_BRACKS or MACRO_BRACE_BRACES).inv() or flag
}
private fun getMacroBraces(flags: Int): MacroBraces? = when {
BitUtil.isSet(flags, MACRO_BRACE_PARENS) -> MacroBraces.PARENS
BitUtil.isSet(flags, MACRO_BRACE_BRACKS) -> MacroBraces.BRACKS
BitUtil.isSet(flags, MACRO_BRACE_BRACES) -> MacroBraces.BRACES
else -> null
}
private val DEFAULT_FLAGS: Int = STRUCT_ALLOWED or TYPE_QUAL_ALLOWED
@JvmField
val ADJACENT_LINE_COMMENTS = WhitespacesAndCommentsBinder { tokens, _, getter ->
var candidate = tokens.size
for (i in 0 until tokens.size) {
val token = tokens[i]
if (OUTER_BLOCK_DOC_COMMENT == token || OUTER_EOL_DOC_COMMENT == token) {
candidate = minOf(candidate, i)
break
}
if (EOL_COMMENT == token) {
candidate = minOf(candidate, i)
}
if (TokenType.WHITE_SPACE == token && "\n\n" in getter[i]) {
candidate = tokens.size
}
}
candidate
}
private val LEFT_BRACES = tokenSetOf(LPAREN, LBRACE, LBRACK)
private val RIGHT_BRACES = tokenSetOf(RPAREN, RBRACE, RBRACK)
//
// Helpers
//
@JvmStatic
fun checkStructAllowed(b: PsiBuilder, level: Int): Boolean = BitUtil.isSet(b.flags, STRUCT_ALLOWED)
@JvmStatic
fun checkTypeQualAllowed(b: PsiBuilder, level: Int): Boolean = BitUtil.isSet(b.flags, TYPE_QUAL_ALLOWED)
@JvmStatic
fun checkBraceAllowed(b: PsiBuilder, level: Int): Boolean =
b.tokenType != LBRACE || checkStructAllowed(b, level)
@JvmStatic
fun checkGtAllowed(b: PsiBuilder, level: Int): Boolean =
!BitUtil.isSet(b.flags, RESTRICTED_CONST_EXPR_MODE)
@JvmStatic
fun checkLetExprAllowed(b: PsiBuilder, level: Int): Boolean =
BitUtil.isSet(b.flags, CONDITION_MODE)
@JvmStatic
fun withRestrictedConstExprMode(b: PsiBuilder, level: Int, mode: RestrictedConstExprMode, parser: Parser): Boolean {
val oldFlags = b.flags
val newFlags = oldFlags.setFlag(RESTRICTED_CONST_EXPR_MODE, mode == RestrictedConstExprMode.ON)
b.flags = newFlags
val result = parser.parse(b, level)
b.flags = oldFlags
return result
}
@JvmStatic
fun withConditionMode(b: PsiBuilder, level: Int, mode: ConditionMode, parser: Parser): Boolean {
val oldFlags = b.flags
val newFlags = oldFlags.setFlag(CONDITION_MODE, mode == ConditionMode.ON)
b.flags = newFlags
val result = parser.parse(b, level)
b.flags = oldFlags
return result
}
@JvmStatic
fun enterBlockExpr(b: PsiBuilder, level: Int, parser: Parser): Boolean {
val oldFlags = b.flags
val newFlags = oldFlags
.setFlag(RESTRICTED_CONST_EXPR_MODE, false)
.setFlag(CONDITION_MODE, false)
b.flags = newFlags
val result = parser.parse(b, level)
b.flags = oldFlags
return result
}
@JvmStatic
fun setStmtMode(b: PsiBuilder, level: Int, mode: StmtMode): Boolean {
b.pushFlag(STMT_EXPR_MODE, mode == StmtMode.ON)
return true
}
@JvmStatic
fun setLambdaExprMode(b: PsiBuilder, level: Int): Boolean {
b.pushFlags(
STMT_EXPR_MODE to false,
CONDITION_MODE to false
)
return true
}
@JvmStatic
fun resetFlags(b: PsiBuilder, level: Int): Boolean {
b.popFlag()
return true
}
@JvmStatic
fun exprMode(
b: PsiBuilder,
level: Int,
structLiterals: StructLiteralsMode,
stmtMode: StmtMode,
parser: Parser
): Boolean {
val oldFlags = b.flags
val newFlags = oldFlags
.setFlag(STRUCT_ALLOWED, structLiterals == StructLiteralsMode.ON)
.setFlag(STMT_EXPR_MODE, stmtMode == StmtMode.ON)
b.flags = newFlags
val result = parser.parse(b, level)
b.flags = oldFlags
return result
}
@JvmStatic
fun isCompleteBlockExpr(b: PsiBuilder, level: Int): Boolean =
isBlock(b, level) && BitUtil.isSet(b.flags, STMT_EXPR_MODE)
@JvmStatic
fun isIncompleteBlockExpr(b: PsiBuilder, level: Int): Boolean =
!isCompleteBlockExpr(b, level)
@JvmStatic
fun isBlock(b: PsiBuilder, level: Int): Boolean {
val m = b.latestDoneMarker ?: return false
return m.tokenType in RS_BLOCK_LIKE_EXPRESSIONS || m.isBracedMacro(b)
}
@JvmStatic
fun pathMode(b: PsiBuilder, level: Int, mode: PathParsingMode, typeQualsMode: TypeQualsMode, parser: Parser): Boolean {
val oldFlags = b.flags
val newFlags = setPathMod(BitUtil.set(oldFlags, TYPE_QUAL_ALLOWED, typeQualsMode == TypeQualsMode.ON), mode)
b.flags = newFlags
check(getPathMod(b.flags) == mode)
// A hack that reduces the growth rate of `level`. This actually allows a deeper path nesting.
val prevPathFrame = ErrorState.get(b).currentFrame?.parentFrame?.ancestorOfTypeOrSelf(PATH)
val nextLevel = if (prevPathFrame != null) {
max(prevPathFrame.level + 2, level - 9)
} else {
level
}
val result = parser.parse(b, nextLevel)
b.flags = oldFlags
return result
}
@JvmStatic
fun isPathMode(b: PsiBuilder, level: Int, mode: PathParsingMode): Boolean =
mode == getPathMod(b.flags)
/**
* `FLOAT_LITERAL` is never produced during lexing. We construct it during parsing from one or
* several `INTEGER_LITERAL` tokens. We need this in order to support nested tuple fields
* access syntax (see https://github.com/intellij-rust/intellij-rust/issues/6029)
*
* Here we collapse these sequences of tokes:
* 1. `INTEGER_LITERAL`, `DOT`, `INTEGER_LITERAL`. Like `0.0`
* 2. `INTEGER_LITERAL`, `DOT` (but **not** `INTEGER_LITERAL`, `DOT`, `IDENTIFIER`). Like `0.`
* 3. Single `INTEGER_LITERAL`, if it has float suffix (`f32`/`f64`) or scientific suffix (`1e3`, `3e-4`)
*/
@JvmStatic
fun parseFloatLiteral(b: PsiBuilder, level: Int): Boolean {
return when (b.tokenType) {
INTEGER_LITERAL -> {
// Works with `0.0`, `0.`, but not `0.foo` (identifier is not accepted after `.`)
if (b.rawLookup(1) == DOT) {
val (collapse, size) = when (b.rawLookup(2)) {
INTEGER_LITERAL, FLOAT_LITERAL -> true to 3
IDENTIFIER -> false to 0
else -> true to 2
}
if (collapse) {
val marker = b.mark()
PsiBuilderUtil.advance(b, size)
marker.collapse(FLOAT_LITERAL)
return true
}
}
// Works with floats without `.` like `1f32`, `1e3`, `3e-4`
val text = b.tokenText
val isFloat = text != null &&
(text.contains("f") || text.contains("e", ignoreCase = true) && !text.endsWith("e"))
&& !text.startsWith("0x")
if (isFloat) {
b.remapCurrentToken(FLOAT_LITERAL)
b.advanceLexer()
}
isFloat
}
// Can be already remapped
FLOAT_LITERAL -> {
b.advanceLexer()
true
}
else -> false
}
}
// !("union" identifier | "async" fn) identifier | self | super | 'Self' | crate
@JvmStatic
fun parsePathIdent(b: PsiBuilder, level: Int): Boolean {
val tokenType = b.tokenType
val result = when (tokenType) {
SELF, SUPER, CSELF, CRATE -> true
IDENTIFIER -> {
val tokenText = b.tokenText
!(tokenText == "union" && b.lookAhead(1) == IDENTIFIER || tokenText == "async" && b.lookAhead(1) == FN)
}
else -> {
// error message
val consumed = consumeToken(b, IDENTIFIER)
check(!consumed)
false
}
}
if (result) {
consumeToken(b, tokenType)
}
return result
}
@JvmStatic
fun unpairedToken(b: PsiBuilder, level: Int): Boolean =
when (b.tokenType) {
LBRACE, RBRACE,
LPAREN, RPAREN,
LBRACK, RBRACK -> false
null -> false // EOF
else -> {
collapsedTokenType(b)?.let { (tokenType, size) ->
val marker = b.mark()
PsiBuilderUtil.advance(b, size)
marker.collapse(tokenType)
} ?: b.advanceLexer()
true
}
}
@JvmStatic
fun macroBindingGroupSeparatorToken(b: PsiBuilder, level: Int): Boolean =
when (b.tokenType) {
PLUS, MUL, Q -> false
else -> unpairedToken(b, level)
}
@JvmStatic
fun macroSemicolon(b: PsiBuilder, level: Int): Boolean {
val m = b.latestDoneMarker ?: return false
b.tokenText
if (b.originalText[m.endOffset - b.offset - 1] == '}') return true
return consumeToken(b, SEMICOLON)
}
@JvmStatic
fun macroIdentifier(b: PsiBuilder, level: Int): Boolean =
when (b.tokenType) {
IDENTIFIER, in RS_KEYWORDS, BOOL_LITERAL -> {
b.advanceLexer()
true
}
else -> false
}
@JvmStatic
fun pathOrTraitType(
b: PsiBuilder,
level: Int,
pathP: Parser,
implicitTraitTypeP: Parser,
traitTypeUpperP: Parser
): Boolean {
val pathOrTraitType = enter_section_(b)
val polybound = enter_section_(b)
val bound = enter_section_(b)
val traitRef = enter_section_(b)
if (!pathP.parse(b, level) || nextTokenIs(b, EXCL)) {
// May be it is lifetime `'a` or `for<'a>` or `foo!()`
exit_section_(b, traitRef, null, false)
exit_section_(b, bound, null, false)
exit_section_(b, polybound, null, false)
exit_section_(b, pathOrTraitType, null, false)
return implicitTraitTypeP.parse(b, level)
}
if (!nextTokenIs(b, PLUS)) {
exit_section_(b, traitRef, null, true)
exit_section_(b, bound, null, true)
exit_section_(b, polybound, null, true)
exit_section_(b, pathOrTraitType, PATH_TYPE, true)
return true
}
exit_section_(b, traitRef, TRAIT_REF, true)
exit_section_(b, bound, BOUND, true)
exit_section_(b, polybound, POLYBOUND, true)
val result = traitTypeUpperP.parse(b, level)
exit_section_(b, pathOrTraitType, TRAIT_TYPE, result)
return result
}
@Suppress("DuplicatedCode")
@JvmStatic
fun typeReferenceOrAssocTypeBinding(
b: PsiBuilder,
level: Int,
pathP: Parser,
assocTypeBindingUpperP: Parser,
typeReferenceP: Parser,
traitTypeUpperP: Parser,
): Boolean {
if (b.tokenType == DYN || b.tokenType == IDENTIFIER && b.tokenText == "dyn" && b.lookAhead(1) != EXCL) {
return typeReferenceP.parse(b, level)
}
val typeOrAssoc = enter_section_(b)
val polybound = enter_section_(b)
val bound = enter_section_(b)
val traitRef = enter_section_(b)
if (!pathP.parse(b, level) || nextTokenIsFast(b, EXCL)) {
exit_section_(b, traitRef, null, false)
exit_section_(b, bound, null, false)
exit_section_(b, polybound, null, false)
exit_section_(b, typeOrAssoc, null, false)
return typeReferenceP.parse(b, level)
}
if (nextTokenIsFast(b, PLUS) ) {
exit_section_(b, traitRef, TRAIT_REF, true)
exit_section_(b, bound, BOUND, true)
exit_section_(b, polybound, POLYBOUND, true)
val result = traitTypeUpperP.parse(b, level)
exit_section_(b, typeOrAssoc, TRAIT_TYPE, result)
return result
}
exit_section_(b, traitRef, null, true)
exit_section_(b, bound, null, true)
exit_section_(b, polybound, null, true)
if (!nextTokenIsFast(b, EQ) && !nextTokenIsFast(b, COLON)) {
exit_section_(b, typeOrAssoc, PATH_TYPE, true)
return true
}
val result = assocTypeBindingUpperP.parse(b, level)
exit_section_(b, typeOrAssoc, ASSOC_TYPE_BINDING, result)
return result
}
private val SPECIAL_MACRO_PARSERS: Map<String, (PsiBuilder, Int) -> Boolean>
private val SPECIAL_EXPR_MACROS: Set<String>
init {
val specialParsers = hashMapOf<String, (PsiBuilder, Int) -> Boolean>()
val exprMacros = hashSetOf<String>()
SPECIAL_MACRO_PARSERS = specialParsers
SPECIAL_EXPR_MACROS = exprMacros
fun put(parser: (PsiBuilder, Int) -> Boolean, isExpr: Boolean, vararg keys: String) {
for (name in keys) {
check(name !in specialParsers) { "$name was already added" }
specialParsers[name] = parser
if (isExpr) {
exprMacros += name
}
}
}
put(RustParser::ExprMacroArgument, true, "dbg")
put(
RustParser::FormatMacroArgument, true, "format", "format_args", "format_args_nl", "write", "writeln",
"print", "println", "eprint", "eprintln", "panic", "unimplemented", "unreachable", "todo"
)
put(
RustParser::AssertMacroArgument, true, "assert", "debug_assert", "assert_eq", "assert_ne",
"debug_assert_eq", "debug_assert_ne"
)
put(RustParser::VecMacroArgument, true, "vec")
put(RustParser::IncludeMacroArgument, true, "include_str", "include_bytes")
put(RustParser::IncludeMacroArgument, false, "include")
put(RustParser::ConcatMacroArgument, true, "concat")
put(RustParser::EnvMacroArgument, true, "env")
put(RustParser::AsmMacroArgument, true, "asm")
}
fun isSpecialMacro(name: String): Boolean =
name in SPECIAL_MACRO_PARSERS
@JvmStatic
fun parseMacroCall(b: PsiBuilder, level: Int, mode: MacroCallParsingMode): Boolean {
if (mode.attrsAndVis && !RustParser.AttrsAndVis(b, level + 1)) return false
if (!RustParser.PathWithoutTypeArgs(b, level + 1) || !consumeToken(b, EXCL)) {
return false
}
val macroName = getMacroName(b, -2)
if (mode.forbidExprSpecialMacros && macroName in SPECIAL_EXPR_MACROS) return false
// foo! bar {}
// ^ this ident
val hasIdent = consumeTokenFast(b, IDENTIFIER)
val braceKind = b.tokenType?.let { MacroBraces.fromToken(it) }
if (macroName != null && !hasIdent && braceKind != null) { // try special macro
val specialParser = SPECIAL_MACRO_PARSERS[macroName]
if (specialParser != null && specialParser(b, level + 1)) {
if (braceKind.needsSemicolon && mode.semicolon && !consumeToken(b, SEMICOLON)) {
b.error("`;` expected, got '${b.tokenText}'")
return mode.pin
}
return true
}
}
if (braceKind == null || !parseMacroArgumentLazy(b, level + 1)) {
b.error("<macro argument> expected, got '${b.tokenText}'")
return mode.pin
}
if (braceKind.needsSemicolon && mode.semicolon && !consumeToken(b, SEMICOLON)) {
b.error("`;` expected, got '${b.tokenText}'")
return mode.pin
}
return true
}
// qualifier::foo ! ();
// ^ this name
@Suppress("SameParameterValue")
private fun getMacroName(b: PsiBuilder, nameTokenIndex: Int): String? {
require(nameTokenIndex < 0) {
"`getMacroName` assumes that path with macro name is already parsed and the name token is behind of current position"
}
var steps = 0
var meaningfulSteps = 0
while (meaningfulSteps > nameTokenIndex) {
steps--
val elementType = b.rawLookup(steps) ?: return null
if (!isWhitespaceOrComment(b, elementType)) {
meaningfulSteps--
}
}
return if (b.rawLookup(steps) == IDENTIFIER) {
b.rawLookupText(steps).toString()
} else {
null
}
}
@JvmStatic
fun gtgteqImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, GTGTEQ, GT, GT, EQ)
@JvmStatic
fun gtgtImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, GTGT, GT, GT)
@JvmStatic
fun gteqImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, GTEQ, GT, EQ)
@JvmStatic
fun ltlteqImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, LTLTEQ, LT, LT, EQ)
@JvmStatic
fun ltltImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, LTLT, LT, LT)
@JvmStatic
fun lteqImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, LTEQ, LT, EQ)
@JvmStatic
fun ororImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, OROR, OR, OR)
@JvmStatic
fun andandImpl(b: PsiBuilder, level: Int): Boolean = collapse(b, ANDAND, AND, AND)
private val DEFAULT_NEXT_ELEMENTS: TokenSet = tokenSetOf(EXCL)
private val ASYNC_NEXT_ELEMENTS: TokenSet = tokenSetOf(LBRACE, MOVE, OR)
private val TRY_NEXT_ELEMENTS: TokenSet = tokenSetOf(LBRACE)
@JvmStatic
fun defaultKeyword(b: PsiBuilder, level: Int): Boolean = contextualKeyword(b, "default", DEFAULT)
@JvmStatic
fun unionKeyword(b: PsiBuilder, level: Int): Boolean = contextualKeyword(b, "union", UNION)
@JvmStatic
fun autoKeyword(b: PsiBuilder, level: Int): Boolean = contextualKeyword(b, "auto", AUTO)
@JvmStatic
fun dynKeyword(b: PsiBuilder, level: Int): Boolean = contextualKeyword(b, "dyn", DYN)
@JvmStatic
fun asyncKeyword(b: PsiBuilder, level: Int): Boolean =
contextualKeyword(b, "async", ASYNC)
@JvmStatic
fun asyncBlockKeyword(b: PsiBuilder, level: Int): Boolean =
contextualKeyword(b, "async", ASYNC) { it in ASYNC_NEXT_ELEMENTS }
@JvmStatic
fun tryKeyword(b: PsiBuilder, level: Int): Boolean =
contextualKeyword(b, "try", TRY) { it in TRY_NEXT_ELEMENTS }
@JvmStatic
fun rawKeyword(b: PsiBuilder, level: Int): Boolean = contextualKeywordWithRollback(b, "raw", RAW)
@JvmStatic
private fun collapse(b: PsiBuilder, tokenType: IElementType, vararg parts: IElementType): Boolean {
// We do not want whitespace between parts, so firstly we do raw lookup for each part,
// and when we make sure that we have desired token, we consume and collapse it.
parts.forEachIndexed { i, tt ->
if (b.rawLookup(i) != tt) return false
}
val marker = b.mark()
PsiBuilderUtil.advance(b, parts.size)
marker.collapse(tokenType)
return true
}
/** Collapses contextual tokens (like &&) to a single token */
fun collapsedTokenType(b: PsiBuilder): Pair<IElementType, Int>? {
return when (b.tokenType) {
GT -> when (b.rawLookup(1)) {
GT -> when (b.rawLookup(2)) {
EQ -> GTGTEQ to 3
else -> GTGT to 2
}
EQ -> GTEQ to 2
else -> null
}
LT -> when (b.rawLookup(1)) {
LT -> when (b.rawLookup(2)) {
EQ -> LTLTEQ to 3
else -> LTLT to 2
}
EQ -> LTEQ to 2
else -> null
}
OR -> when (b.rawLookup(1)) {
OR -> OROR to 2
else -> null
}
AND -> when (b.rawLookup(1)) {
AND -> ANDAND to 2
else -> null
}
// See `parseFloatLiteral`
INTEGER_LITERAL -> when (b.rawLookup(1)) {
DOT -> when (b.rawLookup(2)) {
INTEGER_LITERAL, FLOAT_LITERAL -> FLOAT_LITERAL to 3
IDENTIFIER -> null
else -> FLOAT_LITERAL to 2
}
else -> null
}
else -> null
}
}
private fun LighterASTNode.isBracedMacro(b: PsiBuilder): Boolean {
if (tokenType != MACRO_EXPR) return false
val offset = b.offset
val text = b.originalText.subSequence(startOffset - offset, endOffset - offset)
return '}' == text.findLast { it == '}' || it == ']' || it == ')' }
}
/**
* Non-zero if [PsiBuilder] is created with `LighterLazyParseableNode` chameleon.
* (Used this way in implementations of ILightLazyParseableElementType)
*/
private val PsiBuilder.offset: Int
get() {
val firstMarker = (this as Builder).productions?.firstOrNull() ?: return 0
return firstMarker.startOffset
}
private fun contextualKeyword(
b: PsiBuilder,
keyword: String,
elementType: IElementType,
nextElementPredicate: (IElementType?) -> Boolean = { it !in DEFAULT_NEXT_ELEMENTS }
): Boolean {
// Tricky: the token can be already remapped by some previous rule that was backtracked
if (b.tokenType == elementType ||
b.tokenType == IDENTIFIER && b.tokenText == keyword && nextElementPredicate(b.lookAhead(1))) {
b.remapCurrentToken(elementType)
b.advanceLexer()
return true
}
return false
}
private fun contextualKeywordWithRollback(b: PsiBuilder, keyword: String, elementType: IElementType): Boolean {
if (b.tokenType == IDENTIFIER && b.tokenText == keyword) {
val marker = b.mark()
b.advanceLexer()
marker.collapse(elementType)
return true
}
return false
}
@JvmStatic
fun parseMacroArgumentLazy(builder: PsiBuilder, level: Int): Boolean =
parseTokenTreeLazy(builder, level, MACRO_ARGUMENT)
@JvmStatic
fun parseMacroBodyLazy(builder: PsiBuilder, level: Int): Boolean =
parseTokenTreeLazy(builder, level, MACRO_BODY)
@JvmStatic
fun parseTokenTreeLazy(builder: PsiBuilder, level: Int, tokenTypeToCollapse: IElementType): Boolean {
val firstToken = builder.tokenType
if (firstToken == null || firstToken !in LEFT_BRACES) return false
val rightBrace = MacroBraces.fromTokenOrFail(firstToken).closeToken
PsiBuilderUtil.parseBlockLazy(builder, firstToken, rightBrace, tokenTypeToCollapse)
return true
}
fun hasProperTokenTreeBraceBalance(text: CharSequence, lexer: Lexer): Boolean {
lexer.start(text)
val firstToken = lexer.tokenType
if (firstToken == null || firstToken !in LEFT_BRACES) return false
val rightBrace = MacroBraces.fromTokenOrFail(firstToken).closeToken
return PsiBuilderUtil.hasProperBraceBalance(text, lexer, firstToken, rightBrace)
}
@JvmStatic
fun parseAnyBraces(b: PsiBuilder, level: Int, param: Parser): Boolean {
val firstToken = b.tokenType ?: return false
if (firstToken !in LEFT_BRACES) return false
val leftBrace = MacroBraces.fromTokenOrFail(firstToken)
val pos = b.mark()
b.advanceLexer() // Consume '{' or '(' or '['
return b.withRootBrace(leftBrace) { rootBrace ->
if (!param.parse(b, level + 1)) {
pos.rollbackTo()
return false
}
val lastToken = b.tokenType
if (lastToken == null || lastToken !in RIGHT_BRACES) {
b.error("'${leftBrace.closeText}' expected")
return pos.close(lastToken == null)
}
var rightBrace = MacroBraces.fromToken(lastToken)
if (rightBrace == leftBrace) {
b.advanceLexer() // Consume '}' or ')' or ']'
} else {
b.error("'${leftBrace.closeText}' expected")
if (leftBrace == rootBrace) {
// Recovery loop. Consume everything until [rightBrace] is [leftBrace]
while (rightBrace != leftBrace && !b.eof()) {
b.advanceLexer()
val tokenType = b.tokenType ?: break
rightBrace = MacroBraces.fromToken(tokenType)
}
b.advanceLexer()
}
}
pos.drop()
return true
}
}
/** Saves [currentBrace] as root brace if it is not set yet; applies the root brace to [f] */
private inline fun PsiBuilder.withRootBrace(currentBrace: MacroBraces, f: (MacroBraces) -> Boolean): Boolean {
val oldFlags = flags
val oldRootBrace = getMacroBraces(oldFlags)
if (oldRootBrace == null) {
flags = setMacroBraces(oldFlags, currentBrace)
}
try {
return f(oldRootBrace ?: currentBrace)
} finally {
flags = oldFlags
}
}
@JvmStatic
fun parseCodeBlockLazy(builder: PsiBuilder, level: Int): Boolean {
return PsiBuilderUtil.parseBlockLazy(builder, LBRACE, RBRACE, BLOCK) != null
}
@JvmStatic
fun parseSimplePat(builder: PsiBuilder): Boolean {
return RustParser.SimplePat(builder, 0)
}
private tailrec fun Frame.ancestorOfTypeOrSelf(elementType: IElementType): Frame? {
return if (this.elementType == elementType) {
this
} else {
parentFrame?.ancestorOfTypeOrSelf(elementType)
}
}
}
| src/main/kotlin/org/rust/lang/core/parser/RustParserUtil.kt | 652352129 |
/*
* Copyright (C) 2016 Mantas Varnagiris.
*
* 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.
*/
package com.mvcoding.expensius.feature.premium
import rx.Observable
import java.io.Closeable
interface BillingProductsService : Closeable {
fun billingProducts(): Observable<List<BillingProduct>>
} | app-core/src/main/kotlin/com/mvcoding/expensius/feature/premium/BillingProductsService.kt | 1093286251 |
package edu.csh.chase.kgeojson
public enum class GeoJsonType {
Point,
MultiPoint,
LineString,
MultiLineString,
Polygon,
MultiPolygon,
GeometryCollection,
Feature,
FeatureCollection;
} | src/main/kotlin/edu/csh/chase/kgeojson/GeoJsonType.kt | 4232982476 |
package org.jetbrains.fortran.ide.inspections
import org.junit.Test
class FortranConstructNameTest() : FortranInspectionsBaseTestCase(FortranConstructNameMismatchInspection()) {
@Test
fun testIfConstruct() = checkByText(
"""
myIf: if (2 > 1) then
write (*,*) "2>1"
else if (2 == 1) then MYIF
write(*,*) "2=1"
else <error descr="Construct name mismatch">notMyIf</error>
write(*,*) "2<1"
endif <error descr="Construct name mismatch">if</error>
if: if (2*2 .eq. 4) then
write(*,*) "2*2=4"
endif
end
""")
@Test
fun testFix() = checkFixByText("Construct name fix", """
myDo: do i=1,5,1
write(*,*) i
end do <error descr="Construct name mismatch">myIf<caret></error>
end
""", """
myDo: do i=1,5,1
write(*,*) i
end do myDo
end
""")
} | src/test/kotlin/org/jetbrains/fortran/ide/inspections/FortranConstructNameTest.kt | 1345997606 |
package com.teamwizardry.librarianlib.facade.test.controllers.base
import com.teamwizardry.librarianlib.facade.container.FacadeControllerRegistry
import com.teamwizardry.librarianlib.facade.container.FacadeControllerType
import net.minecraft.util.Identifier
import java.lang.IllegalArgumentException
class TestControllerSet(val name: String, config: Entry.Group.() -> Unit) {
val root: Entry.Group = Entry.Group(name)
val types: List<Type<*, *>>
init {
root.config()
types = root.collectTypes(mutableListOf())
allTypes.addAll(types)
}
fun createData(): Map<Type<*, *>, TestControllerData> {
return types.associateWith { it.dataClass.newInstance() }
}
fun getType(id: Identifier): Type<*, *> {
return types.find { it.id == id }
?: throw IllegalArgumentException("No container type for id '$id'")
}
fun <T: TestController<*>> controllerType(type: Class<T>): FacadeControllerType<T> {
@Suppress("UNCHECKED_CAST")
return getType(makeId(type)).controllerType as FacadeControllerType<T>
}
sealed class Entry(val name: String) {
abstract fun collectTypes(list: MutableList<Type<*, *>>): List<Type<*, *>>
class Controller(name: String, val type: Type<*, *>): Entry(name) {
override fun collectTypes(list: MutableList<Type<*, *>>): List<Type<*, *>> {
list.add(type)
return list
}
}
class Group(name: String, val entries: MutableList<Entry> = mutableListOf()): Entry(name) {
inline fun group(name: String, config: Group.() -> Unit) {
val group = Group(name)
group.config()
entries.add(group)
}
inline fun <reified T : TestControllerData, C : TestController<T>> controller(
name: String,
containerClass: Class<C>
) {
entries.add(Controller(name, Type(T::class.java, containerClass)))
}
override fun collectTypes(list: MutableList<Type<*, *>>): List<Type<*, *>> {
entries.forEach {
it.collectTypes(list)
}
return list
}
}
}
class Type<T : TestControllerData, C : TestController<T>>(
val dataClass: Class<T>,
val controllerClass: Class<C>
) {
val id: Identifier = makeId(controllerClass)
val controllerType: FacadeControllerType<C> = FacadeControllerRegistry.register(id, controllerClass)
}
companion object {
val allTypes: MutableList<Type<*, *>> = mutableListOf()
fun getTypeByData(dataClass: Class<*>): Type<*, *> {
return allTypes.find { it.dataClass == dataClass }
?: throw IllegalArgumentException("No container type for data type '${dataClass.canonicalName}'")
}
fun <T: TestController<*>> makeId(controllerClass: Class<T>): Identifier {
return Identifier("liblib-facade-test", controllerClass.simpleName.lowercase())
}
}
}
| modules/facade/src/test/kotlin/com/teamwizardry/librarianlib/facade/test/controllers/base/TestControllerSet.kt | 2320646084 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.macros.proc
import java.io.IOException
class ProcessCreationException(cause: IOException) : RuntimeException(cause)
| src/main/kotlin/org/rust/lang/core/macros/proc/ProcessCreationException.kt | 3926314141 |
package com.quijotelui.repository
import com.quijotelui.model.*
import java.util.*
interface IFacturaDao {
fun findAll() : MutableList<Factura>
fun findByFecha(fecha : Date) : MutableList<Factura>
fun findByFechas(fechaInicio : Date, fechaFin : Date) : MutableList<Factura>
fun findByComprobante(codigo : String, numero : String) : MutableList<Factura>
fun findEstadoByComprobante(codigo : String, numero : String) : MutableList<Any>
fun findContribuyenteByComprobante(codigo : String, numero : String) : MutableList<Any>
fun findParametroByNombre(nombre : String) : MutableList<Parametro>
fun findImpuestoByComprobante(codigo : String, numero : String) : MutableList<Impuesto>
fun findPagoByComprobante(codigo : String, numero : String) : MutableList<Pago>
fun findFacturaDetalleByComprobante(codigo : String, numero : String) : MutableList<FacturaDetalle>
fun findInformacionByDocumento(documento : String) : MutableList<Informacion>
} | src/main/kotlin/com/quijotelui/repository/IFacturaDao.kt | 3792273600 |
package org.jetbrains.dokka.tests
import com.google.inject.Guice
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtil
import com.intellij.rt.execution.junit.FileComparisonFailure
import org.jetbrains.dokka.*
import org.jetbrains.dokka.Utilities.DokkaAnalysisModule
import org.jetbrains.kotlin.cli.common.config.ContentRoot
import org.jetbrains.kotlin.cli.common.config.KotlinSourceRoot
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageLocation
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
import org.jetbrains.kotlin.cli.common.messages.MessageCollector
import org.jetbrains.kotlin.cli.jvm.config.JavaSourceRoot
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.junit.Assert
import org.junit.Assert.fail
import java.io.File
fun verifyModel(vararg roots: ContentRoot,
withJdk: Boolean = false,
withKotlinRuntime: Boolean = false,
format: String = "html",
includeNonPublic: Boolean = true,
perPackageOptions: List<DokkaConfiguration.PackageOptions> = emptyList(),
noStdlibLink: Boolean = true,
collectInheritedExtensionsFromLibraries: Boolean = false,
verifier: (DocumentationModule) -> Unit) {
val documentation = DocumentationModule("test")
val options = DocumentationOptions(
"",
format,
includeNonPublic = includeNonPublic,
skipEmptyPackages = false,
includeRootPackage = true,
sourceLinks = listOf(),
perPackageOptions = perPackageOptions,
generateClassIndexPage = false,
generatePackageIndexPage = false,
noStdlibLink = noStdlibLink,
noJdkLink = false,
cacheRoot = "default",
languageVersion = null,
apiVersion = null,
collectInheritedExtensionsFromLibraries = collectInheritedExtensionsFromLibraries
)
appendDocumentation(documentation, *roots,
withJdk = withJdk,
withKotlinRuntime = withKotlinRuntime,
options = options)
documentation.prepareForGeneration(options)
verifier(documentation)
}
fun appendDocumentation(documentation: DocumentationModule,
vararg roots: ContentRoot,
withJdk: Boolean = false,
withKotlinRuntime: Boolean = false,
options: DocumentationOptions,
defaultPlatforms: List<String> = emptyList()) {
val messageCollector = object : MessageCollector {
override fun clear() {
}
override fun report(severity: CompilerMessageSeverity, message: String, location: CompilerMessageLocation?) {
when (severity) {
CompilerMessageSeverity.STRONG_WARNING,
CompilerMessageSeverity.WARNING,
CompilerMessageSeverity.LOGGING,
CompilerMessageSeverity.OUTPUT,
CompilerMessageSeverity.INFO,
CompilerMessageSeverity.ERROR -> {
println("$severity: $message at $location")
}
CompilerMessageSeverity.EXCEPTION -> {
fail("$severity: $message at $location")
}
}
}
override fun hasErrors() = false
}
val environment = AnalysisEnvironment(messageCollector)
environment.apply {
if (withJdk || withKotlinRuntime) {
val stringRoot = PathManager.getResourceRoot(String::class.java, "/java/lang/String.class")
addClasspath(File(stringRoot))
}
if (withKotlinRuntime) {
val kotlinStrictfpRoot = PathManager.getResourceRoot(Strictfp::class.java, "/kotlin/jvm/Strictfp.class")
addClasspath(File(kotlinStrictfpRoot))
}
addRoots(roots.toList())
loadLanguageVersionSettings(options.languageVersion, options.apiVersion)
}
val defaultPlatformsProvider = object : DefaultPlatformsProvider {
override fun getDefaultPlatforms(descriptor: DeclarationDescriptor) = defaultPlatforms
}
val injector = Guice.createInjector(
DokkaAnalysisModule(environment, options, defaultPlatformsProvider, documentation.nodeRefGraph, DokkaConsoleLogger))
buildDocumentationModule(injector, documentation)
Disposer.dispose(environment)
}
fun verifyModel(source: String,
withJdk: Boolean = false,
withKotlinRuntime: Boolean = false,
format: String = "html",
includeNonPublic: Boolean = true,
verifier: (DocumentationModule) -> Unit) {
if (!File(source).exists()) {
throw IllegalArgumentException("Can't find test data file $source")
}
verifyModel(contentRootFromPath(source),
withJdk = withJdk,
withKotlinRuntime = withKotlinRuntime,
format = format,
includeNonPublic = includeNonPublic,
verifier = verifier)
}
fun verifyPackageMember(source: String,
withJdk: Boolean = false,
withKotlinRuntime: Boolean = false,
verifier: (DocumentationNode) -> Unit) {
verifyModel(source, withJdk = withJdk, withKotlinRuntime = withKotlinRuntime) { model ->
val pkg = model.members.single()
verifier(pkg.members.single())
}
}
fun verifyJavaModel(source: String,
withKotlinRuntime: Boolean = false,
verifier: (DocumentationModule) -> Unit) {
val tempDir = FileUtil.createTempDirectory("dokka", "")
try {
val sourceFile = File(source)
FileUtil.copy(sourceFile, File(tempDir, sourceFile.name))
verifyModel(JavaSourceRoot(tempDir, null), withJdk = true, withKotlinRuntime = withKotlinRuntime, verifier = verifier)
}
finally {
FileUtil.delete(tempDir)
}
}
fun verifyJavaPackageMember(source: String,
withKotlinRuntime: Boolean = false,
verifier: (DocumentationNode) -> Unit) {
verifyJavaModel(source, withKotlinRuntime) { model ->
val pkg = model.members.single()
verifier(pkg.members.single())
}
}
fun verifyOutput(roots: Array<ContentRoot>,
outputExtension: String,
withJdk: Boolean = false,
withKotlinRuntime: Boolean = false,
format: String = "html",
includeNonPublic: Boolean = true,
noStdlibLink: Boolean = true,
collectInheritedExtensionsFromLibraries: Boolean = false,
outputGenerator: (DocumentationModule, StringBuilder) -> Unit) {
verifyModel(
*roots,
withJdk = withJdk,
withKotlinRuntime = withKotlinRuntime,
format = format,
includeNonPublic = includeNonPublic,
noStdlibLink = noStdlibLink,
collectInheritedExtensionsFromLibraries = collectInheritedExtensionsFromLibraries
) {
verifyModelOutput(it, outputExtension, roots.first().path, outputGenerator)
}
}
fun verifyModelOutput(it: DocumentationModule,
outputExtension: String,
sourcePath: String,
outputGenerator: (DocumentationModule, StringBuilder) -> Unit) {
val output = StringBuilder()
outputGenerator(it, output)
val ext = outputExtension.removePrefix(".")
val expectedFile = File(sourcePath.replaceAfterLast(".", ext, sourcePath + "." + ext))
assertEqualsIgnoringSeparators(expectedFile, output.toString())
}
fun verifyOutput(
path: String,
outputExtension: String,
withJdk: Boolean = false,
withKotlinRuntime: Boolean = false,
format: String = "html",
includeNonPublic: Boolean = true,
noStdlibLink: Boolean = true,
collectInheritedExtensionsFromLibraries: Boolean = false,
outputGenerator: (DocumentationModule, StringBuilder) -> Unit
) {
verifyOutput(
arrayOf(contentRootFromPath(path)),
outputExtension,
withJdk,
withKotlinRuntime,
format,
includeNonPublic,
noStdlibLink,
collectInheritedExtensionsFromLibraries,
outputGenerator
)
}
fun verifyJavaOutput(path: String,
outputExtension: String,
withKotlinRuntime: Boolean = false,
outputGenerator: (DocumentationModule, StringBuilder) -> Unit) {
verifyJavaModel(path, withKotlinRuntime) { model ->
verifyModelOutput(model, outputExtension, path, outputGenerator)
}
}
fun assertEqualsIgnoringSeparators(expectedFile: File, output: String) {
if (!expectedFile.exists()) expectedFile.createNewFile()
val expectedText = expectedFile.readText().replace("\r\n", "\n")
val actualText = output.replace("\r\n", "\n")
if(expectedText != actualText)
throw FileComparisonFailure("", expectedText, actualText, expectedFile.canonicalPath)
}
fun assertEqualsIgnoringSeparators(expectedOutput: String, output: String) {
Assert.assertEquals(expectedOutput.replace("\r\n", "\n"), output.replace("\r\n", "\n"))
}
fun StringBuilder.appendChildren(node: ContentBlock): StringBuilder {
for (child in node.children) {
val childText = child.toTestString()
append(childText)
}
return this
}
fun StringBuilder.appendNode(node: ContentNode): StringBuilder {
when (node) {
is ContentText -> {
append(node.text)
}
is ContentEmphasis -> append("*").appendChildren(node).append("*")
is ContentBlockCode -> {
if (node.language.isNotBlank())
appendln("[code lang=${node.language}]")
else
appendln("[code]")
appendChildren(node)
appendln()
appendln("[/code]")
}
is ContentNodeLink -> {
append("[")
appendChildren(node)
append(" -> ")
append(node.node.toString())
append("]")
}
is ContentBlock -> {
appendChildren(node)
}
is NodeRenderContent -> {
append("render(")
append(node.node)
append(",")
append(node.mode)
append(")")
}
is ContentSymbol -> { append(node.text) }
is ContentEmpty -> { /* nothing */ }
else -> throw IllegalStateException("Don't know how to format node $node")
}
return this
}
fun ContentNode.toTestString(): String {
val node = this
return StringBuilder().apply {
appendNode(node)
}.toString()
}
val ContentRoot.path: String
get() = when(this) {
is KotlinSourceRoot -> path
is JavaSourceRoot -> file.path
else -> throw UnsupportedOperationException()
}
| core/src/test/kotlin/TestAPI.kt | 830028159 |
package nl.rsdt.japp.application.fragments
import android.app.Fragment
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.IntentSender
import android.content.SharedPreferences
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.preference.PreferenceManager
import android.util.Log
import android.util.Pair
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.github.clans.fab.FloatingActionButton
import com.github.clans.fab.FloatingActionMenu
import com.google.android.gms.common.api.Status
import com.google.android.gms.maps.MapView
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.google.android.gms.maps.model.PolygonOptions
import com.google.android.material.snackbar.Snackbar
import com.google.gson.Gson
import nl.rsdt.japp.R
import nl.rsdt.japp.application.Japp
import nl.rsdt.japp.application.JappPreferences
import nl.rsdt.japp.jotial.data.bodies.VosPostBody
import nl.rsdt.japp.jotial.data.nav.Location
import nl.rsdt.japp.jotial.data.structures.area348.AutoInzittendeInfo
import nl.rsdt.japp.jotial.maps.MapManager
import nl.rsdt.japp.jotial.maps.NavigationLocationManager
import nl.rsdt.japp.jotial.maps.deelgebied.Deelgebied
import nl.rsdt.japp.jotial.maps.management.MarkerIdentifier
import nl.rsdt.japp.jotial.maps.movement.MovementManager
import nl.rsdt.japp.jotial.maps.pinning.Pin
import nl.rsdt.japp.jotial.maps.pinning.PinningManager
import nl.rsdt.japp.jotial.maps.pinning.PinningSession
import nl.rsdt.japp.jotial.maps.sighting.SightingIcon
import nl.rsdt.japp.jotial.maps.sighting.SightingSession
import nl.rsdt.japp.jotial.maps.wrapper.IJotiMap
import nl.rsdt.japp.jotial.maps.wrapper.IPolygon
import nl.rsdt.japp.jotial.maps.wrapper.google.GoogleJotiMap
import nl.rsdt.japp.jotial.maps.wrapper.osm.OsmJotiMap
import nl.rsdt.japp.jotial.navigation.NavigationSession
import nl.rsdt.japp.jotial.net.apis.AutoApi
import nl.rsdt.japp.jotial.net.apis.VosApi
import nl.rsdt.japp.service.AutoSocketHandler
import nl.rsdt.japp.service.LocationService
import nl.rsdt.japp.service.ServiceManager
import org.acra.ktx.sendWithAcra
import org.osmdroid.config.Configuration
import org.osmdroid.tileprovider.tilesource.TileSourceFactory
import org.osmdroid.util.GeoPoint
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.File
import java.util.*
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 8-7-2016
* Description...
*/
class JappMapFragment : Fragment(), IJotiMap.OnMapReadyCallback, SharedPreferences.OnSharedPreferenceChangeListener,Deelgebied.OnColorChangeListener {
private val serviceManager = ServiceManager<LocationService, LocationService.LocationBinder>(LocationService::class.java)
var jotiMap: IJotiMap? = null
private set
private var googleMapView: MapView? = null
private var navigationLocationManager: NavigationLocationManager? = null
private var callback: IJotiMap.OnMapReadyCallback? = null
private val pinningManager = PinningManager()
var movementManager: MovementManager? = MovementManager()
private set
private val areas = HashMap<String, IPolygon>()
private var osmActive = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
navigationLocationManager = NavigationLocationManager()
JappPreferences.visiblePreferences.registerOnSharedPreferenceChangeListener(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
pinningManager.intialize(activity)
pinningManager.onCreate(savedInstanceState)
movementManager!!.onCreate(savedInstanceState)
// Inflate the layout for this fragment
val v = inflater.inflate(R.layout.fragment_map, container, false)
return createMap(savedInstanceState, v)
}
private fun createMap(savedInstanceState: Bundle?, v: View): View {
val useOSM = JappPreferences.useOSM()
val view: View
view = if (useOSM) {
createOSMMap(savedInstanceState, v)
} else {
createGoogleMap(savedInstanceState, v)
}
val menu = view.findViewById<FloatingActionMenu>(R.id.fab_menu)
menu.bringToFront()
return view
}
private fun createOSMMap(savedInstanceState: Bundle?, v: View): View {
osmActive = true
val osmView = org.osmdroid.views.MapView(activity)
(v as ViewGroup).addView(osmView)
val ctx = activity.application
Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx))
when (JappPreferences.osmMapSource) {
JappPreferences.OsmMapType.Mapnik -> osmView.setTileSource(TileSourceFactory.MAPNIK)
JappPreferences.OsmMapType.OpenSeaMap -> osmView.setTileSource(TileSourceFactory.OPEN_SEAMAP)
JappPreferences.OsmMapType.HikeBike -> osmView.setTileSource(TileSourceFactory.HIKEBIKEMAP)
JappPreferences.OsmMapType.OpenTopo -> osmView.setTileSource(TileSourceFactory.OpenTopo)
JappPreferences.OsmMapType.Fiets_NL -> osmView.setTileSource(TileSourceFactory.FIETS_OVERLAY_NL)
JappPreferences.OsmMapType.Default -> osmView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE)
JappPreferences.OsmMapType.CloudMade_Normal -> osmView.setTileSource(TileSourceFactory.CLOUDMADESTANDARDTILES)
JappPreferences.OsmMapType.CloudMade_Small -> osmView.setTileSource(TileSourceFactory.CLOUDMADESMALLTILES)
JappPreferences.OsmMapType.ChartBundle_ENRH -> osmView.setTileSource(TileSourceFactory.ChartbundleENRH)
JappPreferences.OsmMapType.ChartBundle_ENRL -> osmView.setTileSource(TileSourceFactory.ChartbundleENRH)
JappPreferences.OsmMapType.ChartBundle_WAC -> osmView.setTileSource(TileSourceFactory.ChartbundleWAC)
JappPreferences.OsmMapType.USGS_Sat -> osmView.setTileSource(TileSourceFactory.USGS_SAT)
JappPreferences.OsmMapType.USGS_Topo -> osmView.setTileSource(TileSourceFactory.USGS_TOPO)
JappPreferences.OsmMapType.Public_Transport -> osmView.setTileSource(TileSourceFactory.PUBLIC_TRANSPORT)
JappPreferences.OsmMapType.Road_NL -> osmView.setTileSource(TileSourceFactory.ROADS_OVERLAY_NL)
JappPreferences.OsmMapType.Base_NL -> osmView.setTileSource(TileSourceFactory.BASE_OVERLAY_NL)
else -> osmView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE)
}
osmView.controller.setCenter(GeoPoint(51.958852, 5.954517))
osmView.controller.setZoom(11)
osmView.setBuiltInZoomControls(true)
osmView.setMultiTouchControls(true)
osmView.isFlingEnabled = true
osmView.isTilesScaledToDpi = true
if (savedInstanceState != null) {
val osmbundle = savedInstanceState.getBundle(OSM_BUNDLE)
if (osmbundle != null) {
osmView.controller.setZoom(osmbundle.getInt(OSM_ZOOM))
osmView.controller.setCenter(GeoPoint(osmbundle.getDouble(OSM_LAT), osmbundle.getDouble(OSM_LNG)))
osmView.rotation = osmbundle.getFloat(OSM_OR)
}
}
movementManager!!.setSnackBarView(osmView)
setupHuntButton(v).isEnabled = true
setupSpotButton(v).isEnabled = true
setupPinButton(v).isEnabled = true
setupFollowButton(v)
setupNavigationButton(v)
jotiMap = OsmJotiMap.getJotiMapInstance(osmView)
Configuration.getInstance().load(activity, PreferenceManager.getDefaultSharedPreferences(activity))
return v
}
private fun createGoogleMap(savedInstanceState: Bundle?, v: View): View {
osmActive = false
googleMapView = MapView(activity)
(v as ViewGroup).addView(googleMapView)
val ctx = activity.application
Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx))
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(BUNDLE_MAP)) {
googleMapView!!.onCreate(savedInstanceState.getBundle(BUNDLE_MAP))
} else {
googleMapView!!.onCreate(null)
}
} else {
googleMapView!!.onCreate(null)
}
movementManager!!.setSnackBarView(googleMapView!!)
setupHuntButton(v)
setupSpotButton(v)
setupPinButton(v)
setupFollowButton(v)
setupNavigationButton(v)
jotiMap = GoogleJotiMap.getJotiMapInstance(googleMapView!!)
if (savedInstanceState != null) {
val osmbundle = savedInstanceState.getBundle(OSM_BUNDLE)
if (osmbundle != null) {
jotiMap!!.setPreviousZoom(osmbundle.getInt(OSM_ZOOM))
jotiMap!!.setPreviousCameraPosition(osmbundle.getDouble(OSM_LAT), osmbundle.getDouble(OSM_LNG))
jotiMap!!.setPreviousRotation(osmbundle.getFloat(OSM_OR))
}
}
return v
}
override fun onSaveInstanceState(savedInstanceState: Bundle?) {
movementManager!!.onSaveInstanceState(savedInstanceState)
pinningManager.onSaveInstanceState(savedInstanceState)
savedInstanceState?.putBoolean(BUNDLE_OSM_ACTIVE, osmActive)
if (!osmActive) {
val mapBundle = Bundle()
googleMapView!!.onSaveInstanceState(mapBundle)
savedInstanceState?.putBundle(BUNDLE_MAP, mapBundle)
} else if (jotiMap is OsmJotiMap) {
val osmMap = (jotiMap as OsmJotiMap).osmMap
val osmMapBundle = Bundle()
osmMapBundle.putInt(OSM_ZOOM, osmMap.zoomLevel)
osmMapBundle.putDouble(OSM_LAT, osmMap.mapCenter.latitude)
osmMapBundle.putDouble(OSM_LNG, osmMap.mapCenter.longitude)
osmMapBundle.putFloat(OSM_OR, osmMap.mapOrientation)
savedInstanceState?.putBundle(OSM_BUNDLE, osmMapBundle)
}
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState)
}
fun getMapAsync(callback: IJotiMap.OnMapReadyCallback) {
this.callback = callback
jotiMap!!.getMapAsync(this)
}
override fun onStart() {
super.onStart()
if (!osmActive) {
googleMapView!!.onStart()
}
}
override fun onStop() {
super.onStop()
if (!osmActive) {
googleMapView!!.onStop()
}
}
override fun onResume() {
super.onResume()
if (!osmActive) {
googleMapView!!.onResume()
} else {
Configuration.getInstance().load(activity, PreferenceManager.getDefaultSharedPreferences(activity))
}
movementManager!!.setListener(object:LocationService.OnResolutionRequiredListener{
override fun onResolutionRequired(status: Status) {
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
activity,
REQUEST_CHECK_SETTINGS)
} catch (e: IntentSender.SendIntentException) {
// Ignore the error.
e.sendWithAcra()
}
}
})
serviceManager.add(movementManager!!)
movementManager!!.onResume()
if (!serviceManager.isBound) {
serviceManager.bind(this.activity)
}
}
override fun onPause() {
super.onPause()
if (!osmActive && googleMapView != null) {
googleMapView!!.onPause()
}
movementManager!!.onPause()
}
override fun onDestroy() {
super.onDestroy()
if (!osmActive) {
googleMapView!!.onDestroy()
}
if (movementManager != null) {
movementManager!!.onDestroy()
serviceManager.remove(movementManager!!)
movementManager = null
}
JappPreferences.visiblePreferences.registerOnSharedPreferenceChangeListener(this)
serviceManager.unbind(activity)
}
override fun onLowMemory() {
super.onLowMemory()
if (!osmActive) {
googleMapView!!.onLowMemory()
}
}
override fun onMapReady(jotiMap: IJotiMap) {
this.jotiMap = jotiMap
jotiMap.clear()
movementManager?.onMapReady(jotiMap)
setupDeelgebieden()
pinningManager.onMapReady(jotiMap)
callback?.onMapReady(jotiMap)
val markerOptions = MarkerOptions()
.position(LatLng(0.0, 0.0))
.visible(false)
val icon: Bitmap? = null
val marker = jotiMap.addMarker(Pair(markerOptions, icon))
navigationLocationManager?.setCallback(object : NavigationLocationManager.OnNewLocation {
override fun onNewLocation(location: Location) {
val identifier = MarkerIdentifier.Builder()
identifier.setType(MarkerIdentifier.TYPE_NAVIGATE_CAR)
identifier.add("addedBy", location.username)
identifier.add("createdOn", location.createdOn.toString())
marker.title = Gson().toJson(identifier.create())
marker.isVisible = true
marker.position = LatLng(location.latitude, location.longitude)
}
override fun onNotInCar() {
marker.isVisible = false
marker.position = LatLng(0.0, 0.0)
}
})
}
private fun setupDeelgebieden() {
val enabled = JappPreferences.areasEnabled
for (area in enabled) {
if (!areas.containsKey(area)) {
setupDeelgebied(Deelgebied.parse(area))
} else { // vraag me niet hoe maar dit fixed #112
val poly = areas[area]
poly!!.remove()
areas.remove(area)
setupDeelgebied(Deelgebied.parse(area))
}
}
if (jotiMap is OsmJotiMap) {
(jotiMap as OsmJotiMap).osmMap.invalidate()
}
}
fun setupDeelgebied(deelgebied: Deelgebied?) {
if (!deelgebied!!.coordinates.isEmpty()) {
setUpDeelgebiedReal(deelgebied)
} else {
deelgebied.getDeelgebiedAsync(object : Deelgebied.OnInitialized{
override fun onInitialized(deelgebied: Deelgebied) {
setUpDeelgebiedReal(deelgebied)
}
})
}
}
private fun setUpDeelgebiedReal(deelgebied: Deelgebied) {
val options = PolygonOptions().addAll(deelgebied.coordinates)
if (JappPreferences.areasColorEnabled) {
val alphaPercent = JappPreferences.areasColorAlpha
val alpha = (100 - alphaPercent).toFloat() / 100 * 255
options.fillColor(deelgebied.alphaled(Math.round(alpha)))
} else {
options.fillColor(Color.TRANSPARENT)
}
options.strokeColor(deelgebied.color)
if (JappPreferences.areasEdgesEnabled) {
options.strokeWidth(JappPreferences.areasEdgesWidth.toFloat())
} else {
options.strokeWidth(0f)
}
options.visible(true)
areas[deelgebied.name] = jotiMap!!.addPolygon(options)
}
override fun onColorChange(deelgebied: Deelgebied) {
setUpDeelgebiedReal(deelgebied)
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
var polygon: IPolygon
when (key) {
JappPreferences.OSM_MAP_TYPE -> {
val lJotiMap = jotiMap
if(lJotiMap is OsmJotiMap) {
val osmView = lJotiMap.osmMap
when (JappPreferences.osmMapSource) {
JappPreferences.OsmMapType.Mapnik -> osmView.setTileSource(TileSourceFactory.MAPNIK)
JappPreferences.OsmMapType.OpenSeaMap -> osmView.setTileSource(TileSourceFactory.OPEN_SEAMAP)
JappPreferences.OsmMapType.HikeBike -> osmView.setTileSource(TileSourceFactory.HIKEBIKEMAP)
JappPreferences.OsmMapType.OpenTopo -> osmView.setTileSource(TileSourceFactory.OpenTopo)
JappPreferences.OsmMapType.Fiets_NL -> osmView.setTileSource(TileSourceFactory.FIETS_OVERLAY_NL)
JappPreferences.OsmMapType.Default -> osmView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE)
JappPreferences.OsmMapType.CloudMade_Normal -> osmView.setTileSource(TileSourceFactory.CLOUDMADESTANDARDTILES)
JappPreferences.OsmMapType.CloudMade_Small -> osmView.setTileSource(TileSourceFactory.CLOUDMADESMALLTILES)
JappPreferences.OsmMapType.ChartBundle_ENRH -> osmView.setTileSource(TileSourceFactory.ChartbundleENRH)
JappPreferences.OsmMapType.ChartBundle_ENRL -> osmView.setTileSource(TileSourceFactory.ChartbundleENRH)
JappPreferences.OsmMapType.ChartBundle_WAC -> osmView.setTileSource(TileSourceFactory.ChartbundleWAC)
JappPreferences.OsmMapType.USGS_Sat -> osmView.setTileSource(TileSourceFactory.USGS_SAT)
JappPreferences.OsmMapType.USGS_Topo -> osmView.setTileSource(TileSourceFactory.USGS_TOPO)
JappPreferences.OsmMapType.Public_Transport -> osmView.setTileSource(TileSourceFactory.PUBLIC_TRANSPORT)
JappPreferences.OsmMapType.Road_NL -> osmView.setTileSource(TileSourceFactory.ROADS_OVERLAY_NL)
JappPreferences.OsmMapType.Base_NL -> osmView.setTileSource(TileSourceFactory.BASE_OVERLAY_NL)
else -> osmView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE)
}
osmView.invalidate()
}
}
JappPreferences.USE_OSM -> {
}
JappPreferences.AREAS -> {
if (jotiMap != null) {
val enabled = JappPreferences.areasEnabled
for (area in enabled) {
if (!areas.containsKey(area)) {
setupDeelgebied(Deelgebied.parse(area))
}
}
val toBeRemoved = ArrayList<String>()
for (area in areas.keys) {
if (!enabled.contains(area)) {
val poly = areas[area]
poly!!.remove()
toBeRemoved.add(area)
}
}
for (area in toBeRemoved) {
areas.remove(area)
}
if (jotiMap is OsmJotiMap) {
(jotiMap as OsmJotiMap).osmMap.invalidate()
}
}
}
JappPreferences.AREAS_EDGES -> {
val edges = JappPreferences.areasEdgesEnabled
for ((_, value) in areas) {
polygon = value
if (edges) {
polygon.setStrokeWidth(JappPreferences.areasEdgesWidth)
} else {
polygon.setStrokeWidth(0)
}
}
}
JappPreferences.AREAS_EDGES_WIDTH -> {
val edgesEnabled = JappPreferences.areasEdgesEnabled
for ((_, value) in areas) {
polygon = value
if (edgesEnabled) {
polygon.setStrokeWidth(JappPreferences.areasEdgesWidth)
}
}
}
JappPreferences.AREAS_COLOR -> {
val color = JappPreferences.areasColorEnabled
for ((key1, value) in areas) {
polygon = value
if (color) {
val alphaPercent = JappPreferences.areasColorAlpha
val alpha = (100 - alphaPercent).toFloat() / 100 * 255
polygon.setFillColor(Deelgebied.parse(key1)!!.alphaled(Math.round(alpha)))
} else {
polygon.setFillColor(Color.TRANSPARENT)
}
}
}
JappPreferences.AREAS_COLOR_ALPHA -> {
val areasColorEnabled = JappPreferences.areasColorEnabled
for ((key1, value) in areas) {
polygon = value
if (areasColorEnabled) {
val alphaPercent = JappPreferences.areasColorAlpha
val alpha = (100 - alphaPercent).toFloat() / 100 * 255
polygon.setFillColor(Deelgebied.parse(key1)!!.alphaled(Math.round(alpha)))
}
}
}
}
}
fun setupSpotButton(v: View): FloatingActionButton {
val spotButton = v.findViewById<FloatingActionButton>(R.id.fab_spot)
spotButton.setOnClickListener(object : View.OnClickListener {
var session: SightingSession? = null
override fun onClick(view: View) {
/*--- Hide the menu ---*/
val v = getView()
val menu = v!!.findViewById<FloatingActionMenu>(R.id.fab_menu)
menu.hideMenu(true)
/*--- Build a SightingSession and start it ---*/
session = SightingSession.Builder()
.setType(SightingSession.SIGHT_SPOT)
.setGoogleMap(jotiMap)
.setTargetView([email protected](R.id.container))
.setDialogContext([email protected])
.setOnSightingCompletedCallback(object:SightingSession.OnSightingCompletedCallback{
override fun onSightingCompleted(chosen: LatLng?, deelgebied: Deelgebied?, optionalInfo: String?) {
/*--- Show the menu ---*/
val menu = getView()!!.findViewById<FloatingActionMenu>(R.id.fab_menu)
menu.showMenu(true)
if (chosen != null) {
/*--- Construct a JSON string with the data ---*/
val builder = VosPostBody.default
builder.setIcon(SightingIcon.SPOT)
builder.setLatLng(chosen)
builder.setTeam(deelgebied?.name?.substring(0, 1)?:"x")
builder.setInfo(optionalInfo)
val api = Japp.getApi(VosApi::class.java)
api.post(builder).enqueue(object : Callback<Void> {
override fun onResponse(call: Call<Void>, response: Response<Void>) {
val snackbarView = [email protected]<View>(R.id.container)
when (response.code()) {
200 -> Snackbar.make(snackbarView, getString(R.string.sent_succesfull), Snackbar.LENGTH_LONG).show()
404 -> Snackbar.make(snackbarView, R.string.wrong_data, Snackbar.LENGTH_LONG).show()
else -> Snackbar.make(snackbarView, getString(R.string.problem_with_sending, Integer.toString(response.code())), Snackbar.LENGTH_LONG).show()
}
MapManager.instance.update()
}
override fun onFailure(call: Call<Void>, t: Throwable) {
t.sendWithAcra()
val snackbarView = [email protected]<View>(R.id.container)
Snackbar.make(snackbarView, getString(R.string.problem_with_sending, t.toString()), Snackbar.LENGTH_LONG).show()
}
})
}
session = null
}
})
.create()
session!!.start()
}
})
return spotButton
}
fun setupFollowButton(v: View): FloatingActionButton {
val followButton = v.findViewById<FloatingActionButton>(R.id.fab_follow)
followButton.setOnClickListener(object : View.OnClickListener {
var session: MovementManager.FollowSession? = null
override fun onClick(view: View) {
val v = getView()
val followButton = v!!.findViewById<FloatingActionButton>(R.id.fab_follow)
/*--- Hide the menu ---*/
val menu = v.findViewById<FloatingActionMenu>(R.id.fab_menu)
/**
* TODO: use color to identify follow state?
*/
if (session != null) {
// followButton.setColorNormal(Color.parseColor("#DA4336"));
followButton.labelText = getString(R.string.follow_me)
session!!.end()
session = null
} else {
menu.close(true)
//followButton.setColorNormal(Color.parseColor("#5cd65c"));
followButton.labelText = [email protected](R.string.stop_following)
session = movementManager!!.newSession(jotiMap!!,jotiMap!!.previousCameraPosition, JappPreferences.followZoom, JappPreferences.followAngleOfAttack)
}
}
})
return followButton
}
private fun setupPinButton(v: View): FloatingActionButton {
val pinButton = v.findViewById<FloatingActionButton>(R.id.fab_mark)
pinButton.setOnClickListener(object : View.OnClickListener {
var session: PinningSession? = null
override fun onClick(view: View) {
val v = getView()
val menu = v!!.findViewById<FloatingActionMenu>(R.id.fab_menu)
if (session != null) {
/*--- Show the menu ---*/
menu.showMenu(true)
session!!.end()
session = null
} else {
/*--- Hide the menu ---*/
menu.hideMenu(true)
session = PinningSession.Builder()
.setJotiMap(jotiMap)
.setCallback(object : PinningSession.OnPinningCompletedCallback{
override fun onPinningCompleted(pin: Pin?) {
if (pin != null) {
pinningManager.add(pin)
}
val menu = getView()!!.findViewById<FloatingActionMenu>(R.id.fab_menu)
menu.showMenu(true)
session!!.end()
session = null
}
})
.setTargetView([email protected](R.id.container))
.setDialogContext([email protected])
.create()
session!!.start()
}
}
})
return pinButton
}
private fun setupNavigationButton(v: View): FloatingActionButton {
val navigationButton = v.findViewById<FloatingActionButton>(R.id.fab_nav)
navigationButton.setOnClickListener(object : View.OnClickListener {
var session: NavigationSession? = null
override fun onClick(view: View) {
val v = getView()
val menu = v!!.findViewById<FloatingActionMenu>(R.id.fab_menu)
if (session != null) {
/*--- Show the menu ---*/
menu.showMenu(true)
session!!.end()
session = null
} else {
/*--- Hide the menu ---*/
menu.hideMenu(true)
session = NavigationSession.Builder()
.setJotiMap(jotiMap)
.setDialogContext(v.context)
.setTargetView(v)
.setCallback(object : NavigationSession.OnNavigationCompletedCallback {
override fun onNavigationCompleted(navigateTo: LatLng?, toNavigationPhone: Boolean) {
val menu = getView()!!.findViewById<FloatingActionMenu>(R.id.fab_menu)
menu.showMenu(true)
session!!.end()
session = null
if (navigateTo != null) {
if (!toNavigationPhone) {
try {
when (JappPreferences.navigationApp()) {
JappPreferences.NavigationApp.GoogleMaps -> {
val uristr = getString(R.string.google_uri, java.lang.Double.toString(navigateTo.latitude), java.lang.Double.toString(navigateTo.longitude))
val gmmIntentUri = Uri.parse(uristr)
val mapIntent = Intent(Intent.ACTION_VIEW, gmmIntentUri)
mapIntent.setPackage("com.google.android.apps.maps")
startActivity(mapIntent)
}
JappPreferences.NavigationApp.Waze -> {
val uri = getString(R.string.waze_uri, java.lang.Double.toString(navigateTo.latitude), java.lang.Double.toString(navigateTo.longitude))
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(uri)))
}
JappPreferences.NavigationApp.OSMAnd -> {
val osmuri = getString(R.string.osmand_uri, java.lang.Double.toString(navigateTo.latitude), java.lang.Double.toString(navigateTo.longitude))
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(osmuri)))
}
JappPreferences.NavigationApp.OSMAndWalk -> {
val osmuriwalk = getString(R.string.osmandwalk_uri, java.lang.Double.toString(navigateTo.latitude), java.lang.Double.toString(navigateTo.longitude))
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(osmuriwalk)))
}
JappPreferences.NavigationApp.Geo -> {
val geouri = getString(R.string.geo_uri, java.lang.Double.toString(navigateTo.latitude), java.lang.Double.toString(navigateTo.longitude))
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(geouri)))
}
}
} catch (e: ActivityNotFoundException) {
println(e.toString())
e.sendWithAcra()
val snackbarView = [email protected]<View>(R.id.container)
Snackbar.make(snackbarView,
getString(R.string.navigation_app_not_installed, JappPreferences.navigationApp().toString()),
Snackbar.LENGTH_LONG).show()
}
} else {
val id = JappPreferences.accountId
if (id >= 0) {
val autoApi = Japp.getApi(AutoApi::class.java)
autoApi.getInfoById(JappPreferences.accountKey, id).enqueue(object : Callback<AutoInzittendeInfo> {
override fun onResponse(call: Call<AutoInzittendeInfo>, response: Response<AutoInzittendeInfo>) {
if (response.code() == 200) {
val autoInfo = response.body()
if (autoInfo != null) {
val auto = autoInfo.autoEigenaar!!
AutoSocketHandler.location(Location(navigateTo, auto, JappPreferences.accountUsername))
}
}
if (response.code() == 404) {
val snackbarView = [email protected]<View>(R.id.container)
Snackbar.make(snackbarView, getString(R.string.fout_not_in_car), Snackbar.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<AutoInzittendeInfo>, t: Throwable) {
t.sendWithAcra()
}
})
}
}
}
}
}).create()
session?.start()
}
}
})
return navigationButton
}
private fun setupHuntButton(v: View): FloatingActionButton {
val huntButton = v.findViewById<FloatingActionButton>(R.id.fab_hunt)
huntButton.setOnClickListener(object : View.OnClickListener {
override fun onClick(view: View) {
val session: SightingSession
/*--- Hide the menu ---*/
val v = getView()
val menu = v!!.findViewById<FloatingActionMenu>(R.id.fab_menu)
menu.hideMenu(true)
/*--- Build a SightingSession and start it ---*/
session = SightingSession.Builder()
.setType(SightingSession.SIGHT_HUNT)
.setGoogleMap(jotiMap)
.setTargetView([email protected](R.id.container))
.setDialogContext([email protected])
.setOnSightingCompletedCallback(object: SightingSession.OnSightingCompletedCallback{
override fun onSightingCompleted(chosen: LatLng?, deelgebied: Deelgebied?, optionalInfo: String?) {
/*--- Show the menu ---*/
val menu = getView()!!.findViewById<FloatingActionMenu>(R.id.fab_menu)
menu.showMenu(true)
if (chosen != null) {
/*--- Construct a JSON string with the data ---*/
val builder = VosPostBody.default
builder.setIcon(SightingIcon.HUNT)
builder.setLatLng(chosen)
builder.setTeam(deelgebied?.name?.substring(0, 1)?:"x")
builder.setInfo(optionalInfo)
val api = Japp.getApi(VosApi::class.java)
api.post(builder).enqueue(object : Callback<Void> {
override fun onResponse(call: Call<Void>, response: Response<Void>) {
val snackbarView = [email protected]<View>(R.id.container)
when (response.code()) {
200 -> Snackbar.make(snackbarView, R.string.sent_succesfull, Snackbar.LENGTH_LONG).show()
404 -> Snackbar.make(snackbarView, getString(R.string.wrong_data), Snackbar.LENGTH_LONG).show()
else -> Snackbar.make(snackbarView, getString(R.string.problem_sending, Integer.toString(response.code())), Snackbar.LENGTH_LONG).show()
}
}
override fun onFailure(call: Call<Void>, t: Throwable) {
val snackbarView = [email protected]<View>(R.id.container)
Snackbar.make(snackbarView, getString(R.string.problem_sending, t.toString()), Snackbar.LENGTH_LONG).show()
t.sendWithAcra()
}
})
}
}
})
.create()
session.start()
}
})
return huntButton
}
companion object {
val TAG = "JappMapFragment"
private val BUNDLE_MAP = "BUNDLE_MAP"
private val BUNDLE_OSM_ACTIVE = "BUNDLE_OSM_ACTIVE_B"
private val OSM_ZOOM = "OSM_ZOOM"
private val OSM_LAT = "OSM_LAT"
private val OSM_LNG = "OSM_LNG"
private val OSM_OR = "OSM_OR"
private val OSM_BUNDLE = "OSM_BUNDLE"
val REQUEST_CHECK_SETTINGS = 32
}
}
| app/src/main/java/nl/rsdt/japp/application/fragments/JappMapFragment.kt | 3363422196 |
package com.devbrackets.android.exomedia.core.source.builder
import androidx.media3.common.MediaItem
import androidx.media3.exoplayer.hls.HlsMediaSource
import androidx.media3.exoplayer.source.MediaSource
class HlsMediaSourceBuilder : MediaSourceBuilder() {
override fun build(attributes: MediaSourceAttributes): MediaSource {
val dataSourceFactory = buildDataSourceFactory(attributes)
val mediaItem = MediaItem.Builder().setUri(attributes.uri).build()
return HlsMediaSource.Factory(dataSourceFactory)
.setDrmSessionManagerProvider(attributes.drmSessionManagerProvider)
.createMediaSource(mediaItem)
}
}
| library/src/main/kotlin/com/devbrackets/android/exomedia/core/source/builder/HlsMediaSourceBuilder.kt | 1416449420 |
package org.open.openstore.file.internal
import org.open.openstore.file.FilePlatform
import org.open.openstore.file.FileType
import org.open.openstore.file.IFileName
import org.open.openstore.file.NameScope
/**
* 默认的文件名实现
*/
abstract class AbstractFileName(private val scheme: String, private var absPath:String?, private var type:FileType): IFileName {
private var uri: String? = null
private var baseName: String? = null
private var rootUri: String? = null
private var extension: String? = null
private var decodedAbsPath: String? = null
private var key: String? = null
init {
absPath?.let {
if (it.isNotEmpty()) {
if (it.length > 1 && it.endsWith("/")) {
this.absPath = it.substring(0, it.length - 1)
} else {
this.absPath = it
}
} else {
this.absPath = IFileName.ROOT_PATH
}
}
}
override fun equals(o: Any?): Boolean {
if (this === o) {
return true
}
if (o == null || javaClass != o.javaClass) {
return false
}
val that = o as AbstractFileName?
return getKey() == that!!.getKey()
}
override fun hashCode(): Int {
return getKey().hashCode()
}
override operator fun compareTo(obj: IFileName): Int {
return getKey().compareTo((obj as AbstractFileName)?.getKey())
}
override fun toString(): String {
return getURI()
}
/**
* 创建名称实例的工厂模板方法
*/
abstract fun createName(absolutePath: String, fileType: FileType): IFileName
/**
* 为此文件名实例构建根URI的模板方法,root URI不以分隔符结尾
*/
protected abstract fun appendRootUri(buffer: StringBuilder, addPassword: Boolean)
override fun getBaseName(): String {
if (baseName == null) {
val idx = getPath().lastIndexOf(IFileName.SEPARATOR_CHAR)
if (idx == -1) {
baseName = getPath()
} else {
baseName = getPath().substring(idx + 1)
}
}
return baseName!!
}
override fun getPath(): String {
if (FilePlatform.URL_STYPE) {
return absPath + getUriTrailer()
}
return absPath!!
}
protected fun getUriTrailer(): String {
return if (getType().hasChildren()) "/" else ""
}
/**
* 获取编码后的path
*/
fun getPathDecoded(): String {
if (decodedAbsPath == null) {
decodedAbsPath = FilePlatform.UriParser.decode(getPath())
}
return decodedAbsPath!!
}
override fun getParent(): IFileName {
val parentPath: String
val idx = getPath().lastIndexOf(IFileName.SEPARATOR_CHAR)
if (idx == -1 || idx == getPath().length - 1) {
// No parent
return IFileName.NO_NAME
} else if (idx == 0) {
// Root is the parent
parentPath = IFileName.SEPARATOR
} else {
parentPath = getPath().substring(0, idx)
}
return createName(parentPath, FileType.FOLDER)
}
override fun getRoot(): IFileName {
var root: IFileName = this
while (root.getParent() != IFileName.NO_NAME) {
root = root.getParent()
}
return root
}
override fun getScheme(): String {
return scheme
}
override fun getURI(): String {
if (uri == null) {
uri = createURI()
}
return uri!!
}
protected fun createURI(): String {
return createURI(false, true)
}
private fun getKey(): String {
if (key == null) {
key = getURI()
}
return key!!
}
override fun getFriendlyURI(): String {
return createURI(false, false)
}
private fun createURI(useAbsolutePath: Boolean, usePassword: Boolean): String {
val buffer = StringBuilder()
appendRootUri(buffer, usePassword)
buffer.append(if (useAbsolutePath) absPath else getPath())
return buffer.toString()
}
/**
* 将指定文件名转换为相对此文件名的相对名称
*/
override fun getRelativeName(name: IFileName): String {
val path = name.getPath()
// Calculate the common prefix
val basePathLen = getPath().length
val pathLen = path.length
// Deal with root
if (basePathLen == 1 && pathLen == 1) {
return "."
} else if (basePathLen == 1) {
return path.substring(1)
}
val maxlen = Math.min(basePathLen, pathLen)
var pos = 0
while (pos < maxlen && getPath()[pos] == path.get(pos)) {
pos++
}
if (pos == basePathLen && pos == pathLen) {
// Same names
return "."
} else if (pos == basePathLen && pos < pathLen && path.get(pos) == IFileName.SEPARATOR_CHAR) {
// A descendent of the base path
return path.substring(pos + 1)
}
// Strip the common prefix off the path
val buffer = StringBuilder()
if (pathLen > 1 && (pos < pathLen || getPath()[pos] != IFileName.SEPARATOR_CHAR)) {
// Not a direct ancestor, need to back up
pos = getPath().lastIndexOf(IFileName.SEPARATOR_CHAR, pos)
buffer.append(path.substring(pos))
}
// Prepend a '../' for each element in the base path past the common
// prefix
buffer.insert(0, "..")
pos = getPath().indexOf(IFileName.SEPARATOR_CHAR, pos + 1)
while (pos != -1) {
buffer.insert(0, "../")
pos = getPath().indexOf(IFileName.SEPARATOR_CHAR, pos + 1)
}
return buffer.toString()
}
override fun getRootURI(): String {
if (rootUri == null) {
val buffer = StringBuilder()
appendRootUri(buffer, true)
buffer.append(IFileName.SEPARATOR_CHAR)
rootUri = buffer.toString().intern()
}
return rootUri!!
}
override fun getDepth(): Int {
val len = getPath().length
if (len == 0 || len == 1 && getPath()[0] == IFileName.SEPARATOR_CHAR) {
return 0
}
var depth = 1
var pos = 0
while (pos > -1 && pos < len) {
pos = getPath().indexOf(IFileName.SEPARATOR_CHAR, pos + 1)
depth++
}
return depth
}
override fun getExtension(): String {
if (extension == null) {
getBaseName()
val pos = baseName!!.lastIndexOf('.')
// if ((pos == -1) || (pos == baseName.length() - 1))
// [email protected]: Review of patch from [email protected]
// do not treat filenames like
// .bashrc c:\windows\.java c:\windows\.javaws c:\windows\.jedit c:\windows\.appletviewer
// as extension
if (pos < 1 || pos == baseName!!.length - 1) {
// No extension
extension = ""
} else {
extension = baseName!!.substring(pos + 1).intern()
}
}
return extension!!
}
override fun isAncestor(ancestor: IFileName): Boolean {
if (!ancestor.getRootURI().equals(getRootURI())) {
return false
}
return IFileName.checkName(ancestor.getPath(), getPath(), NameScope.DESCENDENT)
}
override fun isDescendent(descendent: IFileName, scope: NameScope): Boolean {
if (!descendent.getRootURI().equals(getRootURI())) {
return false
}
return IFileName.checkName(getPath(), descendent.getPath(), scope)
}
override fun isFile(): Boolean {
// Use equals instead of == to avoid any class loader worries.
return FileType.FILE.equals(this.getType())
}
override fun getType(): FileType {
return type
}
/**
* 文件名的状态可设置
*/
fun setType(type:FileType) {
if (type != FileType.FOLDER && type != FileType.FILE && type != FileType.FILE_OR_FOLDER && type != FileType.LINK) {
throw org.open.openstore.file.FileSystemException("filename-type.error")
}
this.type = type
}
} | src/main/kotlin/org/open/openstore/file/internal/AbstractFileName.kt | 2020456951 |
/*
* 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.compose.ui.test.junit4
import androidx.compose.ui.test.InternalTestApi
import androidx.test.espresso.Espresso
import androidx.test.espresso.IdlingRegistry
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import org.junit.After
import org.junit.Test
class EspressoLinkTest {
@OptIn(InternalTestApi::class, ExperimentalCoroutinesApi::class)
private val espressoLink = EspressoLink(
IdlingResourceRegistry(TestScope(UnconfinedTestDispatcher()))
)
@After
fun tearDown() {
// Unregister EspressoLink with public API in case our implementation
// that relies on deprecated API doesn't work anymore.
IdlingRegistry.getInstance().unregister(espressoLink)
// onIdle() should remove the espressoLink from all lists of idling resources
Espresso.onIdle()
}
/**
* Tests that EspressoLink registers and unregisters itself synchronously to both the public
* registry (IdlingRegistry) and the private registry (IdlingResourceRegistry). When the
* unregistration doesn't unregister itself synchronously anymore, we might have a memory
* leak (see b/202190483).
*
* Also see b/205550018 for context.
*/
@Test
fun registerAndUnregister() {
// Check the public registry:
assertThat(IdlingRegistry.getInstance().resources).hasSize(0)
// Check the private registry:
assertThat(@Suppress("DEPRECATION") Espresso.getIdlingResources()).hasSize(0)
espressoLink.withStrategy {
assertThat(IdlingRegistry.getInstance().resources)
.containsExactlyElementsIn(listOf(espressoLink))
assertThat(@Suppress("DEPRECATION") Espresso.getIdlingResources())
.containsExactlyElementsIn(listOf(espressoLink))
}
// Check if espressoLink is removed from both places:
assertThat(IdlingRegistry.getInstance().resources).hasSize(0)
assertThat(@Suppress("DEPRECATION") Espresso.getIdlingResources()).hasSize(0)
}
}
| compose/ui/ui-test-junit4/src/androidAndroidTest/kotlin/androidx/compose/ui/test/junit4/EspressoLinkTest.kt | 860572448 |
/*
* 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.camera.camera2.pipe.graph
import android.hardware.camera2.CaptureResult
import android.os.Build
import androidx.camera.camera2.pipe.FrameNumber
import androidx.camera.camera2.pipe.RequestNumber
import androidx.camera.camera2.pipe.testing.FakeFrameMetadata
import androidx.camera.camera2.pipe.testing.FakeRequestMetadata
import androidx.camera.camera2.pipe.testing.RobolectricCameraPipeTestRunner
import androidx.camera.camera2.pipe.testing.UpdateCounting3AStateListener
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
import org.robolectric.annotation.internal.DoNotInstrument
@RunWith(RobolectricCameraPipeTestRunner::class)
@DoNotInstrument
@Config(minSdk = Build.VERSION_CODES.LOLLIPOP)
internal class Listener3ATest {
@Test
fun testListenersInvoked() {
val result3AStateListener = Result3AStateListenerImpl(
mapOf(
CaptureResult.CONTROL_AF_MODE to listOf(CaptureResult.CONTROL_AF_MODE_AUTO)
)
)
val listener3A = Listener3A()
listener3A.addListener(result3AStateListener)
// The deferred result of 3a state listener shouldn't be complete right now.
assertThat(result3AStateListener.result.isCompleted).isFalse()
listener3A.onRequestSequenceCreated(
FakeRequestMetadata(requestNumber = RequestNumber(1))
)
val requestMetadata = FakeRequestMetadata(requestNumber = RequestNumber(1))
val frameNumber = FrameNumber(1L)
val captureResult = FakeFrameMetadata(
mapOf(
CaptureResult.CONTROL_AF_MODE to CaptureResult.CONTROL_AF_MODE_AUTO
)
)
// Once the correct metadata is updated the listener3A should broadcast it to the
// result3AState listener added to it, making the deferred result complete.
listener3A.onPartialCaptureResult(requestMetadata, frameNumber, captureResult)
assertThat(result3AStateListener.result.isCompleted).isTrue()
}
@Test
fun testListenersInvokedWithMultipleUpdates() {
val result3AStateListener = UpdateCounting3AStateListener(
Result3AStateListenerImpl(
mapOf(
CaptureResult.CONTROL_AF_MODE to listOf(CaptureResult.CONTROL_AF_MODE_AUTO)
)
)
)
val listener3A = Listener3A()
listener3A.addListener(result3AStateListener)
listener3A.onRequestSequenceCreated(
FakeRequestMetadata(requestNumber = RequestNumber(1))
)
val requestMetadata = FakeRequestMetadata(requestNumber = RequestNumber(1))
val captureResult = FakeFrameMetadata(
mapOf(
CaptureResult.CONTROL_AF_MODE to CaptureResult.CONTROL_AF_MODE_CONTINUOUS_PICTURE
)
)
val captureResult1 = FakeFrameMetadata(
mapOf(
CaptureResult.CONTROL_AF_MODE to CaptureResult.CONTROL_AF_MODE_CONTINUOUS_PICTURE
)
)
listener3A.onPartialCaptureResult(requestMetadata, FrameNumber(1), captureResult)
assertThat(result3AStateListener.updateCount).isEqualTo(1)
// Since the first update didn't have the right key and it's desired value, the second
// update should also be supplies to the result3AListener.
listener3A.onPartialCaptureResult(requestMetadata, FrameNumber(2), captureResult1)
assertThat(result3AStateListener.updateCount).isEqualTo(2)
}
@Test
fun testListenersAreRemovedWhenDone() {
val result3AStateListener1 = UpdateCounting3AStateListener(
Result3AStateListenerImpl(
mapOf(
CaptureResult.CONTROL_AF_MODE to listOf(CaptureResult.CONTROL_AF_MODE_AUTO)
)
)
)
val result3AStateListener2 = UpdateCounting3AStateListener(
Result3AStateListenerImpl(
mapOf(
CaptureResult.CONTROL_AE_MODE to listOf(CaptureResult.CONTROL_AE_MODE_OFF)
)
)
)
val listener3A = Listener3A()
listener3A.addListener(result3AStateListener1)
listener3A.addListener(result3AStateListener2)
val requestMetadata = FakeRequestMetadata(requestNumber = RequestNumber(1))
val frameNumber = FrameNumber(1L)
val captureResult = FakeFrameMetadata(
mapOf(
CaptureResult.CONTROL_AF_MODE to CaptureResult.CONTROL_AF_MODE_AUTO
)
)
// There should be no update to either of the listeners right now.
assertThat(result3AStateListener1.updateCount).isEqualTo(0)
assertThat(result3AStateListener2.updateCount).isEqualTo(0)
listener3A.onRequestSequenceCreated(
FakeRequestMetadata(requestNumber = RequestNumber(1))
)
// Once the metadata for correct AF mode is updated, the listener3A should broadcast it to
// the result3AState listeners added to it, making result3AStateListener1 complete.
listener3A.onPartialCaptureResult(requestMetadata, frameNumber, captureResult)
assertThat(result3AStateListener1.updateCount).isEqualTo(1)
assertThat(result3AStateListener2.updateCount).isEqualTo(1)
// Once the metadata for correct AE mode is updated, the listener3A should broadcast it to
// the result3AState listeners added to it, making result3AStateListener2 complete. Since
// result3AStateListener1 was already completed it will not be updated again.
val captureResult1 = FakeFrameMetadata(
mapOf(
CaptureResult.CONTROL_AF_MODE to CaptureResult.CONTROL_AF_MODE_AUTO,
CaptureResult.CONTROL_AE_MODE to CaptureResult.CONTROL_AE_MODE_OFF
)
)
listener3A.onPartialCaptureResult(requestMetadata, frameNumber, captureResult1)
assertThat(result3AStateListener1.updateCount).isEqualTo(1)
assertThat(result3AStateListener2.updateCount).isEqualTo(2)
// Since both result3AStateListener1 and result3AStateListener2 are complete, they will not
// receive further updates.
listener3A.onPartialCaptureResult(requestMetadata, frameNumber, captureResult1)
assertThat(result3AStateListener1.updateCount).isEqualTo(1)
assertThat(result3AStateListener2.updateCount).isEqualTo(2)
}
} | camera/camera-camera2-pipe/src/test/java/androidx/camera/camera2/pipe/graph/Listener3ATest.kt | 1180217026 |
/*
* Copyright (C) 2017 Juan Ramón González González (https://github.com/jrgonzalezg)
*
* 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.jrgonzalezg.openlibrary.app
import com.github.jrgonzalezg.openlibrary.IntegrationTests
import io.kotlintest.TestCaseContext
abstract class NetworkIntegrationTests : IntegrationTests() {
lateinit var networkComponent: IntegrationTestNetworkComponent
val networkInterceptor: (TestCaseContext, () -> Unit) -> Unit = { context, testCase ->
networkComponent = DaggerIntegrationTestNetworkComponent.builder().integrationTestNetworkModule(
IntegrationTestNetworkModule()).build()
testCase()
}
override val defaultTestCaseConfig = super.defaultTestCaseConfig.copy(
interceptors = super.defaultTestCaseConfig.interceptors + networkInterceptor)
}
| app/src/test/kotlin/com/github/jrgonzalezg/openlibrary/app/NetworkIntegrationTests.kt | 614646791 |
/*
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby
import io.jooby.Router.GET
import kotlin.coroutines.AbstractCoroutineContextElement
import kotlin.coroutines.CoroutineContext
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.coroutineScope
import org.junit.jupiter.api.Assertions.assertSame
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.mockito.ArgumentCaptor
import org.mockito.Mockito.RETURNS_DEEP_STUBS
import org.mockito.Mockito.eq
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
class CoroutineRouterTest {
private val router = mock(Router::class.java, RETURNS_DEEP_STUBS)
private val ctx = mock(Context::class.java)
@Test
fun withoutLaunchContext() {
CoroutineRouter(CoroutineStart.UNDISPATCHED, router).apply { get("/path") { "Result" } }
val handlerCaptor = ArgumentCaptor.forClass(Route.Handler::class.java)
verify(router).route(eq(GET), eq("/path"), handlerCaptor.capture())
handlerCaptor.value.apply(ctx)
verify(ctx).render("Result")
}
@Test
fun launchContext_isRunEveryTime() {
var coroutineRouteCalled = false
CoroutineRouter(CoroutineStart.UNDISPATCHED, router).apply {
launchContext { SampleCoroutineContext(ctx) }
get("/path") {
coroutineScope {
assertSame(ctx, coroutineContext[SampleCoroutineContext.Key]!!.ctx)
coroutineRouteCalled = true
}
}
}
val handlerCaptor = ArgumentCaptor.forClass(Route.Handler::class.java)
verify(router).route(eq(GET), eq("/path"), handlerCaptor.capture())
handlerCaptor.value.apply(ctx)
assertTrue(coroutineRouteCalled)
}
class SampleCoroutineContext(val ctx: Context) : AbstractCoroutineContextElement(Key) {
companion object Key : CoroutineContext.Key<SampleCoroutineContext>
}
}
| jooby/src/test/kotlin/io/jooby/CoroutineRouterTest.kt | 3110731238 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengl.templates
import org.lwjgl.generator.*
import org.lwjgl.opengl.*
val OVR_multiview = "OVRMultiview".nativeClassGL("OVR_multiview", postfix = OVR) {
documentation =
"""
Native bindings to the $registryLink extension.
The method of stereo rendering supported in OpenGL is currently achieved by rendering to the two eye buffers sequentially. This typically incurs double
the application and driver overhead, despite the fact that the command streams and render states are almost identical.
This extension seeks to address the inefficiency of sequential multiview rendering by adding a means to render to multiple elements of a 2D texture
array simultaneously. In multiview rendering, draw calls are instanced into each corresponding element of the texture array. The vertex program uses a
new ViewID variable to compute per-view values, typically the vertex position and view-dependent variables like reflection.
The formulation of this extension is high level in order to allow implementation freedom. On existing hardware, applications and drivers can realize
the benefits of a single scene traversal, even if all GPU work is fully duplicated per-view. But future support could enable simultaneous rendering via
multi-GPU, tile-based architectures could sort geometry into tiles for multiple views in a single pass, and the implementation could even choose to
interleave at the fragment level for better texture cache utilization and more coherent fragment shader branching.
The most obvious use case in this model is to support two simultaneous views: one view for each eye. However, we also anticipate a usage where two
views are rendered per eye, where one has a wide field of view and the other has a narrow one. The nature of wide field of view planar projection is
that the sample density can become unacceptably low in the view direction. By rendering two inset eye views per eye, we can get the required sample
density in the center of projection without wasting samples, memory, and time by oversampling in the periphery.
Requires ${GL30.core}.
"""
IntConstant(
"Accepted by the {@code pname} parameter of GetFramebufferAttachmentParameteriv.",
"FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR"..0x9630,
"FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR"..0x9632
)
IntConstant(
"Accepted by the {@code pname} parameter of GetIntegerv.",
"MAX_VIEWS_OVR"..0x9631
)
IntConstant(
"Returned by CheckFramebufferStatus.",
"FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR"..0x9633
)
val FramebufferTextureLayer = GL30["FramebufferTextureLayer"]
void(
"FramebufferTextureMultiviewOVR",
"""
Operates similarly to GL30#FramebufferTextureLayer(), except that {@code baseViewIndex} and {@code numViews} selects a range of texture array elements
that will be targeted when rendering.
The command
${codeBlock("""
View( uint id );""")}
does not exist in the GL, but is used here to describe the multi-view functionality in this section. The effect of this hypothetical function is to set
the value of the shader built-in input uint {@code gl_ViewID_OVR}.
When multi-view rendering is enabled, drawing commands have the same effect as:
${codeBlock("""
for( int i = 0; i < numViews; i++ ) {
FramebufferTextureLayer( target, attachment, texture, level, baseViewIndex + i );
View( i );
<drawing-command>
}""")}
The result is that every drawing command is broadcast into every active view. The shader uses {@code gl_ViewID_OVR} to compute view dependent outputs.
The number of views, as specified by {@code numViews}, must be the same for all framebuffer attachments points where the value of
GL30#FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE is not GL11#NONE or the framebuffer is incomplete.
In this mode there are several restrictions:
${ul(
"in vertex shader {@code gl_Position} is the only output that can depend on {@code ViewID}",
"no transform feedback",
"no tessellation control or evaluation shaders",
"no geometry shader",
"no timer query",
"occlusion query results must be between max and sum of per-view queries, inclusive"
)}
<h5>Errors</h5>
$INVALID_OPERATION is generated by FramebufferTextureMultiviewOVR if target is GL30#READ_FRAMEBUFFER.
$INVALID_VALUE is generated by FramebufferTextureMultiviewOVR if {@code numViews} is less than 1, if {@code numViews} is more than #MAX_VIEWS_OVR or if
${code("(baseViewIndex + numViews)")} exceeds GL30#MAX_ARRAY_TEXTURE_LAYERS.
$INVALID_OPERATION is generated if a rendering command is issued and the number of views in the current draw framebuffer is not equal to the number
of views declared in the currently bound program.
""",
FramebufferTextureLayer["target"],
FramebufferTextureLayer["attachment"],
FramebufferTextureLayer["texture"],
FramebufferTextureLayer["level"],
GLint.IN("baseViewIndex", "the base framebuffer texture layer index"),
GLsizei.IN("numViews", "the number of views to target when rendering")
)
}
| modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/OVR_multiview.kt | 3480298742 |
import org.json.simple.parser.ContentHandler
import java.util.Stack
enum class ContainerType {
ObjectContainer, ArrayContainer
}
enum class ValueType {
TrueValue, FalseValue, NullValue, StringValue, NumberValue
}
interface PassJSONValue {
fun passJSONValue(path: String, valtype: ValueType, strval: String) : Boolean
}
class JSONReader(val cb: PassJSONValue): ContentHandler {
val ctx = Stack<Triple<ContainerType,Long,String>>()
fun pushResult(t: ValueType, e: String): Boolean {
cb.passJSONValue(getPath(), t, e)
return true;
}
fun getPath() : String {
val paths = arrayListOf<String>()
for (c in ctx) {
val p = when(c.first) {
ContainerType.ObjectContainer -> c.third
ContainerType.ArrayContainer -> (c.second-1).toString()
}
paths.add(p)
}
return paths.joinToString(".")
}
fun incStack() {
if (!ctx.isEmpty()) {
val (t, i, k) = ctx.pop()
val ni = when(t) {
ContainerType.ArrayContainer -> i + 1
ContainerType.ObjectContainer -> i
}
ctx.push(Triple(t,ni,k))
}
}
override fun startObject() : Boolean {
incStack()
ctx.push(Triple(ContainerType.ObjectContainer, 0, ""))
return true;
}
override fun startObjectEntry(name: String) : Boolean {
val (t, i, k) = ctx.pop()
ctx.push(Triple(t,i,name))
return true;
}
override fun endObject() : Boolean {
ctx.pop()
return true;
}
override fun startArray() : Boolean {
incStack()
ctx.push(Triple(ContainerType.ArrayContainer, 0, ""))
return true;
}
override fun endArray() : Boolean {
ctx.pop()
return true;
}
override fun primitive(value: Any?) : Boolean {
incStack()
val (valtype, strval) = when(value) {
is String -> Pair(ValueType.StringValue, value)
is Number -> Pair(ValueType.NumberValue, value.toString())
is Boolean -> Pair(if (value) ValueType.TrueValue else ValueType.FalseValue, value.toString())
null -> Pair(ValueType.NullValue, "null")
else -> {
throw Exception("Unknown type of value ${value.toString()}")
}
}
return pushResult(valtype, strval)
}
override fun endJSON() { }
override fun startJSON() { }
override fun endObjectEntry() : Boolean { return true; }
}
| JSONReader.kt | 2934858975 |
package nerd.tuxmobil.fahrplan.congress.dataconverters
import info.metadude.android.eventfahrplan.network.fetching.HttpStatus as NetworkHttpStatus
import nerd.tuxmobil.fahrplan.congress.net.HttpStatus as AppHttpStatus
fun NetworkHttpStatus.toAppHttpStatus() = when (this) {
NetworkHttpStatus.HTTP_OK -> AppHttpStatus.HTTP_OK
NetworkHttpStatus.HTTP_LOGIN_FAIL_UNTRUSTED_CERTIFICATE -> AppHttpStatus.HTTP_LOGIN_FAIL_UNTRUSTED_CERTIFICATE
NetworkHttpStatus.HTTP_DNS_FAILURE -> AppHttpStatus.HTTP_DNS_FAILURE
NetworkHttpStatus.HTTP_COULD_NOT_CONNECT -> AppHttpStatus.HTTP_COULD_NOT_CONNECT
NetworkHttpStatus.HTTP_SSL_SETUP_FAILURE -> AppHttpStatus.HTTP_SSL_SETUP_FAILURE
NetworkHttpStatus.HTTP_CANNOT_PARSE_CONTENT -> AppHttpStatus.HTTP_CANNOT_PARSE_CONTENT
NetworkHttpStatus.HTTP_WRONG_HTTP_CREDENTIALS -> AppHttpStatus.HTTP_WRONG_HTTP_CREDENTIALS
NetworkHttpStatus.HTTP_CONNECT_TIMEOUT -> AppHttpStatus.HTTP_CONNECT_TIMEOUT
NetworkHttpStatus.HTTP_NOT_MODIFIED -> AppHttpStatus.HTTP_NOT_MODIFIED
NetworkHttpStatus.HTTP_NOT_FOUND -> AppHttpStatus.HTTP_NOT_FOUND
NetworkHttpStatus.HTTP_CLEARTEXT_NOT_PERMITTED -> AppHttpStatus.HTTP_CLEARTEXT_NOT_PERMITTED
}
| app/src/main/java/nerd/tuxmobil/fahrplan/congress/dataconverters/HttpStatusExtensions.kt | 47569718 |
/*
* Copyright (c) 2015 Mark Platvoet<[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 example.default
import nl.komponents.progress.OutOfRangeException
import nl.komponents.progress.Progress
import java.text.DecimalFormat
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
fun main(args: Array<String>) {
val masterControl = Progress.containerControl()
masterControl.progress.update {
println("${value.percentage}%")
}
val firstChild = masterControl.child(0.1)
val secondChild = masterControl.containerChild(5.0)
val secondChildFirstChild = secondChild.child()
val secondChildSecondChild = secondChild.child()
val thirdChild = masterControl.child()
val fourthChild = masterControl.child(2.0)
firstChild.value = 0.25
firstChild.value = 0.50
firstChild.value = 0.75
firstChild.value = 1.0
secondChildFirstChild.markAsDone()
secondChildSecondChild.value = 0.5
secondChildSecondChild.value = 1.0
thirdChild.value = 0.25
thirdChild.value = 0.50
thirdChild.value = 0.75
thirdChild.value = 1.0
fourthChild.value = 0.25
fourthChild.value = 0.50
fourthChild.value = 0.75
fourthChild.value = 1.0
}
private val percentageFormat by ThreadLocalVal { DecimalFormat("##0.00") }
val Double.percentage: String
get() = if (this in (0.0..1.0)) percentageFormat.format(this * 100) else throw OutOfRangeException("[$this] must be within bounds (0.0 .. 1.0)")
private class ThreadLocalVal<T>(private val initializer: () -> T) : ReadOnlyProperty<Any?, T> {
private val threadLocal = object : ThreadLocal<T>() {
override fun initialValue(): T = initializer()
}
public override fun getValue(thisRef: Any?, property: KProperty<*>): T = threadLocal.get()
}
| projects/core/src/test/kotlin/example/default.kt | 982391681 |
package ru.fantlab.android.ui.modules.main
import androidx.fragment.app.FragmentManager
import it.sephiroth.android.library.bottomnavigation.BottomNavigation
import ru.fantlab.android.ui.base.mvp.BaseMvp
interface MainMvp {
enum class NavigationType {
NEWS,
NEWFICTION,
RESPONSES
}
interface View : BaseMvp.View {
fun onNavigationChanged(navType: NavigationType)
}
interface Presenter : BaseMvp.Presenter, BottomNavigation.OnMenuItemSelectionListener {
fun onModuleChanged(fragmentManager: FragmentManager, type: NavigationType)
}
} | app/src/main/kotlin/ru/fantlab/android/ui/modules/main/MainMvp.kt | 4185687865 |
/**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package com.mycollab.module.project.domain.criteria
import com.mycollab.db.arguments.DateSearchField
import com.mycollab.db.arguments.SearchCriteria
import com.mycollab.db.arguments.SetSearchField
import com.mycollab.db.arguments.StringSearchField
/**
* @author MyCollab Ltd.
* @since 1.0
*/
class StandupReportSearchCriteria : SearchCriteria() {
var projectIds: SetSearchField<Int>? = null
var logBy: StringSearchField? = null
var onDate: DateSearchField? = null
}
| mycollab-services/src/main/java/com/mycollab/module/project/domain/criteria/StandupReportSearchCriteria.kt | 2860269476 |
/*
* Copyright (c) 2017. tangzx([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.
*/
package com.tang.intellij.lua.editor.completion
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.icons.AllIcons
import com.intellij.lang.findUsages.LanguageFindUsages
import com.intellij.patterns.PatternCondition
import com.intellij.patterns.PlatformPatterns.psiElement
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNamedElement
import com.intellij.psi.tree.TokenSet
import com.intellij.util.ProcessingContext
import com.tang.intellij.lua.comment.LuaCommentUtil
import com.tang.intellij.lua.lang.LuaIcons
import com.tang.intellij.lua.lang.LuaLanguage
import com.tang.intellij.lua.project.LuaSettings
import com.tang.intellij.lua.psi.*
import com.tang.intellij.lua.refactoring.LuaRefactoringUtil
/**
* Created by tangzx on 2016/11/27.
*/
class LuaCompletionContributor : CompletionContributor() {
private var suggestWords = true
init {
//可以override
extend(CompletionType.BASIC, SHOW_OVERRIDE, OverrideCompletionProvider())
extend(CompletionType.BASIC, IN_CLASS_METHOD, SuggestSelfMemberProvider())
//提示属性, 提示方法
extend(CompletionType.BASIC, SHOW_CLASS_FIELD, ClassMemberCompletionProvider())
extend(CompletionType.BASIC, SHOW_REQUIRE_PATH, RequirePathCompletionProvider())
extend(CompletionType.BASIC, LuaStringArgHistoryProvider.STRING_ARG, LuaStringArgHistoryProvider())
//提示全局函数,local变量,local函数
extend(CompletionType.BASIC, IN_NAME_EXPR, LocalAndGlobalCompletionProvider(LocalAndGlobalCompletionProvider.ALL))
extend(CompletionType.BASIC, IN_CLASS_METHOD_NAME, LocalAndGlobalCompletionProvider(LocalAndGlobalCompletionProvider.VARS))
extend(CompletionType.BASIC, GOTO, object : CompletionProvider<CompletionParameters>(){
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, resultSet: CompletionResultSet) {
LuaPsiTreeUtil.walkUpLabel(parameters.position) {
val name = it.name
if (name != null) {
resultSet.addElement(LookupElementBuilder.create(name).withIcon(AllIcons.Actions.Rollback))
}
return@walkUpLabel true
}
resultSet.stopHere()
}
})
extend(CompletionType.BASIC, psiElement(LuaTypes.ID).withParent(LuaNameDef::class.java), SuggestLocalNameProvider())
extend(CompletionType.BASIC, IN_TABLE_FIELD, TableCompletionProvider())
extend(CompletionType.BASIC, ATTRIBUTE, AttributeCompletionProvider())
}
override fun fillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) {
val session = CompletionSession(parameters, result)
parameters.editor.putUserData(CompletionSession.KEY, session)
super.fillCompletionVariants(parameters, result)
if (LuaSettings.instance.isShowWordsInFile && suggestWords && session.isSuggestWords && !result.isStopped) {
suggestWordsInFile(parameters)
}
}
override fun beforeCompletion(context: CompletionInitializationContext) {
suggestWords = true
val file = context.file
if (file is LuaPsiFile) {
val element = file.findElementAt(context.caret.offset - 1)
if (element != null) {
if (element.parent is LuaLabelStat) {
suggestWords = false
context.dummyIdentifier = ""
} else if (!LuaCommentUtil.isComment(element)) {
val type = element.node.elementType
if (type in IGNORE_SET) {
suggestWords = false
context.dummyIdentifier = ""
}
}
}
}
}
companion object {
private val IGNORE_SET = TokenSet.create(LuaTypes.STRING, LuaTypes.NUMBER, LuaTypes.CONCAT)
private val SHOW_CLASS_FIELD = psiElement(LuaTypes.ID)
.withParent(LuaIndexExpr::class.java)
private val IN_FUNC_NAME = psiElement(LuaTypes.ID)
.withParent(LuaIndexExpr::class.java)
.inside(LuaClassMethodName::class.java)
private val AFTER_FUNCTION = psiElement()
.afterLeaf(psiElement(LuaTypes.FUNCTION))
private val IN_CLASS_METHOD_NAME = psiElement().andOr(IN_FUNC_NAME, AFTER_FUNCTION)
private val IN_NAME_EXPR = psiElement(LuaTypes.ID)
.withParent(LuaNameExpr::class.java)
private val SHOW_OVERRIDE = psiElement()
.withParent(LuaClassMethodName::class.java)
private val IN_CLASS_METHOD = psiElement(LuaTypes.ID)
.withParent(LuaNameExpr::class.java)
.inside(LuaClassMethodDef::class.java)
private val SHOW_REQUIRE_PATH = psiElement(LuaTypes.STRING)
.withParent(
psiElement(LuaTypes.LITERAL_EXPR).withParent(
psiElement(LuaArgs::class.java).afterSibling(
psiElement().with(RequireLikePatternCondition())
)
)
)
private val GOTO = psiElement(LuaTypes.ID).withParent(LuaGotoStat::class.java)
private val IN_TABLE_FIELD = psiElement().andOr(
psiElement().withParent(
psiElement(LuaTypes.NAME_EXPR).withParent(LuaTableField::class.java)
),
psiElement(LuaTypes.ID).withParent(LuaTableField::class.java)
)
private val ATTRIBUTE = psiElement(LuaTypes.ID).withParent(LuaAttribute::class.java)
private fun suggestWordsInFile(parameters: CompletionParameters) {
val session = CompletionSession[parameters]
val originalPosition = parameters.originalPosition
if (originalPosition != null)
session.addWord(originalPosition.text)
val wordsScanner = LanguageFindUsages.INSTANCE.forLanguage(LuaLanguage.INSTANCE).wordsScanner
wordsScanner?.processWords(parameters.editor.document.charsSequence) {
val word = it.baseText.subSequence(it.start, it.end).toString()
if (word.length > 2 && LuaRefactoringUtil.isLuaIdentifier(word) && session.addWord(word)) {
session.resultSet.addElement(PrioritizedLookupElement.withPriority(LookupElementBuilder
.create(word)
.withIcon(LuaIcons.WORD), -1.0)
)
}
true
}
}
}
}
class RequireLikePatternCondition : PatternCondition<PsiElement>("requireLike"){
override fun accepts(psi: PsiElement, context: ProcessingContext?): Boolean {
val name = (psi as? PsiNamedElement)?.name
return if (name != null) LuaSettings.isRequireLikeFunctionName(name) else false
}
} | src/main/java/com/tang/intellij/lua/editor/completion/LuaCompletionContributor.kt | 3667353945 |
package com.commonsense.android.kotlin.prebuilt.baseClasses
import org.junit.*
/**
*
*/
class BaseApplicationTest {
@Ignore
@Test
fun onApplicationResumed() {
}
@Ignore
@Test
fun onApplicationPaused() {
}
@Ignore
@Test
fun onCreate() {
}
@Ignore
@Test
fun shouldBailOnCreate() {
}
@Ignore
@Test
fun isDebugMode() {
}
@Ignore
@Test
fun afterOnCreate() {
}
@Ignore
@Test
fun onStrictModeViolation() {
}
@Ignore
@Test
fun shouldDieOnStrictModeViolation() {
}
} | prebuilt/src/test/kotlin/com/commonsense/android/kotlin/prebuilt/baseClasses/BaseApplicationTest.kt | 2445927588 |
// Author: Konrad Jamrozik, github.com/konrad-jamrozik
package com.konradjamrozik
import com.google.common.collect.ArrayListMultimap
import com.google.common.collect.LinkedListMultimap
/**
* @return
* Map of counts of how many times given elements appears in this receiver [Iterable].
*/
val <T> Iterable<T>.frequencies: Map<T, Int> get() {
val grouped: Map<T, List<T>> = this.groupBy { it }
val frequencies: Map<T, Int> = grouped.mapValues { it.value.size }
return frequencies
}
/**
* @return
* A map from unique items to the index of first element in the receiver [Iterable] from which given unique item was
* obtained. The indexing starts at 0.
*
* @param extractItems
* A function that is applied to each element of the receiver iterable, converting it to an iterable of items.
*
* @param extractUniqueString
* A function used to remove duplicates from all the items extracted from receiver iterable using [extractItems].
*
*/
fun <T, TItem> Iterable<T>.uniqueItemsWithFirstOccurrenceIndex(
extractItems: (T) -> Iterable<TItem>,
extractUniqueString: (TItem) -> String
): Map<TItem, Int> {
return this.foldIndexed(
mapOf<String, Pair<TItem, Int>>(), { index, accumulatedMap, elem ->
val uniqueStringsToItemsWithIndexes: Map<String, Pair<TItem, Int>> =
extractItems(elem).associate {
Pair(
extractUniqueString(it),
Pair(it, index + 1)
)
}
val newUniqueStrings = uniqueStringsToItemsWithIndexes.keys.subtract(accumulatedMap.keys)
val uniqueStringsToNewItemsWithIndexes = uniqueStringsToItemsWithIndexes.filterKeys { it in newUniqueStrings }
accumulatedMap.plus(uniqueStringsToNewItemsWithIndexes)
}).map { it.value }.toMap()
}
inline fun <T, K, V> Iterable<T>.associateMany(transform: (T) -> Pair<K, V>): Map<K, Iterable<V>> {
val multimap = ArrayListMultimap.create<K, V>()
this.forEach { val pair = transform(it); multimap.put(pair.first, pair.second) }
return multimap.asMap()
}
fun <K, V> Iterable<Map<K, Iterable<V>>>.flatten(): Map<K, Iterable<V>> {
val multimap = LinkedListMultimap.create<K, V>()
this.forEach { map ->
map.forEach { multimap.putAll(it.key, it.value) }
}
return multimap.asMap()
} | src/main/kotlin/com/konradjamrozik/IterableExtensions.kt | 2595679968 |
package eu.kanade.tachiyomi.extension.en.mangaeffect
import eu.kanade.tachiyomi.multisrc.madara.Madara
import java.text.SimpleDateFormat
import java.util.Locale
class MangaEffect : Madara("MangaEffect", "https://mangaeffect.com", "en", SimpleDateFormat("dd.MM.yyyy", Locale.US))
| multisrc/overrides/madara/mangaeffect/src/MangaEffect.kt | 3365328877 |
/**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.ads.dto
import com.google.gson.annotations.SerializedName
import kotlin.String
import kotlin.collections.List
/**
* @param paragraphs
* @param title - Comment
*/
data class AdsRules(
@SerializedName("paragraphs")
val paragraphs: List<AdsParagraphs>? = null,
@SerializedName("title")
val title: String? = null
)
| api/src/main/java/com/vk/sdk/api/ads/dto/AdsRules.kt | 407935289 |
package com.yichiuan.moedict
import android.app.Application
import android.content.Context
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class AppModule(private val application: Application) {
@Provides
@Singleton
fun provideAppContext(): Context = application
}
| moedict-android/app/src/main/java/com/yichiuan/moedict/AppModule.kt | 3584500493 |
package org.jetbrains.haskell.vfs
import java.io.File
import java.io.BufferedInputStream
import java.io.InputStream
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
import java.io.FileInputStream
import java.util.ArrayList
/**
* Created by atsky on 12/12/14.
*/
class TarGzArchive(val file : File) {
val filesList : List<String>
init {
val bin = BufferedInputStream(FileInputStream(file))
val gzIn = GzipCompressorInputStream(bin);
val tarArchiveInputStream = TarArchiveInputStream(gzIn)
var file = ArrayList<String>()
while (true) {
val entry = tarArchiveInputStream.getNextTarEntry();
if (entry == null) {
break
}
file.add(entry.getName())
}
filesList = file;
bin.close()
}
} | plugin/src/org/jetbrains/haskell/vfs/TarGzArchive.kt | 862437981 |
package com.intfocus.template.ui.view
import android.app.Activity
import android.graphics.drawable.BitmapDrawable
import android.support.v4.content.ContextCompat
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.TextView
import com.intfocus.template.R
/**
* Created by CANC on 2017/8/1.
*/
class CommonPopupWindow : PopupWindow() {
lateinit var conentView: View
lateinit var tvBtn1: TextView
lateinit var tvBtn2: TextView
lateinit var minePop: PopupWindow
/**
*
*/
fun showPopupWindow(activity: Activity, str1: String, colorId1: Int, str2: String, colorId2: Int, lisenter: ButtonLisenter) {
val inflater = LayoutInflater.from(activity)
conentView = inflater.inflate(R.layout.popup_common, null)
tvBtn1 = conentView.findViewById(R.id.tv_btn1)
tvBtn2 = conentView.findViewById(R.id.tv_btn2)
tvBtn1.text = str1
tvBtn2.text = str2
tvBtn1.setTextColor(ContextCompat.getColor(activity, colorId1))
tvBtn2.setTextColor(ContextCompat.getColor(activity, colorId2))
//
tvBtn1.setOnClickListener {
lisenter.btn1Click()
minePop.dismiss()
}
tvBtn2.setOnClickListener {
lisenter.btn2Click()
minePop.dismiss()
}
minePop = PopupWindow(conentView,
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT)
minePop.isFocusable = true// 取得焦点
//注意 要是点击外部空白处弹框消息 那么必须给弹框设置一个背景色 不然是不起作用的
minePop.setBackgroundDrawable(BitmapDrawable())
val params = activity.window.attributes
params.alpha = 0.7f
activity.window.attributes = params
//点击外部消失
minePop.isOutsideTouchable = true
//设置可以点击
minePop.isTouchable = true
//进入退出的动画
minePop.animationStyle = R.style.anim_popup_bottombar
minePop.showAtLocation(conentView, Gravity.BOTTOM, 0, 0)
minePop.setOnDismissListener {
val paramsa = activity.window.attributes
paramsa.alpha = 1f
activity.window.attributes = paramsa
}
}
interface ButtonLisenter {
fun btn1Click()
fun btn2Click()
}
}
| app/src/main/java/com/intfocus/template/ui/view/CommonPopupWindow.kt | 1252277281 |
/*
* Copyright 2020 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.example.biometricloginsample
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.biometric.BiometricPrompt
import androidx.core.content.ContextCompat
// Since we are using the same methods in more than one Activity, better give them their own file.
object BiometricPromptUtils {
private const val TAG = "BiometricPromptUtils"
fun createBiometricPrompt(
activity: AppCompatActivity,
processSuccess: (BiometricPrompt.AuthenticationResult) -> Unit
): BiometricPrompt {
val executor = ContextCompat.getMainExecutor(activity)
val callback = object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationError(errCode: Int, errString: CharSequence) {
super.onAuthenticationError(errCode, errString)
Log.d(TAG, "errCode is $errCode and errString is: $errString")
}
override fun onAuthenticationFailed() {
super.onAuthenticationFailed()
Log.d(TAG, "User biometric rejected.")
}
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
super.onAuthenticationSucceeded(result)
Log.d(TAG, "Authentication was successful")
processSuccess(result)
}
}
return BiometricPrompt(activity, executor, callback)
}
fun createPromptInfo(activity: AppCompatActivity): BiometricPrompt.PromptInfo =
BiometricPrompt.PromptInfo.Builder().apply {
setTitle(activity.getString(R.string.prompt_info_title))
setSubtitle(activity.getString(R.string.prompt_info_subtitle))
setDescription(activity.getString(R.string.prompt_info_description))
setConfirmationRequired(false)
setNegativeButtonText(activity.getString(R.string.prompt_info_use_app_password))
}.build()
} | codelab-02/app/src/main/java/com/example/biometricloginsample/BiometricPromptUtils.kt | 1301256412 |
/*
* Copyright (C) 2017 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xpath.psi.impl.full.text
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import uk.co.reecedunn.intellij.plugin.xpath.ast.full.text.FTRange
class FTRangePsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), FTRange | src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/psi/impl/full/text/FTRangePsiImpl.kt | 2059085353 |
package org.stepik.android.domain.purchase_notification.interactor
import io.reactivex.Completable
import org.stepic.droid.util.AppConstants
import org.stepic.droid.util.DateTimeHelper
import org.stepik.android.data.purchase_notification.model.PurchaseNotificationScheduled
import org.stepik.android.domain.purchase_notification.repository.PurchaseNotificationRepository
import org.stepik.android.view.purchase_notification.notification.PurchaseNotificationDelegate
import java.util.Calendar
import javax.inject.Inject
class PurchaseReminderInteractor
@Inject
constructor(
private val purchaseNotificationDelegate: PurchaseNotificationDelegate,
private val purchaseNotificationRepository: PurchaseNotificationRepository
) {
companion object {
private const val MILLIS_IN_1_HOUR = 3600000L
}
fun savePurchaseNotificationSchedule(courseId: Long): Completable =
purchaseNotificationRepository
.getClosestTimeStamp()
.flatMapCompletable { timeStamp ->
val baseTime = if (timeStamp > DateTimeHelper.nowUtc()) {
timeStamp
} else {
DateTimeHelper.nowUtc()
}
purchaseNotificationRepository.savePurchaseNotificationSchedule(
PurchaseNotificationScheduled(courseId, calculateScheduleOffset(baseTime))
)
}
.doOnComplete { purchaseNotificationDelegate.schedulePurchaseNotification() }
private fun calculateScheduleOffset(timeStamp: Long): Long {
val scheduledTime = timeStamp + MILLIS_IN_1_HOUR
val calendar = Calendar.getInstance()
calendar.timeInMillis = scheduledTime
val scheduledHour = calendar.get(Calendar.HOUR_OF_DAY)
calendar.set(Calendar.HOUR_OF_DAY, 12)
calendar.set(Calendar.MINUTE, 0)
calendar.set(Calendar.MILLISECOND, 0)
val nowAt12 = calendar.timeInMillis
return when {
scheduledHour < 12 ->
nowAt12
scheduledHour >= 21 ->
nowAt12 + AppConstants.MILLIS_IN_24HOURS
else ->
scheduledTime
}
}
} | app/src/main/java/org/stepik/android/domain/purchase_notification/interactor/PurchaseReminderInteractor.kt | 2246371175 |
package org.stepik.android.domain.personal_deadlines.resolver
import io.reactivex.Single
import org.stepic.droid.util.AppConstants
import ru.nobird.android.core.model.mapToLongArray
import org.stepik.android.domain.course.repository.CourseRepository
import org.stepik.android.domain.lesson.repository.LessonRepository
import org.stepik.android.domain.personal_deadlines.model.Deadline
import org.stepik.android.domain.personal_deadlines.model.DeadlinesWrapper
import org.stepik.android.domain.personal_deadlines.model.LearningRate
import org.stepik.android.domain.section.repository.SectionRepository
import org.stepik.android.domain.unit.repository.UnitRepository
import org.stepik.android.model.Lesson
import org.stepik.android.model.Section
import org.stepik.android.model.Unit
import java.util.Calendar
import java.util.Date
import javax.inject.Inject
class DeadlinesResolverImpl
@Inject
constructor(
private val courseRepository: CourseRepository,
private val sectionRepository: SectionRepository,
private val unitRepository: UnitRepository,
private val lessonRepository: LessonRepository
) : DeadlinesResolver {
companion object {
private const val DEFAULT_STEP_LENGTH_IN_SECONDS = 60L
private const val TIME_MULTIPLIER = 1.3
}
override fun calculateDeadlinesForCourse(courseId: Long, learningRate: LearningRate): Single<DeadlinesWrapper> =
courseRepository.getCourse(courseId)
.flatMapSingle { course ->
sectionRepository.getSections(course.sections ?: listOf())
}
.flatMap { sections ->
val unitIds = sections
.flatMap(Section::units)
.fold(listOf(), List<Long>::plus)
unitRepository
.getUnits(unitIds)
.map { units -> sections to units }
}
.flatMap { (sections, units) ->
val lessonIds = units.mapToLongArray(Unit::lesson)
lessonRepository
.getLessons(*lessonIds)
.map { lessons ->
sections.map { section ->
getTimeToCompleteForSection(section, units, lessons)
}
}
}
.map {
val offset = Calendar.getInstance()
offset.add(Calendar.HOUR_OF_DAY, 24)
offset.set(Calendar.HOUR_OF_DAY, 0)
offset.set(Calendar.MINUTE, 0)
val deadlines = it.map { (sectionId, timeToComplete) ->
val deadlineDate = getDeadlineDate(offset, timeToComplete, learningRate)
Deadline(sectionId, deadlineDate)
}
DeadlinesWrapper(courseId, deadlines)
}
private fun getTimeToCompleteForSection(section: Section, units: List<Unit>, lessons: List<Lesson>): Pair<Long, Long> =
section
.units
.fold(0L) { acc, unitId ->
val unit = units.find { it.id == unitId }
val timeToComplete: Long = lessons
.find { it.id == unit?.lesson }
?.let { lesson ->
lesson
.timeToComplete
.takeIf { it != 0L }
?: lesson.steps.size * DEFAULT_STEP_LENGTH_IN_SECONDS
}
?: 0L
acc + timeToComplete
}
.let {
section.id to it
}
private fun getDeadlineDate(calendar: Calendar, timeToComplete: Long, learningRate: LearningRate): Date {
val timePerWeek = learningRate.millisPerWeek
val time = timeToComplete * 1000 * TIME_MULTIPLIER / timePerWeek * AppConstants.MILLIS_IN_SEVEN_DAYS
calendar.timeInMillis += time.toLong()
calendar.set(Calendar.HOUR_OF_DAY, 23)
calendar.set(Calendar.MINUTE, 59)
val date = calendar.time
calendar.add(Calendar.MINUTE, 1) // set time at 00:00 of the next day
return date
}
} | app/src/main/java/org/stepik/android/domain/personal_deadlines/resolver/DeadlinesResolverImpl.kt | 1535227990 |
package org.stepik.android.domain.course_calendar.interactor
import android.content.Context
import io.reactivex.Completable
import io.reactivex.Single
import io.reactivex.rxkotlin.toObservable
import org.stepic.droid.R
import ru.nobird.android.domain.rx.doCompletableOnSuccess
import ru.nobird.android.core.model.mapToLongArray
import org.stepik.android.domain.calendar.model.CalendarEventData
import org.stepik.android.domain.calendar.model.CalendarItem
import org.stepik.android.domain.calendar.repository.CalendarRepository
import org.stepik.android.domain.course_calendar.model.SectionDateEvent
import org.stepik.android.domain.course_calendar.repository.CourseCalendarRepository
import org.stepik.android.view.course_content.model.CourseContentItem
import org.stepik.android.view.course_content.model.CourseContentSectionDate
import javax.inject.Inject
class CourseCalendarInteractor
@Inject
constructor(
private val context: Context,
private val calendarRepository: CalendarRepository,
private val courseCalendarRepository: CourseCalendarRepository
) {
fun getCalendarItems(): Single<List<CalendarItem>> =
calendarRepository.getCalendarItems()
fun exportScheduleToCalendar(courseContentItems: List<CourseContentItem>, calendarItem: CalendarItem): Completable =
Single
.fromCallable {
courseContentItems
.filterIsInstance<CourseContentItem.SectionItem>()
}
.doCompletableOnSuccess(::removeOldSchedule)
.flatMapObservable { sectionItems ->
sectionItems
.flatMap { sectionItem ->
sectionItem.dates.map { date -> mapDateToCalendarEventData(sectionItem, date) }
}
.toObservable()
}
.flatMapSingle { (sectionId, eventData) ->
calendarRepository
.saveCalendarEventData(eventData, calendarItem)
.map { eventId ->
SectionDateEvent(eventId, sectionId)
}
}
.toList()
.flatMapCompletable(courseCalendarRepository::saveSectionDateEvents)
private fun removeOldSchedule(sectionItems: List<CourseContentItem.SectionItem>): Completable =
courseCalendarRepository
.getSectionDateEventsByIds(*sectionItems.mapToLongArray { it.section.id })
.flatMapCompletable { dateEvents ->
calendarRepository
.removeCalendarEventDataByIds(*dateEvents.mapToLongArray(SectionDateEvent::eventId)) // mapToLongArray for varargs
.andThen(courseCalendarRepository
.removeSectionDateEventsByIds(*dateEvents.mapToLongArray(SectionDateEvent::sectionId)))
}
private fun mapDateToCalendarEventData(
sectionItem: CourseContentItem.SectionItem,
date: CourseContentSectionDate
): Pair<Long, CalendarEventData> =
sectionItem.section.id to
CalendarEventData(
title = context
.getString(
R.string.course_content_calendar_title,
sectionItem.section.title,
context.getString(date.titleRes)
),
date = date.date
)
} | app/src/main/java/org/stepik/android/domain/course_calendar/interactor/CourseCalendarInteractor.kt | 560581799 |
package HarmonyGen.MessageBus
import HarmonyGen.DB.DBArtist
import HarmonyGen.DB.Genre
import HarmonyGen.DB.PlayListByMap
import HarmonyGen.DB.getDBConn
import HarmonyGen.MusicAbstractor.getSimilarArtists
import HarmonyGen.Util.ArtistQuery
import HarmonyGen.Util.getArtist
import HarmonyGen.Util.getQueryBase
import HarmonyGen.Util.logger
import co.paralleluniverse.kotlin.fiber
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import java.time.OffsetDateTime
/**
* Created by on 9/6/16.
*/
data class SimilarPlayListMapping(
val artist: DBArtist,
val from : String?
)
fun dispatchInitializePlayList(event: InitializePlayList, branchDepth: Int = 2) {
logger.info("Dispatching initialization of playlist")
val rsp = getQueryBase("playlists").get(event.playlist).run<Map<String, Any?>>(getDBConn())
println(rsp)
val playlist = PlayListByMap(rsp)
val artists = playlist.seedArtists.map {
getQueryBase("artists").get(it).run<DBArtist, DBArtist>(getDBConn(), DBArtist::class.java).let { rcrd ->
try {
rcrd!!
} catch (e: NullPointerException) {
getSimilarArtists(ArtistQuery.ByMBID(it!!), initiateSimilar = true)
}
}
}
val genres = playlist.seedGenres.map {
getQueryBase("genres").get(it).run<Genre, Genre>(getDBConn(), Genre::class.java)
}
val similarMap = mutableMapOf<Int, MutableList<SimilarPlayListMapping>>()
for (a in artists) {
if (similarMap.containsKey(0)) {
similarMap[0]?.add(SimilarPlayListMapping(artist=a, from=null))
} else {
similarMap[0] = mutableListOf<SimilarPlayListMapping>(SimilarPlayListMapping(artist=a, from=null))
}
similarMap.putAll(getSimilarArtistsRecursive(a.similar!!, a, similarMap, branch = 0))
}
logger.debug("Scanned to depths of ${similarMap.keys}")
}
/**
* This is a recursive wrapper around getSimilarArtist.
*
* Given a list of MusicBrainz identifiers. Taking an inbound similarMap, which
* is branch level as key, and a similarmapping as the value. Iterate to match the breakAt points.
*
* Note we count in computer science/array terms. 0 is the origin point. It will stop when
* branch == breakAt.
*
* This will return the hashmap, and build out a nesting hierarchy.
*
* **ToDo**
*
* * This is introducing a side effect, the map is being modified. Make it sanitary and have it only return the map not modify
* * Adjust the inbound list to match ArtistQuery
*
* @see HarmonyGen.MessageBus.SimilarPlayListMapping
* @see HarmonyGen.DB.DBArtist
*
* @param breakAt:Int
*/
fun getSimilarArtistsRecursive(mbid:List<String>, from: DBArtist, similarMap:MutableMap<Int, MutableList<SimilarPlayListMapping>>, branch: Int = 0, breakAt: Int = 2)
: MutableMap<Int, MutableList<SimilarPlayListMapping>>{
logger.info("Beginning to recursively discover similar artists")
if (branch == breakAt) return similarMap
val artists = mbid.map { getSimilarArtists(ArtistQuery.ByMBID(it), initiateSimilar = true)}
for (artist in artists) {
if (similarMap.containsKey(branch)) {
similarMap[branch]?.add(SimilarPlayListMapping(artist=artist, from=from.id))
} else {
similarMap[branch] = mutableListOf(SimilarPlayListMapping(artist=artist, from=from.id))
}
val rcrd = getSimilarArtists(ArtistQuery.ByMBID(artist.id!!), initiateSimilar=true )
similarMap.putAll(getSimilarArtistsRecursive(rcrd.similar!!, artist, similarMap, branch=branch+1, breakAt = breakAt))
}
return similarMap
}
fun dispatchGetArtist(event: GetArtist) {
fiber {
val name = event.artist
if (name != null) {
var artist = getArtist(ArtistQuery.ByName(name), addIfNotExist = true, populateGenres = true)
event.completed = true
event.finished = OffsetDateTime.now()
updateEvent<GetArtist, GetArtist>(event)
}
}
} | src/main/kotlin/HarmonyGen/MessageBus/dispatchers.kt | 993615043 |
package su.jfdev.anci.logging
import kotlin.reflect.*
/**
* I recommend to use domain-likely loggers:
* as example: "network.message"
*/
interface Logger {
val name: String
operator fun contains(type: LogLevel): Boolean
fun print(type: LogLevel, text: String)
fun print(type: LogLevel, text: String, throwable: Throwable)
fun print(type: LogLevel, throwable: Throwable)
companion object {
operator fun get(name: String) = LoggingService.logger(name)
operator fun get(clazz: Class<*>) = Logger[clazz.name]
/**
* Inline to avoid KClass creating
*/
@Suppress("NOTHING_TO_INLINE")
inline operator fun get(clazz: KClass<*>) = Logger[clazz.java]
inline operator fun <reified C: Any> invoke() = Logger[C::class.java]
}
} | logging/src/api/kotlin/su/jfdev/anci/logging/Logger.kt | 1710998968 |
package com.apollographql.apollo3.cache.normalized.sql
import com.apollographql.apollo3.cache.normalized.NormalizedCacheFactory
import com.squareup.sqldelight.db.SqlDriver
expect class SqlNormalizedCacheFactory internal constructor(
driver: SqlDriver
) : NormalizedCacheFactory
| apollo-normalized-cache-sqlite/src/commonMain/kotlin/com/apollographql/apollo3/cache/normalized/sql/SqlNormalizedCacheFactory.kt | 1443909001 |
package org.zack.music.tools
import android.util.Log
import org.zack.music.BuildConfig
/**
* @Author Zackratos
* @Data 18-5-21
* @Email [email protected]
*/
object LogUtil {
fun d(tag: String, msg: String) {
if (BuildConfig.DEBUG)
Log.d(tag, msg)
}
fun d(msg: String) {
d("pure", msg)
}
} | app/src/main/kotlin/org/zack/music/tools/LogUtil.kt | 2581649546 |
package info.nightscout.androidaps.danars.comm
import dagger.android.HasAndroidInjector
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.danars.encryption.BleEncryption
class DanaRSPacketGeneralSetUserTimeChangeFlagClear(
injector: HasAndroidInjector
) : DanaRSPacket(injector) {
init {
opCode = BleEncryption.DANAR_PACKET__OPCODE_REVIEW__SET_USER_TIME_CHANGE_FLAG_CLEAR
aapsLogger.debug(LTag.PUMPCOMM, "New message")
}
override fun handleMessage(data: ByteArray) {
val result = intFromBuff(data, 0, 1)
@Suppress("LiftReturnOrAssignment")
if (result == 0) {
aapsLogger.debug(LTag.PUMPCOMM, "Result OK")
failed = false
} else {
aapsLogger.error("Result Error: $result")
failed = true
}
}
override val friendlyName: String = "REVIEW__SET_USER_TIME_CHANGE_FLAG_CLEAR"
} | danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralSetUserTimeChangeFlagClear.kt | 977933349 |
package com.cherryperry.amiami
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.scheduling.annotation.EnableScheduling
@SpringBootApplication
@EnableScheduling
class App {
companion object {
@Suppress("SpreadOperator")
@JvmStatic
fun main(args: Array<String>) {
SpringApplication.run(App::class.java, *args)
}
}
}
| src/main/kotlin/com/cherryperry/amiami/App.kt | 1774014548 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.gradleTooling
import org.gradle.api.Task
import org.gradle.api.file.SourceDirectorySet
import org.gradle.api.internal.FactoryNamedDomainObjectContainer
import org.gradle.api.plugins.JavaPluginConvention
import org.jetbrains.kotlin.idea.gradleTooling.AbstractKotlinGradleModelBuilder.Companion.getSourceSetName
import org.jetbrains.kotlin.idea.gradleTooling.AbstractKotlinGradleModelBuilder.Companion.kotlinPluginWrapper
import org.jetbrains.kotlin.idea.gradleTooling.AbstractKotlinGradleModelBuilder.Companion.kotlinProjectExtensionClass
import org.jetbrains.kotlin.idea.gradleTooling.AbstractKotlinGradleModelBuilder.Companion.kotlinSourceSetClass
import org.jetbrains.kotlin.idea.projectModel.KotlinTaskProperties
import java.io.File
data class KotlinTaskPropertiesImpl(
override val incremental: Boolean?,
override val packagePrefix: String?,
override val pureKotlinSourceFolders: List<File>?,
override val pluginVersion: String?
) : KotlinTaskProperties {
constructor(kotlinTaskProperties: KotlinTaskProperties) : this(
kotlinTaskProperties.incremental,
kotlinTaskProperties.packagePrefix,
kotlinTaskProperties.pureKotlinSourceFolders?.map { it }?.toList(),
kotlinTaskProperties.pluginVersion
)
}
typealias KotlinTaskPropertiesBySourceSet = MutableMap<String, KotlinTaskProperties>
private fun Task.getPackagePrefix(): String? {
try {
val getJavaPackagePrefix = this.javaClass.getMethod("getJavaPackagePrefix")
return (getJavaPackagePrefix.invoke(this) as? String)
} catch (e: Exception) {
}
return null
}
private fun Task.getIsIncremental(): Boolean? {
try {
val abstractKotlinCompileClass = javaClass.classLoader.loadClass(AbstractKotlinGradleModelBuilder.ABSTRACT_KOTLIN_COMPILE_CLASS)
val getIncremental = abstractKotlinCompileClass.getDeclaredMethod("getIncremental")
return (getIncremental.invoke(this) as? Boolean)
} catch (e: Exception) {
}
return null
}
private fun Task.getPureKotlinSourceRoots(sourceSet: String, disambiguationClassifier: String? = null): List<File>? {
try {
val kotlinExtensionClass = project.extensions.findByType(javaClass.classLoader.loadClass(kotlinProjectExtensionClass))
val getKotlinMethod = javaClass.classLoader.loadClass(kotlinSourceSetClass).getMethod("getKotlin")
val classifier = if (disambiguationClassifier == "metadata") "common" else disambiguationClassifier
val kotlinSourceSet = (kotlinExtensionClass?.javaClass?.getMethod("getSourceSets")?.invoke(kotlinExtensionClass)
as? FactoryNamedDomainObjectContainer<Any>)?.asMap?.get(compilationFullName(sourceSet, classifier)) ?: return null
val javaSourceSet =
(project.convention.getPlugin(JavaPluginConvention::class.java) as JavaPluginConvention).sourceSets.asMap[sourceSet]
val pureJava = javaSourceSet?.java?.srcDirs
return (getKotlinMethod.invoke(kotlinSourceSet) as? SourceDirectorySet)?.srcDirs?.filter {
!(pureJava?.contains(it) ?: false)
}?.toList()
} catch (e: Exception) {
}
return null
}
private fun Task.getKotlinPluginVersion(): String? {
try {
val pluginWrapperClass = javaClass.classLoader.loadClass(kotlinPluginWrapper)
val getVersionMethod =
pluginWrapperClass.getMethod("getKotlinPluginVersion", javaClass.classLoader.loadClass("org.gradle.api.Project"))
return getVersionMethod.invoke(null, this.project) as String
} catch (e: Exception) {
}
return null
}
fun KotlinTaskPropertiesBySourceSet.acknowledgeTask(compileTask: Task, classifier: String?) {
this[compileTask.getSourceSetName()] =
getKotlinTaskProperties(compileTask, classifier)
}
fun getKotlinTaskProperties(compileTask: Task, classifier: String?): KotlinTaskPropertiesImpl {
return KotlinTaskPropertiesImpl(
compileTask.getIsIncremental(),
compileTask.getPackagePrefix(),
compileTask.getPureKotlinSourceRoots(compileTask.getSourceSetName(), classifier),
compileTask.getKotlinPluginVersion()
)
}
| plugins/kotlin/gradle/gradle-tooling/src/org/jetbrains/kotlin/idea/gradleTooling/KotlinTasksPropertyUtils.kt | 823176229 |
package pl.orbitemobile.wspolnoty.data.remote.download
import org.jsoup.Connection
interface DownloadManager {
fun getResponse(url: String): Connection.Response
} | app/src/main/java/pl/orbitemobile/wspolnoty/data/remote/download/DownloadManager.kt | 3881372921 |
/*
* Copyright (c) 2017. All Rights Reserved. Michal Jankowski orbitemobile.pl
*/
package pl.orbitemobile.wspolnoty.activities.news
import io.reactivex.Single
import io.reactivex.SingleObserver
import pl.orbitemobile.mvp.MvpPresenter
import pl.orbitemobile.mvp.MvpView
import pl.orbitemobile.wspolnoty.activities.mvp.DownloadView
import pl.orbitemobile.wspolnoty.data.dto.ArticleDTO
class NewsContract {
abstract class View(layoutId: Int) : MvpView<Presenter>(layoutId), DownloadView {
abstract fun showArticles(articleDTOs: Array<ArticleDTO>)
}
interface Presenter : MvpPresenter<View>, SingleObserver<Array<ArticleDTO>> {
fun onRetryClick()
fun onArticleClick(articleDTO: ArticleDTO)
fun onShowMore()
}
interface UseCase {
fun getRemoteArticles(page: Int): Single<Array<ArticleDTO>>
}
}
| app/src/main/java/pl/orbitemobile/wspolnoty/activities/news/NewsContract.kt | 2568674046 |
package com.bajdcc.util.lexer.regex
import com.bajdcc.util.lexer.automata.dfa.DFA
import com.bajdcc.util.lexer.error.RegexException
import com.bajdcc.util.lexer.error.RegexException.RegexError
import com.bajdcc.util.lexer.stringify.RegexToString
import com.bajdcc.util.lexer.token.MetaType
import com.bajdcc.util.lexer.token.TokenUtility
/**
* 【词法分析】## 正则表达式分析工具 ##<br></br>
* 用于生成语法树<br></br>
* 语法同一般的正则表达式,只有贪婪模式,没有前/后向匹配, 没有捕获功能,仅用于匹配。
*
* @author bajdcc
*/
class Regex @Throws(RegexException::class)
@JvmOverloads constructor(pattern: String, val debug: Boolean = false) : RegexStringIterator(pattern) {
/**
* 表达式树根结点
*/
private lateinit var expression: IRegexComponent
/**
* DFA
*/
private lateinit var dfa: DFA
/**
* DFA状态转换表
*/
private lateinit var transition: Array<IntArray>
/**
* 终态表
*/
private val setFinalStatus = mutableSetOf<Int>()
/**
* 字符区间表
*/
private lateinit var charMap: CharacterMap
/**
* 字符串过滤接口
*/
var filter: IRegexStringFilter? = null
/**
* 获取字符区间描述
*
* @return 字符区间描述
*/
val statusString: String
get() = dfa.statusString
/**
* 获取NFA描述
*
* @return NFA描述
*/
val nfaString: String
get() = dfa.nfaString
/**
* 获取DFA描述
*
* @return DFA描述
*/
val dfaString: String
get() = dfa.dfaString
/**
* 获取DFATable描述
*
* @return DFATable描述
*/
val dfaTableString: String
get() = dfa.dfaTableString
init {
compile()
}
/**
* ## 编译表达式 ##<br></br>
*
* @throws RegexException 正则表达式错误
*/
@Throws(RegexException::class)
private fun compile() {
translate()
/* String->AST */
expression = analysis(MetaType.END.char, MetaType.END)
if (debug) {
println("#### 正则表达式语法树 ####")
println(toString())
}
/* AST->ENFA->NFA->DFA */
dfa = DFA(expression, debug)
/* DFA Transfer Table */
buildTransition()
}
/**
* 建立DFA状态转换表
*/
private fun buildTransition() {
/* 字符区间映射表 */
charMap = dfa.characterMap
/* DFA状态转移表 */
transition = dfa.buildTransition(setFinalStatus)
}
/**
* 匹配
*
* @param string 被匹配的字符串
* @param greed 是否贪婪匹配
* @return 匹配结果(若不成功则返回空)
*/
@JvmOverloads
fun match(string: String, greed: Boolean = true): String? {
var matchString: String? = null
val attr = object : IRegexStringAttribute {
override var result: String = ""
override val greedMode: Boolean
get() = greed
}
if (match(RegexStringIterator(string), attr)) {
matchString = attr.result
}
return matchString
}
/**
* 匹配算法(DFA状态表)
*
* @param iterator 字符串遍历接口
* @param attr 输出的匹配字符串
* @return 是否匹配成功
*/
fun match(iterator: IRegexStringIterator,
attr: IRegexStringAttribute): Boolean {
/* 使用全局字符映射表 */
val charMap = charMap.status
/* 保存当前位置 */
iterator.snapshot()
/* 当前状态 */
var status = 0
/* 上次经过的终态 */
var lastFinalStatus = -1
/* 上次经过的终态位置 */
var lastIndex = -1
/* 是否为贪婪模式 */
val greed = attr.greedMode
/* 存放匹配字符串 */
val sb = StringBuilder()
/* 是否允许通过终态结束识别 */
var allowFinal = false
while (true) {
if (setFinalStatus.contains(status)) {// 经过终态
if (greed) {// 贪婪模式
if (lastFinalStatus == -1) {
iterator.snapshot()// 保存位置
} else {
iterator.cover()// 覆盖位置
}
lastFinalStatus = status// 记录上次状态
lastIndex = sb.length
} else if (!allowFinal) {// 非贪婪模式,则匹配完成
iterator.discard()// 匹配成功,丢弃位置
attr.result = sb.toString()
return true
}
}
val local: Char
var skipStore = false// 取消存储当前字符
/* 获得当前字符 */
if (filter != null) {
val (_, current, _, meta) = filter!!.filter(iterator)// 过滤
local = current
skipStore = meta === MetaType.NULL
allowFinal = meta === MetaType.MUST_SAVE// 强制跳过终态
} else {
if (!iterator.available()) {
local = 0.toChar()
} else {
local = iterator.current()
iterator.next()
}
}
/* 存储字符 */
if (!skipStore) {
sb.append(if (data.zero) '\u0000' else local)
}
/* 获得字符区间索引 */
val charClass = charMap[local.toInt()]
/* 状态转移 */
var refer = -1
if (charClass != -1) {// 区间有效,尝试转移
refer = transition[status][charClass]
}
if (refer == -1) {// 失败
iterator.restore()
if (lastFinalStatus == -1) {// 匹配失败
return false
} else {// 使用上次经过的终态匹配结果
iterator.discard()// 匹配成功,丢弃位置
attr.result = sb.substring(0, lastIndex)
return true
}
} else {
status = refer// 更新状态
}
}
}
@Throws(RegexException::class)
private fun analysis(terminal: Char, meta: MetaType): IRegexComponent {
var sequence = Constructure(false)// 建立序列以存储表达式
var branch: Constructure? = null// 建立分支以存储'|'型表达式,是否是分支有待预测
var result = sequence
while (true) {
if (data.meta === meta && data.current == terminal) {// 结束字符
if (data.index == 0) {// 表达式为空
err(RegexError.NULL)
} else if (sequence.arrComponents.isEmpty()) {// 部件为空
err(RegexError.INCOMPLETE)
} else {
next()
break// 正常终止
}
} else if (data.meta === MetaType.END) {
err(RegexError.INCOMPLETE)
}
var expression: IRegexComponent? = null// 当前待赋值的表达式
if (data.meta == MetaType.BAR) {// '|'
next()
if (sequence.arrComponents.isEmpty())
// 在此之前没有存储表达式 (|...)
{
err(RegexError.INCOMPLETE)
} else {
if (branch == null) {// 分支为空,则建立分支
branch = Constructure(true)
branch.arrComponents.add(sequence)// 用新建的分支包含并替代当前序列
result = branch
}
sequence = Constructure(false)// 新建一个序列
branch.arrComponents.add(sequence)
continue
}
} else if (data.meta == MetaType.LPARAN) {// '('
next()
expression = analysis(MetaType.RPARAN.char,
MetaType.RPARAN)// 递归分析
}
if (expression == null) {// 当前不是表达式,则作为字符
val charset = Charset()// 当前待分析的字符集
expression = charset
when (data.meta) {
MetaType.ESCAPE// '\\'
-> {
next()
escape(charset, true)// 处理转义
}
MetaType.DOT// '.'
-> {
data.meta = MetaType.CHARACTER
escape(charset, true)
}
MetaType.LSQUARE // '['
-> {
next()
range(charset)
}
MetaType.END // '\0'
-> return result
else -> {
if (!charset.addChar(data.current)) {
err(RegexError.RANGE)
}
next()
}
}
}
val rep: Repetition// 循环
when (data.meta) {
MetaType.QUERY// '?'
-> {
next()
rep = Repetition(expression, 0, 1)
sequence.arrComponents.add(rep)
}
MetaType.PLUS// '+'
-> {
next()
rep = Repetition(expression, 1, -1)
sequence.arrComponents.add(rep)
}
MetaType.STAR// '*'
-> {
next()
rep = Repetition(expression, 0, -1)
sequence.arrComponents.add(rep)
}
MetaType.LBRACE // '{'
-> {
next()
rep = Repetition(expression, 0, -1)
quantity(rep)
sequence.arrComponents.add(rep)
}
else -> sequence.arrComponents.add(expression)
}
}
return result
}
/**
* 处理转义字符
*
* @param charset 字符集
* @param extend 是否支持扩展如\d \w等
* @throws RegexException 正则表达式错误
*/
@Throws(RegexException::class)
private fun escape(charset: Charset, extend: Boolean) {
var ch = data.current
if (data.meta === MetaType.CHARACTER) {// 字符
next()
if (extend) {
if (TokenUtility.isUpperLetter(ch) || ch == '.') {
charset.bReverse = true// 大写则取反
}
val cl = Character.toLowerCase(ch)
when (cl) {
'd'// 数字
-> {
charset.addRange('0', '9')
return
}
'a'// 字母
-> {
charset.addRange('a', 'z')
charset.addRange('A', 'Z')
return
}
'w'// 标识符
-> {
charset.addRange('a', 'z')
charset.addRange('A', 'Z')
charset.addRange('0', '9')
charset.addChar('_')
return
}
's'// 空白字符
-> {
charset.addChar('\r')
charset.addChar('\n')
charset.addChar('\t')
charset.addChar('\b')
charset.addChar('\u000c')
charset.addChar(' ')
return
}
else -> {
}
}
}
if (TokenUtility.isLetter(ch)) {// 如果为字母
ch = utility.fromEscape(ch, RegexError.ESCAPE)
if (!charset.addChar(ch)) {
err(RegexError.RANGE)
}
}
} else if (data.meta === MetaType.END) {
err(RegexError.INCOMPLETE)
} else {// 功能字符则转义
next()
if (!charset.addChar(ch)) {
err(RegexError.RANGE)
}
}
}
/**
* 处理字符集合
*
* @param charset 字符集
* @throws RegexException 正则表达式错误
*/
@Throws(RegexException::class)
private fun range(charset: Charset) {
if (data.meta === MetaType.CARET) {// '^'取反
next()
charset.bReverse = true
}
while (data.meta !== MetaType.RSQUARE) {// ']'
if (data.meta === MetaType.CHARACTER) {
character(charset)
val lower = data.current // lower bound
next()
if (data.meta === MetaType.DASH) {// '-'
next()
character(charset)
val upper = data.current // upper bound
next()
if (lower > upper) {// check bound
err(RegexError.RANGE)
}
if (!charset.addRange(lower, upper)) {
err(RegexError.RANGE)
}
} else {
if (!charset.addChar(lower)) {
err(RegexError.RANGE)
}
}
} else if (data.meta === MetaType.ESCAPE) {
next()
escape(charset, false)
} else if (data.meta === MetaType.END) {
err(RegexError.INCOMPLETE)
} else {
charset.addChar(data.current)
next()
}
}
next()
}
/**
* 处理字符
*
* @param charset 字符集
* @throws RegexException 正则表达式错误
*/
@Throws(RegexException::class)
private fun character(charset: Charset) {
if (data.meta === MetaType.ESCAPE) {// '\\'
next()
escape(charset, false)
} else if (data.meta === MetaType.END) {// '\0'
err(RegexError.INCOMPLETE)
} else if (data.meta !== MetaType.CHARACTER && data.meta !== MetaType.DASH) {
err(RegexError.CTYPE)
}
}
/**
* 处理量词
*
* @throws RegexException 正则表达式错误
*/
@Throws(RegexException::class)
private fun quantity(rep: Repetition) {
val lower: Int
var upper: Int
upper = digit()
lower = upper// 循环下界
if (lower == -1) {
err(RegexError.BRACE)
}
if (data.meta === MetaType.COMMA) {// ','
next()
if (data.meta === MetaType.RBRACE) {// '}'
upper = -1// 上界为无穷大
} else {
upper = digit()// 得到循环上界
if (upper == -1) {
err(RegexError.BRACE)
}
}
}
if (upper != -1 && upper < lower) {
err(RegexError.RANGE)
}
expect(MetaType.RBRACE, RegexError.BRACE)
rep.lowerBound = lower
rep.upperBound = upper
}
/**
* 十进制数字转换
*
* @return 数字
*/
private fun digit(): Int {
val index = data.index
while (Character.isDigit(data.current)) {
next()
}
return try {
Integer.valueOf(context.substring(index, data.index), 10)
} catch (e: NumberFormatException) {
-1
}
}
override fun transform() {
// 一般字符
data.meta = g_mapMeta.getOrDefault(data.current, MetaType.CHARACTER)// 功能字符
}
override fun toString(): String {
val alg = RegexToString()// 表达式树序列化算法初始化
expression.visit(alg)// 遍历树
return alg.toString()
}
companion object {
private val g_mapMeta = mutableMapOf<Char, MetaType>()
init {
val metaTypes = arrayOf(MetaType.LPARAN, MetaType.RPARAN,
MetaType.STAR, MetaType.PLUS, MetaType.QUERY,
MetaType.CARET, MetaType.LSQUARE, MetaType.RSQUARE,
MetaType.BAR, MetaType.ESCAPE, MetaType.DASH,
MetaType.LBRACE, MetaType.RBRACE, MetaType.COMMA,
MetaType.DOT, MetaType.NEW_LINE, MetaType.CARRIAGE_RETURN,
MetaType.BACKSPACE)
metaTypes.forEach { meta ->
g_mapMeta[meta.char] = meta
}
}
}
}
| src/main/kotlin/com/bajdcc/util/lexer/regex/Regex.kt | 3111502339 |
package org.intellij.plugins.markdown.lang.psi.impl
import com.intellij.openapi.util.TextRange
import com.intellij.psi.AbstractElementManipulator
import com.intellij.psi.ElementManipulators
import com.intellij.psi.LiteralTextEscaper
import com.intellij.psi.PsiLanguageInjectionHost
import com.intellij.psi.impl.source.tree.CompositePsiElement
import com.intellij.psi.tree.IElementType
import com.intellij.psi.util.siblings
import org.intellij.plugins.markdown.lang.MarkdownElementTypes
import org.intellij.plugins.markdown.lang.psi.MarkdownPsiElement
import org.intellij.plugins.markdown.lang.psi.MarkdownPsiElementFactory
import org.intellij.plugins.markdown.lang.psi.util.hasType
import org.intellij.plugins.markdown.util.MarkdownPsiUtil
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Experimental
class MarkdownFrontMatterHeader(type: IElementType): CompositePsiElement(type), PsiLanguageInjectionHost, MarkdownPsiElement {
override fun isValidHost(): Boolean {
val children = firstChild.siblings(forward = true, withSelf = true)
val newlines = children.count { MarkdownPsiUtil.WhiteSpaces.isNewLine(it) }
return newlines >= 2 && children.find { it.hasType(MarkdownElementTypes.FRONT_MATTER_HEADER_CONTENT) } != null
}
override fun updateText(text: String): PsiLanguageInjectionHost {
return ElementManipulators.handleContentChange(this, text)
}
override fun createLiteralTextEscaper(): LiteralTextEscaper<out PsiLanguageInjectionHost> {
return LiteralTextEscaper.createSimple(this)
}
internal class Manipulator: AbstractElementManipulator<MarkdownFrontMatterHeader>() {
override fun handleContentChange(element: MarkdownFrontMatterHeader, range: TextRange, content: String): MarkdownFrontMatterHeader? {
if (content.contains("---")) {
val textElement = MarkdownPsiElementFactory.createTextElement(element.project, content)
return if (textElement is MarkdownFrontMatterHeader) {
element.replace(textElement) as MarkdownFrontMatterHeader
} else null
}
val children = element.firstChild.siblings(forward = true, withSelf = true)
val contentElement = children.filterIsInstance<MarkdownFrontMatterHeaderContent>().firstOrNull() ?: return null
val shiftedRange = range.shiftLeft(contentElement.startOffsetInParent)
val updatedText = shiftedRange.replace(contentElement.text, content)
contentElement.replaceWithText(updatedText)
return element
}
}
}
| plugins/markdown/core/src/org/intellij/plugins/markdown/lang/psi/impl/MarkdownFrontMatterHeader.kt | 2365463237 |
package bz.stewart.bracken.db.leglislators.data
/**
* Created by stew on 6/4/17.
*/
class SocialMapper (socialInfoParsed:List<LegislatorSocialInfo>){
val socialInfoMap = socialInfoParsed.associate { Pair(it.id.bioguide, it) }
/**
* Updates the LegislatorData with the social info by mapping bioguide id.
*/
fun associateSocialToPeople(legislatorsParsed:List<LegislatorData>){
for (person in legislatorsParsed){
val socialInfo = socialInfoMap[person.id.bioguide]
if(socialInfo!=null){
person.social = socialInfo.social
}
}
}
} | db/src/main/kotlin/bz/stewart/bracken/db/leglislators/data/SocialMapper.kt | 2513341219 |
package org.hexworks.zircon.internal.util.rex
import java.io.* // ktlint-disable no-wildcard-imports
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.util.zip.GZIPInputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
/**
* Takes a GZIP-compressed [ByteArray] and returns it decompressed. This
* function can only be used on the **JVM**.
*/
fun decompressGZIPByteArray(compressedData: ByteArray): ByteArray {
ByteArrayInputStream(compressedData).use { bin ->
GZIPInputStream(bin).use { gzipper ->
val buffer = ByteArray(1024)
val out = ByteArrayOutputStream()
var len = gzipper.read(buffer)
while (len > 0) {
out.write(buffer, 0, len)
len = gzipper.read(buffer)
}
gzipper.close()
out.close()
return out.toByteArray()
}
}
}
fun unZipIt(zipSource: InputStream, outputFolder: File): List<File> {
val buffer = ByteArray(1024)
val outputFolderPath = outputFolder.absolutePath
val result = mutableListOf<File>()
val zis = ZipInputStream(zipSource)
var ze: ZipEntry? = zis.nextEntry
while (ze != null) {
val fileName = ze.name
val newFile = File(outputFolderPath + File.separator + fileName)
File(newFile.parent).mkdirs()
val fos = FileOutputStream(newFile)
result.add(newFile)
var len = zis.read(buffer)
while (len > 0) {
fos.write(buffer, 0, len)
len = zis.read(buffer)
}
fos.close()
ze = zis.nextEntry
}
zis.closeEntry()
zis.close()
return result
}
| zircon.core/src/jvmMain/kotlin/org/hexworks/zircon/internal/util/Decompressor.kt | 1413370775 |
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.vimscript.model.commands
import com.intellij.openapi.editor.RangeMarker
import com.maddyhome.idea.vim.VimPlugin
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.getLineStartForOffset
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.ex.ranges.LineRange
import com.maddyhome.idea.vim.ex.ranges.Ranges
import com.maddyhome.idea.vim.group.SearchGroup.RE_BOTH
import com.maddyhome.idea.vim.group.SearchGroup.RE_LAST
import com.maddyhome.idea.vim.group.SearchGroup.RE_SEARCH
import com.maddyhome.idea.vim.group.SearchGroup.RE_SUBST
import com.maddyhome.idea.vim.helper.MessageHelper.message
import com.maddyhome.idea.vim.helper.Msg
import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.regexp.CharPointer
import com.maddyhome.idea.vim.regexp.RegExp
import com.maddyhome.idea.vim.vimscript.model.ExecutionResult
/**
* see "h :global" / "h :vglobal"
*/
data class GlobalCommand(val ranges: Ranges, val argument: String, val invert: Boolean) : Command.SingleExecution(ranges, argument) {
override val argFlags = flags(RangeFlag.RANGE_OPTIONAL, ArgumentFlag.ARGUMENT_OPTIONAL, Access.SELF_SYNCHRONIZED)
override fun processCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult {
var result: ExecutionResult = ExecutionResult.Success
editor.removeSecondaryCarets()
val caret = editor.currentCaret()
// For :g command the default range is %
val lineRange: LineRange = if (ranges.size() == 0) {
LineRange(0, editor.lineCount() - 1)
} else {
getLineRange(editor, caret)
}
if (!processGlobalCommand(editor, context, lineRange)) {
result = ExecutionResult.Error
}
return result
}
private fun processGlobalCommand(
editor: VimEditor,
context: ExecutionContext,
range: LineRange,
): Boolean {
// When nesting the command works on one line. This allows for
// ":g/found/v/notfound/command".
if (globalBusy && (range.startLine != 0 || range.endLine != editor.lineCount() - 1)) {
VimPlugin.showMessage(message("E147"))
VimPlugin.indicateError()
return false
}
var cmd = CharPointer(StringBuffer(argument))
val pat: CharPointer
val delimiter: Char
var whichPat = RE_LAST
/*
* undocumented vi feature:
* "\/" and "\?": use previous search pattern.
* "\&": use previous substitute pattern.
*/
if (argument.isEmpty()) {
VimPlugin.showMessage(message("E148"))
VimPlugin.indicateError()
return false
} else if (cmd.charAt() == '\\') {
cmd.inc()
if ("/?&".indexOf(cmd.charAt()) == -1) {
VimPlugin.showMessage(message(Msg.e_backslash))
return false
}
whichPat = if (cmd.charAt() == '&') RE_SUBST else RE_SEARCH
cmd.inc()
pat = CharPointer("") /* empty search pattern */
} else {
delimiter = cmd.charAt() /* get the delimiter */
cmd.inc()
pat = cmd.ref(0) /* remember start of pattern */
cmd = RegExp.skip_regexp(cmd, delimiter, true)
if (cmd.charAt() == delimiter) { /* end delimiter found */
cmd.set('\u0000').inc() /* replace it with a NUL */
}
}
val (first, second) = injector.searchGroup.search_regcomp(pat, whichPat, RE_BOTH)
if (!first) {
VimPlugin.showMessage(message(Msg.e_invcmd))
VimPlugin.indicateError()
return false
}
val regmatch = second.first as RegExp.regmmatch_T
val sp = second.third as RegExp
var match: Int
val lcount = editor.lineCount()
val searchcol = 0
if (globalBusy) {
val offset = editor.currentCaret().offset
val lineStartOffset = editor.getLineStartForOffset(offset.point)
match = sp.vim_regexec_multi(regmatch, editor, lcount, editor.currentCaret().getLine().line, searchcol)
if ((!invert && match > 0) || (invert && match <= 0)) {
globalExecuteOne(editor, context, lineStartOffset, cmd.toString())
}
} else {
// pass 1: set marks for each (not) matching line
val line1 = range.startLine
val line2 = range.endLine
//region search_regcomp implementation
// We don't need to worry about lastIgnoreSmartCase, it's always false. Vim resets after checking, and it only sets
// it to true when searching for a word with `*`, `#`, `g*`, etc.
if (line1 < 0 || line2 < 0) {
return false
}
var ndone = 0
val marks = mutableListOf<RangeMarker>()
for (lnum in line1..line2) {
if (gotInt) break
// a match on this line?
match = sp.vim_regexec_multi(regmatch, editor, lcount, lnum, searchcol)
if ((!invert && match > 0) || (invert && match <= 0)) {
val lineStartOffset = editor.getLineStartOffset(lnum)
marks += editor.ij.document.createRangeMarker(lineStartOffset, lineStartOffset)
ndone += 1
}
// TODO: 25.05.2021 Check break
}
// pass 2: execute the command for each line that has been marked
if (gotInt) {
VimPlugin.showMessage(message("e_interr"))
} else if (ndone == 0) {
if (invert) {
VimPlugin.showMessage(message("global.command.not.found.v", pat.toString()))
} else {
VimPlugin.showMessage(message("global.command.not.found.g", pat.toString()))
}
} else {
globalExe(editor, context, marks, cmd.toString())
}
}
return true
}
private fun globalExe(editor: VimEditor, context: ExecutionContext, marks: List<RangeMarker>, cmd: String) {
globalBusy = true
try {
for (mark in marks) {
if (gotInt) break
if (!globalBusy) break
val startOffset = mark.startOffset
mark.dispose()
globalExecuteOne(editor, context, startOffset, cmd)
// TODO: 26.05.2021 break check
}
} catch (e: Exception) {
throw e
} finally {
globalBusy = false
}
// TODO: 26.05.2021 Add other staff
}
private fun globalExecuteOne(editor: VimEditor, context: ExecutionContext, lineStartOffset: Int, cmd: String?) {
// TODO: 26.05.2021 What about folds?
editor.currentCaret().moveToOffset(lineStartOffset)
if (cmd == null || cmd.isEmpty() || (cmd.length == 1 && cmd[0] == '\n')) {
injector.vimscriptExecutor.execute("p", editor, context, skipHistory = true, indicateErrors = true, this.vimContext)
} else {
injector.vimscriptExecutor.execute(cmd, editor, context, skipHistory = true, indicateErrors = true, this.vimContext)
}
}
companion object {
private var globalBusy = false
// Interrupted. Not used at the moment
var gotInt: Boolean = false
}
}
| src/main/java/com/maddyhome/idea/vim/vimscript/model/commands/GlobalCommand.kt | 27555562 |
package org.wordpress.android.ui.posts
import android.app.Dialog
import android.app.TimePickerDialog
import android.app.TimePickerDialog.OnTimeSetListener
import android.content.Context
import android.os.Bundle
import android.text.format.DateFormat
import androidx.appcompat.view.ContextThemeWrapper
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.ViewModelProvider
import org.wordpress.android.R.style
import org.wordpress.android.WordPress
import org.wordpress.android.ui.posts.prepublishing.PrepublishingPublishSettingsViewModel
import javax.inject.Inject
class PostTimePickerDialogFragment : DialogFragment() {
@Inject lateinit var viewModelFactory: ViewModelProvider.Factory
private lateinit var viewModel: PublishSettingsViewModel
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val publishSettingsFragmentType = arguments?.getParcelable<PublishSettingsFragmentType>(
ARG_PUBLISH_SETTINGS_FRAGMENT_TYPE
)
viewModel = when (publishSettingsFragmentType) {
PublishSettingsFragmentType.EDIT_POST -> ViewModelProvider(requireActivity(), viewModelFactory)
.get(EditPostPublishSettingsViewModel::class.java)
PublishSettingsFragmentType.PREPUBLISHING_NUDGES -> ViewModelProvider(requireActivity(), viewModelFactory)
.get(PrepublishingPublishSettingsViewModel::class.java)
null -> error("PublishSettingsViewModel not initialized")
}
val is24HrFormat = DateFormat.is24HourFormat(activity)
val context = ContextThemeWrapper(activity, style.PostSettingsCalendar)
val timePickerDialog = TimePickerDialog(
context,
OnTimeSetListener { _, selectedHour, selectedMinute ->
viewModel.onTimeSelected(selectedHour, selectedMinute)
},
viewModel.hour ?: 0,
viewModel.minute ?: 0,
is24HrFormat
)
return timePickerDialog
}
override fun onAttach(context: Context) {
super.onAttach(context)
(requireActivity().applicationContext as WordPress).component().inject(this)
}
companion object {
const val TAG = "post_time_picker_dialog_fragment"
const val ARG_PUBLISH_SETTINGS_FRAGMENT_TYPE = "publish_settings_fragment_type"
fun newInstance(publishSettingsFragmentType: PublishSettingsFragmentType): PostTimePickerDialogFragment {
return PostTimePickerDialogFragment().apply {
arguments = Bundle().apply {
putParcelable(
ARG_PUBLISH_SETTINGS_FRAGMENT_TYPE,
publishSettingsFragmentType
)
}
}
}
}
}
| WordPress/src/main/java/org/wordpress/android/ui/posts/PostTimePickerDialogFragment.kt | 3033859121 |
package com.edwardharker.aircraftrecognition
import android.app.Application
import com.edwardharker.aircraftrecognition.aircraftupdater.aircraftUpdater
import com.edwardharker.aircraftrecognition.android.firstInstall
import com.edwardharker.aircraftrecognition.stetho.initialiseStetho
class AircraftRecognitionApp : Application() {
override fun onCreate() {
super.onCreate()
app = this
initialiseStetho(this)
firstInstall().saveVersion()
aircraftUpdater().update()
}
companion object {
lateinit var app: AircraftRecognitionApp
}
}
| androidcommon/src/main/kotlin/com/edwardharker/aircraftrecognition/AircraftRecognitionApp.kt | 220334162 |
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
import com.kotlinnlp.simplednn.core.functionalities.activations.Softmax
import com.kotlinnlp.simplednn.core.functionalities.activations.Softsign
import com.kotlinnlp.simplednn.core.functionalities.losses.SoftmaxCrossEntropyCalculator
import com.kotlinnlp.simplednn.core.functionalities.outputevaluation.ClassificationEvaluation
import com.kotlinnlp.simplednn.core.functionalities.updatemethods.adagrad.AdaGradMethod
import com.kotlinnlp.simplednn.core.layers.LayerType
import com.kotlinnlp.simplednn.core.neuralnetwork.preset.FeedforwardNeuralNetwork
import utils.Corpus
import utils.SimpleExample
import traininghelpers.training.FeedforwardTrainer
import traininghelpers.validation.FeedforwardEvaluator
import com.kotlinnlp.simplednn.simplemath.ndarray.sparsebinary.SparseBinaryNDArray
import utils.CorpusReader
import utils.exampleextractor.ClassificationSparseExampleExtractor
fun main() {
println("Start 'Sparse Input Test'")
val dataset = CorpusReader<SimpleExample<SparseBinaryNDArray>>().read(
corpusPath = Configuration.loadFromFile().sparse_input.datasets_paths,
exampleExtractor = ClassificationSparseExampleExtractor(inputSize = 356425, outputSize = 86),
perLine = true)
SparseInputTest(dataset).start()
println("\nEnd.")
}
/**
*
*/
class SparseInputTest(val dataset: Corpus<SimpleExample<SparseBinaryNDArray>>) {
/**
*
*/
private val neuralNetwork = FeedforwardNeuralNetwork(
inputSize = 356425,
inputType = LayerType.Input.SparseBinary,
hiddenSize = 200,
hiddenActivation = Softsign,
outputSize = 86,
outputActivation = Softmax())
/**
*
*/
fun start() {
this.train()
}
/**
*
*/
private fun train() {
println("\n-- TRAINING")
FeedforwardTrainer(
model = this.neuralNetwork,
updateMethod = AdaGradMethod(learningRate = 0.1),
lossCalculator = SoftmaxCrossEntropyCalculator,
examples = this.dataset.training,
epochs = 3,
batchSize = 1,
evaluator = FeedforwardEvaluator(
model = this.neuralNetwork,
examples = this.dataset.validation,
outputEvaluationFunction = ClassificationEvaluation)
).train()
}
}
| examples/SparseInputTest.kt | 798706773 |
// WITH_STDLIB
val foo: String
<caret>get() = throw UnsupportedOperationException()
| plugins/kotlin/idea/tests/testData/intentions/convertToBlockBody/getterWithThrow.kt | 2325394096 |
package com.pluscubed.velociraptor.settings
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.text.parseAsHtml
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import butterknife.BindView
import butterknife.ButterKnife
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.list.listItems
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.Purchase
import com.android.billingclient.api.SkuDetails
import com.google.android.gms.location.LocationServices
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.crashlytics.FirebaseCrashlytics
import com.pluscubed.velociraptor.R
import com.pluscubed.velociraptor.billing.BillingConstants
import com.pluscubed.velociraptor.billing.BillingManager
import com.pluscubed.velociraptor.utils.PrefUtils
import com.pluscubed.velociraptor.utils.Utils
import kotlinx.coroutines.*
import java.util.*
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
class ProvidersFragment : Fragment() {
//Providers
@BindView(R.id.here_container)
lateinit var hereContainer: View
@BindView(R.id.here_title)
lateinit var hereTitle: TextView
@BindView(R.id.here_provider_desc)
lateinit var herePriceDesc: TextView
@BindView(R.id.here_subscribe)
lateinit var hereSubscribeButton: Button
@BindView(R.id.here_editdata)
lateinit var hereEditDataButton: Button
@BindView(R.id.tomtom_container)
lateinit var tomtomContainer: View
@BindView(R.id.tomtom_title)
lateinit var tomtomTitle: TextView
@BindView(R.id.tomtom_provider_desc)
lateinit var tomtomPriceDesc: TextView
@BindView(R.id.tomtom_subscribe)
lateinit var tomtomSubscribeButton: Button
@BindView(R.id.tomtom_editdata)
lateinit var tomtomEditDataButton: Button
@BindView(R.id.osm_title)
lateinit var osmTitle: TextView
@BindView(R.id.osm_editdata)
lateinit var osmEditDataButton: Button
@BindView(R.id.osm_donate)
lateinit var osmDonateButton: Button
@BindView(R.id.osm_coverage)
lateinit var osmCoverageButton: Button
private var billingManager: BillingManager? = null
private val isBillingManagerReady: Boolean
get() = billingManager != null && billingManager!!.billingClientResponseCode == BillingClient.BillingResponse.OK
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onDestroy() {
super.onDestroy()
if (billingManager != null) {
billingManager!!.destroy()
}
}
override fun onResume() {
super.onResume()
if (billingManager != null && billingManager!!.billingClientResponseCode == BillingClient.BillingResponse.OK) {
billingManager!!.queryPurchases()
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_providers, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
ButterKnife.bind(this, view)
hereEditDataButton.setOnClickListener {
Utils.openLink(activity, view, HERE_EDITDATA_URL)
}
hereSubscribeButton.setOnClickListener {
if (!isBillingManagerReady) {
Snackbar.make(
view,
R.string.in_app_unavailable,
Snackbar.LENGTH_SHORT
).show()
return@setOnClickListener
}
billingManager?.initiatePurchaseFlow(
BillingConstants.SKU_HERE,
BillingClient.SkuType.SUBS
)
}
tomtomSubscribeButton.setOnClickListener {
if (!isBillingManagerReady) {
Snackbar.make(
view,
R.string.in_app_unavailable,
Snackbar.LENGTH_SHORT
).show()
return@setOnClickListener;
}
billingManager?.initiatePurchaseFlow(
BillingConstants.SKU_TOMTOM,
BillingClient.SkuType.SUBS
)
}
tomtomEditDataButton.setOnClickListener {
Utils.openLink(activity, view, TOMTOM_EDITDATA_URL)
}
osmCoverageButton.setOnClickListener {
openOsmCoverage()
}
osmEditDataButton.setOnClickListener {
activity?.let { activity ->
MaterialDialog(activity)
.show {
var text = getString(R.string.osm_edit)
if (text.contains("%s")) {
text = text.format("<b>$OSM_EDITDATA_URL</b>")
}
message(text = text.parseAsHtml()) {
lineSpacing(1.2f)
}
positiveButton(R.string.share_link) { _ ->
val shareIntent = Intent()
shareIntent.type = "text/plain"
shareIntent.putExtra(Intent.EXTRA_TEXT, OSM_EDITDATA_URL)
startActivity(
Intent.createChooser(
shareIntent,
getString(R.string.share_link)
)
)
}
}
}
}
osmDonateButton.setOnClickListener { Utils.openLink(activity, view, OSM_DONATE_URL) }
val checkIcon =
activity?.let { AppCompatResources.getDrawable(it, R.drawable.ic_done_green_20dp) }
val crossIcon =
activity?.let { AppCompatResources.getDrawable(it, R.drawable.ic_cross_red_20dp) }
osmTitle.setCompoundDrawablesWithIntrinsicBounds(null, null, checkIcon, null)
hereTitle.setCompoundDrawablesWithIntrinsicBounds(null, null, crossIcon, null)
tomtomTitle.setCompoundDrawablesWithIntrinsicBounds(null, null, crossIcon, null)
billingManager = BillingManager(activity, object : BillingManager.BillingUpdatesListener {
override fun onBillingClientSetupFinished() {
try {
billingManager?.querySkuDetailsAsync(
BillingClient.SkuType.SUBS,
Arrays.asList(BillingConstants.SKU_HERE, BillingConstants.SKU_TOMTOM)
) { responseCode, skuDetailsList ->
if (responseCode != BillingClient.BillingResponse.OK) {
return@querySkuDetailsAsync
}
for (details in skuDetailsList) {
if (details.sku == BillingConstants.SKU_HERE) {
herePriceDesc.text = getString(
R.string.here_desc,
getString(R.string.per_month, details.price)
)
}
if (details.sku == BillingConstants.SKU_TOMTOM) {
tomtomPriceDesc.text = getString(
R.string.tomtom_desc,
getString(R.string.per_month, details.price)
)
}
}
}
} catch (e: Exception) {
FirebaseCrashlytics.getInstance().recordException(e);
}
}
override fun onConsumeFinished(token: String, result: Int) {
PrefUtils.setSupported(activity, true)
}
override fun onPurchasesUpdated(purchases: List<Purchase>) {
val purchased = HashSet<String>()
if (purchased.size > 0) {
PrefUtils.setSupported(activity, true)
}
val onetime = BillingConstants.getSkuList(BillingClient.SkuType.INAPP)
for (purchase in purchases) {
if (purchase.sku in onetime) {
try {
billingManager?.consumeAsync(purchase.purchaseToken);
} catch (e: Exception) {
FirebaseCrashlytics.getInstance().recordException(e);
}
} else {
purchased.add(purchase.sku)
}
}
val hereSubscribed = purchased.contains(BillingConstants.SKU_HERE)
if (hereSubscribed) {
hereContainer.isVisible = true
}
setButtonSubscriptionState(
hereSubscribeButton,
hereTitle,
purchased.contains(BillingConstants.SKU_HERE),
BillingConstants.SKU_HERE
)
val tomtomSubscribed = purchased.contains(BillingConstants.SKU_TOMTOM)
if (tomtomSubscribed) {
tomtomContainer.isVisible = true
}
setButtonSubscriptionState(
tomtomSubscribeButton,
tomtomTitle,
tomtomSubscribed,
BillingConstants.SKU_TOMTOM
)
}
})
}
private fun setButtonSubscriptionState(button: Button?, title: TextView?, subscribed: Boolean, sku: String) {
if (subscribed) {
button?.setText(R.string.unsubscribe)
button?.setOnClickListener {
Utils.openLink(context, it,
"http://play.google.com/store/account/subscriptions?package=com.pluscubed.velociraptor&sku=${sku}")
}
val checkIcon =
activity?.let { AppCompatResources.getDrawable(it, R.drawable.ic_done_green_20dp) }
title?.setCompoundDrawablesWithIntrinsicBounds(null, null, checkIcon, null)
} else {
button?.setText(R.string.subscribe)
button?.setOnClickListener {
if (!isBillingManagerReady) {
Snackbar.make(
requireView(),
R.string.in_app_unavailable,
Snackbar.LENGTH_SHORT
).show()
return@setOnClickListener
}
billingManager?.initiatePurchaseFlow(
sku,
BillingClient.SkuType.SUBS
)
}
val crossIcon =
activity?.let { AppCompatResources.getDrawable(it, R.drawable.ic_cross_red_20dp) }
title?.setCompoundDrawablesWithIntrinsicBounds(null, null, crossIcon, null)
}
}
private suspend fun querySkuDetails(
manager: BillingManager?,
itemType: String,
vararg skuList: String
): List<SkuDetails> = suspendCoroutine { cont ->
manager?.querySkuDetailsAsync(
itemType,
Arrays.asList(*skuList)
) { responseCode, skuDetailsList ->
if (responseCode != BillingClient.BillingResponse.OK) {
cont.resumeWithException(Exception("Billing error: $responseCode"))
} else {
cont.resume(skuDetailsList)
}
}
}
fun showSupportDialog() {
if (!isBillingManagerReady) {
view?.let {
Snackbar.make(it, R.string.in_app_unavailable, Snackbar.LENGTH_SHORT).show()
}
return
}
viewLifecycleOwner.lifecycleScope.launch {
supervisorScope {
try {
val monthlyDonations = async(Dispatchers.IO) {
querySkuDetails(
billingManager,
BillingClient.SkuType.SUBS,
BillingConstants.SKU_D1_MONTHLY,
BillingConstants.SKU_D3_MONTHLY
)
}
val oneTimeDonations = async(Dispatchers.IO) {
querySkuDetails(
billingManager,
BillingClient.SkuType.INAPP,
BillingConstants.SKU_D1,
BillingConstants.SKU_D3,
BillingConstants.SKU_D5,
BillingConstants.SKU_D10,
BillingConstants.SKU_D20
)
}
val skuDetailsList = monthlyDonations.await() + oneTimeDonations.await()
@Suppress("DEPRECATION")
var text = getString(R.string.support_dev_dialog)
if (PrefUtils.hasSupported(activity)) {
text += "\n\n\uD83C\uDF89 " + getString(R.string.support_dev_dialog_badge) + " \uD83C\uDF89"
}
var dialog = activity?.let {
MaterialDialog(it)
.icon(
drawable = AppCompatResources.getDrawable(
it,
R.drawable.ic_favorite_black_24dp
)
)
.title(R.string.support_development)
.message(text = text) {
lineSpacing(1.2f)
}
}
val purchaseDisplay = ArrayList<String>()
for (details in skuDetailsList) {
var amount = details.price
if (details.type == BillingClient.SkuType.SUBS)
amount = getString(R.string.per_month, amount)
else {
amount = getString(R.string.one_time, amount)
}
purchaseDisplay.add(amount)
}
dialog = dialog?.listItems(items = purchaseDisplay) { _, which, _ ->
val skuDetails = skuDetailsList[which]
billingManager!!.initiatePurchaseFlow(skuDetails.sku, skuDetails.type)
}
dialog?.show()
} catch (e: Exception) {
view?.let {
Snackbar.make(it, R.string.in_app_unavailable, Snackbar.LENGTH_SHORT).show()
}
e.printStackTrace()
}
}
}
}
@SuppressLint("MissingPermission")
private fun openOsmCoverage() {
if (Utils.isLocationPermissionGranted(activity)) {
activity?.let {
val fusedLocationProvider = LocationServices.getFusedLocationProviderClient(it)
fusedLocationProvider.lastLocation.addOnCompleteListener(it) { task ->
var uriString = OSM_COVERAGE_URL
if (task.isSuccessful && task.result != null) {
val lastLocation = task.result
uriString +=
"?lon=${lastLocation?.longitude}&lat=${lastLocation?.latitude}&zoom=12"
}
Utils.openLink(activity, view, uriString)
}
}
} else {
Utils.openLink(activity, view, OSM_COVERAGE_URL)
}
}
companion object {
const val OSM_EDITDATA_URL = "https://openstreetmap.org"
const val OSM_COVERAGE_URL = "https://product.itoworld.com/map/124"
const val OSM_DONATE_URL = "https://donate.openstreetmap.org"
const val HERE_EDITDATA_URL = "https://mapcreator.here.com/mapcreator"
const val TOMTOM_EDITDATA_URL = "https://www.tomtom.com/mapshare/tools"
}
} | app/src/main/java/com/pluscubed/velociraptor/settings/ProvidersFragment.kt | 3760625941 |
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.resolve.delegatesTo
import com.intellij.psi.PsiType
import groovy.lang.Closure
class DelegatesToInfo(val typeToDelegate: PsiType?, val strategy: Int = Closure.OWNER_FIRST)
| plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/delegatesTo/DelegatesToInfo.kt | 2047439299 |
/*
* VoIP.ms SMS
* Copyright (C) 2017-2021 Michael Kourlas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.kourlas.voipms_sms.notifications
import android.annotation.SuppressLint
import android.app.*
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.widget.Toast
import androidx.core.app.*
import androidx.core.app.Person
import androidx.core.app.RemoteInput
import androidx.core.app.TaskStackBuilder
import androidx.core.content.LocusIdCompat
import androidx.core.graphics.drawable.IconCompat
import androidx.work.WorkManager
import net.kourlas.voipms_sms.BuildConfig
import net.kourlas.voipms_sms.CustomApplication
import net.kourlas.voipms_sms.R
import net.kourlas.voipms_sms.conversation.ConversationActivity
import net.kourlas.voipms_sms.conversation.ConversationBubbleActivity
import net.kourlas.voipms_sms.conversations.ConversationsActivity
import net.kourlas.voipms_sms.database.Database
import net.kourlas.voipms_sms.preferences.*
import net.kourlas.voipms_sms.sms.ConversationId
import net.kourlas.voipms_sms.sms.Message
import net.kourlas.voipms_sms.sms.receivers.MarkReadReceiver
import net.kourlas.voipms_sms.sms.receivers.SendMessageReceiver
import net.kourlas.voipms_sms.utils.*
import java.util.*
/**
* Single-instance class used to send notifications when new SMS messages
* are received.
*/
class Notifications private constructor(private val context: Context) {
// Helper variables
private val notificationManager = context.getSystemService(
Context.NOTIFICATION_SERVICE
) as NotificationManager
// Information associated with active notifications
private val notificationIds = mutableMapOf<ConversationId, Int>()
private val notificationMessages =
mutableMapOf<ConversationId,
List<NotificationCompat.MessagingStyle.Message>>()
private var notificationIdCount = MESSAGE_START_NOTIFICATION_ID
/**
* Attempts to create a notification channel for the specified DID.
*/
fun createDidNotificationChannel(did: String, contact: String) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create the default notification channel if it doesn't already
// exist
createDefaultNotificationChannel()
val defaultChannel = notificationManager.getNotificationChannel(
context.getString(R.string.notifications_channel_default)
)
val channelGroup = NotificationChannelGroup(
context.getString(
R.string.notifications_channel_group_did,
did
),
getFormattedPhoneNumber(did)
)
notificationManager.createNotificationChannelGroup(channelGroup)
val contactName = getContactName(context, contact)
val channel = NotificationChannel(
context.getString(
R.string.notifications_channel_contact,
did, contact
),
contactName ?: getFormattedPhoneNumber(contact),
defaultChannel.importance
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
channel.setConversationId(
context.getString(R.string.notifications_channel_default),
ConversationId(did, contact).getId()
)
}
channel.enableLights(defaultChannel.shouldShowLights())
channel.lightColor = defaultChannel.lightColor
channel.enableVibration(defaultChannel.shouldVibrate())
channel.vibrationPattern = defaultChannel.vibrationPattern
channel.lockscreenVisibility = defaultChannel.lockscreenVisibility
channel.setBypassDnd(defaultChannel.canBypassDnd())
channel.setSound(
defaultChannel.sound,
defaultChannel.audioAttributes
)
channel.setShowBadge(defaultChannel.canShowBadge())
channel.group = context.getString(
R.string.notifications_channel_group_did,
did
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
channel.setAllowBubbles(true)
}
notificationManager.createNotificationChannel(channel)
}
}
/**
* Attempts to create the default notification channel.
*/
fun createDefaultNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createOtherNotificationChannelGroup()
val channel = NotificationChannel(
context.getString(R.string.notifications_channel_default),
context.getString(R.string.notifications_channel_default_title),
NotificationManager.IMPORTANCE_HIGH
)
channel.enableLights(true)
channel.lightColor = Color.RED
channel.enableVibration(true)
channel.vibrationPattern = longArrayOf(0, 250, 250, 250)
channel.setShowBadge(true)
channel.group = context.getString(
R.string.notifications_channel_group_other
)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
channel.setAllowBubbles(true)
}
notificationManager.createNotificationChannel(channel)
}
}
/**
* Creates the notification channel for the notification displayed during
* database synchronization.
*/
private fun createSyncNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createOtherNotificationChannelGroup()
val channel = NotificationChannel(
context.getString(R.string.notifications_channel_sync),
context.getString(R.string.notifications_channel_sync_title),
NotificationManager.IMPORTANCE_LOW
)
channel.group = context.getString(
R.string.notifications_channel_group_other
)
notificationManager.createNotificationChannel(channel)
}
}
/**
* Creates the notification channel group for non-conversation related
* notifications.
*/
private fun createOtherNotificationChannelGroup() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelGroup = NotificationChannelGroup(
context.getString(R.string.notifications_channel_group_other),
context.getString(
R.string.notifications_channel_group_other_title
)
)
notificationManager.createNotificationChannelGroup(channelGroup)
}
}
/**
* Rename notification channels for changed contact numbers.
*/
fun renameNotificationChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Rename all channels
for (channel in notificationManager.notificationChannels) {
if (channel.id.startsWith(
context.getString(
R.string.notifications_channel_contact_prefix
)
)
) {
val contact = channel.id.split("_")[4]
val contactName = getContactName(context, contact)
channel.name = contactName ?: getFormattedPhoneNumber(
contact
)
notificationManager.createNotificationChannel(channel)
}
}
}
}
/**
* Delete notification channels for conversations that are no longer active.
*/
suspend fun deleteNotificationChannelsAndGroups() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Remove any channel for which there is no conversation with
// notifications enabled in the database
val conversationIds = Database.getInstance(context)
.getConversationIds(
getDids(context, onlyShowNotifications = true)
)
for (channel in notificationManager.notificationChannels) {
if (channel.id.startsWith(
context.getString(
R.string.notifications_channel_contact_prefix
)
)
) {
val splitId = channel.id.split(":")[0].trim().split("_")
val conversationId = ConversationId(splitId[3], splitId[4])
if (conversationId !in conversationIds) {
notificationManager.deleteNotificationChannel(
channel.id
)
validateGroupNotification()
}
}
}
// Remove any channel for which there is no conversation with
// notifications enabled in the database
val dids = conversationIds.map { it.did }.toSet()
for (group in notificationManager.notificationChannelGroups) {
if (group.id.startsWith(
context.getString(
R.string.notifications_channel_group_did, ""
)
)
) {
val did = group.id.split("_")[3]
if (did !in dids) {
notificationManager.deleteNotificationChannelGroup(
group.id
)
validateGroupNotification()
}
}
}
}
}
/**
* Gets the notification displayed during synchronization.
*/
fun getSyncDatabaseNotification(id: UUID, progress: Int = 0): Notification {
createSyncNotificationChannel()
val builder = NotificationCompat.Builder(
context, context.getString(R.string.notifications_channel_sync)
)
builder.setCategory(NotificationCompat.CATEGORY_PROGRESS)
builder.setSmallIcon(R.drawable.ic_message_sync_toolbar_24dp)
builder.setContentTitle(
context.getString(
R.string.notifications_sync_database_message
)
)
builder.setContentText("$progress%")
builder.setProgress(100, progress, false)
builder.setOngoing(true)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
@Suppress("DEPRECATION")
builder.priority = Notification.PRIORITY_LOW
}
// Cancel action
val cancelPendingIntent =
WorkManager.getInstance(context).createCancelPendingIntent(id)
val cancelAction = NotificationCompat.Action.Builder(
R.drawable.ic_delete_toolbar_24dp,
context.getString(R.string.notifications_button_cancel),
cancelPendingIntent
)
.setShowsUserInterface(false)
.build()
builder.addAction(cancelAction)
return builder.build()
}
/**
* Gets the notification displayed during message sending.
*/
fun getSyncMessageSendNotification(): Notification {
createSyncNotificationChannel()
val builder = NotificationCompat.Builder(
context, context.getString(R.string.notifications_channel_sync)
)
builder.setCategory(NotificationCompat.CATEGORY_SERVICE)
builder.setSmallIcon(R.drawable.ic_message_sync_toolbar_24dp)
builder.setContentTitle(
context.getString(
R.string.notifications_sync_send_message_message
)
)
builder.setOngoing(true)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
@Suppress("DEPRECATION")
builder.priority = Notification.PRIORITY_LOW
}
return builder.build()
}
/**
* Gets the notification displayed during verification of credentials.
*/
fun getSyncVerifyCredentialsNotification(): Notification {
createSyncNotificationChannel()
val builder = NotificationCompat.Builder(
context, context.getString(R.string.notifications_channel_sync)
)
builder.setCategory(NotificationCompat.CATEGORY_SERVICE)
builder.setSmallIcon(R.drawable.ic_message_sync_toolbar_24dp)
builder.setContentTitle(
context.getString(
R.string.notifications_sync_verify_credentials_message
)
)
builder.setOngoing(true)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
@Suppress("DEPRECATION")
builder.priority = Notification.PRIORITY_LOW
}
return builder.build()
}
/**
* Gets the notification displayed during verification of credentials.
*/
fun getSyncRetrieveDidsNotification(): Notification {
createSyncNotificationChannel()
val builder = NotificationCompat.Builder(
context, context.getString(R.string.notifications_channel_sync)
)
builder.setCategory(NotificationCompat.CATEGORY_SERVICE)
builder.setSmallIcon(R.drawable.ic_message_sync_toolbar_24dp)
builder.setContentTitle(
context.getString(
R.string.notifications_sync_retrieve_dids_message
)
)
builder.setOngoing(true)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
@Suppress("DEPRECATION")
builder.priority = Notification.PRIORITY_LOW
}
return builder.build()
}
/**
* Gets the notification displayed during verification of credentials.
*/
fun getSyncRegisterPushNotificationsNotification(): Notification {
createSyncNotificationChannel()
val builder = NotificationCompat.Builder(
context, context.getString(R.string.notifications_channel_sync)
)
builder.setCategory(NotificationCompat.CATEGORY_SERVICE)
builder.setSmallIcon(R.drawable.ic_message_sync_toolbar_24dp)
builder.setContentTitle(
context.getString(
R.string.notifications_sync_register_push_message
)
)
builder.setOngoing(true)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
@Suppress("DEPRECATION")
builder.priority = Notification.PRIORITY_LOW
}
return builder.build()
}
/**
* Returns whether notifications are enabled globally and for the
* conversation ID if one is specified.
*/
fun getNotificationsEnabled(
conversationId: ConversationId? = null
): Boolean {
// Prior to Android O, check the global notification settings;
// otherwise we can just rely on the system to block the notifications
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
@Suppress("DEPRECATION")
if (!getNotificationsEnabled(context)) {
return false
}
if (!NotificationManagerCompat.from(
context
).areNotificationsEnabled()
) {
return false
}
} else {
removePreference(
context, context.getString(
R.string.preferences_notifications_enable_key
)
)
}
// However, we do check to see if notifications are enabled for a
// particular DID, since the Android O interface doesn't really work
// with this use case
if (conversationId != null) {
if (!getDidShowNotifications(context, conversationId.did)) {
return false
}
}
return true
}
/**
* Show notifications for new messages for the specified conversations.
*/
suspend fun showNotifications(
conversationIds: Set<ConversationId>,
bubbleOnly: Boolean = false,
autoLaunchBubble: Boolean = false,
inlineReplyMessages: List<Message>
= emptyList()
) {
// Do not show notifications when the conversations view is open,
// unless this is for a bubble only.
if (CustomApplication.getApplication()
.conversationsActivityVisible() && !bubbleOnly
) {
return
}
for (conversationId in conversationIds) {
// Do not show notifications when notifications are disabled.
if (!getNotificationsEnabled(conversationId)) {
continue
}
// Do not show notifications when the conversation view is
// open, unless this is for a bubble only.
if (CustomApplication.getApplication()
.conversationActivityVisible(conversationId)
&& !bubbleOnly
) {
continue
}
showNotification(
conversationId,
if (bubbleOnly || inlineReplyMessages.isNotEmpty())
emptyList()
else Database.getInstance(context)
.getConversationMessagesUnread(conversationId),
inlineReplyMessages,
bubbleOnly,
autoLaunchBubble
)
}
}
/**
* Shows a notification for the specified message, bypassing all normal
* checks. Only used for demo purposes.
*/
fun showDemoNotification(message: Message) = showNotification(
message.conversationId,
listOf(message),
inlineReplyMessages = emptyList(),
bubbleOnly = false,
autoLaunchBubble = false
)
/**
* Returns true if a notification for the provided DID and contact would
* be allowed to bubble.
*/
fun canBubble(did: String, contact: String): Boolean {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val channel = getNotificationChannelId(did, contact)
val notificationManager: NotificationManager =
context.getSystemService(
Context.NOTIFICATION_SERVICE
) as NotificationManager
val bubblesAllowed =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
notificationManager.bubblePreference == NotificationManager.BUBBLE_PREFERENCE_ALL
} else {
@Suppress("DEPRECATION")
notificationManager.areBubblesAllowed()
}
if (!bubblesAllowed) {
val notificationChannel =
notificationManager.getNotificationChannel(channel)
return notificationChannel != null
&& notificationChannel.canBubble()
}
return true
}
return false
}
/**
* Shows a notification with the specified messages.
*/
private fun showNotification(
conversationId: ConversationId,
messages: List<Message>,
inlineReplyMessages: List<Message>,
bubbleOnly: Boolean,
autoLaunchBubble: Boolean
) {
// Do not show notification if there are no messages, unless this is
// for a bubble notification.
if (messages.isEmpty()
&& inlineReplyMessages.isEmpty()
&& !bubbleOnly
) {
return
}
// However, if this is not Android R or later, there is no such thing
// as a "bubble only" notification, so we should just return.
if (bubbleOnly && Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
return
}
// Notification metadata
val did = conversationId.did
val contact = conversationId.contact
// Do not show bubble-only notifications if we're not allowed to
// bubble.
if (bubbleOnly && !canBubble(did, contact)) {
return
}
@Suppress("ConstantConditionIf")
val contactName = if (!BuildConfig.IS_DEMO) {
getContactName(context, contact) ?: getFormattedPhoneNumber(contact)
} else {
net.kourlas.voipms_sms.demo.getContactName(contact)
}
val largeIcon = applyCircularMask(
getContactPhotoBitmap(
context,
contactName,
contact,
context.resources.getDimensionPixelSize(
android.R.dimen.notification_large_icon_height
)
)
)
val adaptiveIcon = IconCompat.createWithAdaptiveBitmap(
getContactPhotoAdaptiveBitmap(context, contactName, contact)
)
// Notification channel
val channel = getNotificationChannelId(did, contact)
// General notification properties
val notification = NotificationCompat.Builder(context, channel)
notification.setSmallIcon(R.drawable.ic_chat_toolbar_24dp)
notification.setLargeIcon(largeIcon)
notification.setAutoCancel(true)
notification.addPerson(
Person.Builder()
.setName(contactName)
.setKey(contact)
.setIcon(adaptiveIcon)
.setUri("tel:${contact}")
.build()
)
notification.setCategory(Notification.CATEGORY_MESSAGE)
notification.color = 0xFFAA0000.toInt()
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
@Suppress("DEPRECATION")
notification.priority = Notification.PRIORITY_HIGH
notification.setLights(0xFFAA0000.toInt(), 1000, 5000)
@Suppress("DEPRECATION")
val notificationSound = getNotificationSound(context)
if (notificationSound != "") {
@Suppress("DEPRECATION")
notification.setSound(Uri.parse(getNotificationSound(context)))
}
@Suppress("DEPRECATION")
if (getNotificationVibrateEnabled(context)) {
notification.setVibrate(longArrayOf(0, 250, 250, 250))
}
} else {
removePreference(
context, context.getString(
R.string.preferences_notifications_sound_key
)
)
removePreference(
context, context.getString(
R.string.preferences_notifications_vibrate_key
)
)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
notification.setGroup(
context.getString(
R.string.notifications_group_key
)
)
}
notification.setGroupAlertBehavior(
NotificationCompat.GROUP_ALERT_CHILDREN
)
notification.setShortcutId(conversationId.getId())
notification.setLocusId(LocusIdCompat(conversationId.getId()))
if (bubbleOnly || inlineReplyMessages.isNotEmpty()) {
// This means no new messages were received, so we should avoid
// notifying the user if we can.
notification.setOnlyAlertOnce(true)
}
// Notification text
val person = Person.Builder().setName(
context.getString(R.string.notifications_current_user)
).build()
val style = NotificationCompat.MessagingStyle(person)
val existingMessages =
notificationMessages[conversationId] ?: emptyList()
for (existingMessage in existingMessages) {
style.addHistoricMessage(existingMessage)
}
val messagesToAdd = mutableListOf<Message>()
if (messages.isNotEmpty()) {
for (message in messages.reversed()) {
if (existingMessages.isNotEmpty()
&& existingMessages.last().text == message.text
&& existingMessages.last().person != null
&& existingMessages.last().timestamp == message.date.time
) {
break
}
messagesToAdd.add(message)
}
messagesToAdd.reverse()
}
if (inlineReplyMessages.isNotEmpty()) {
for (message in inlineReplyMessages) {
style.addMessage(message.text, Date().time, null as Person?)
}
} else if (messagesToAdd.isNotEmpty()) {
val notificationMessages = messagesToAdd.map {
NotificationCompat.MessagingStyle.Message(
it.text,
it.date.time,
if (it.isIncoming)
Person.Builder()
.setName(contactName)
.setKey(contact)
.setIcon(adaptiveIcon)
.setUri("tel:${it.contact}")
.build()
else null
)
}
for (message in notificationMessages) {
style.addMessage(message)
}
notification.setShowWhen(true)
notification.setWhen(messagesToAdd.last().date.time)
}
notificationMessages[conversationId] =
(style.historicMessages.toMutableList()
+ style.messages.toMutableList())
notification.setStyle(style)
// Mark as read button
val markReadIntent = MarkReadReceiver.getIntent(context, did, contact)
markReadIntent.component = ComponentName(
context, MarkReadReceiver::class.java
)
val markReadFlags =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE
} else {
PendingIntent.FLAG_CANCEL_CURRENT
}
val markReadPendingIntent = PendingIntent.getBroadcast(
context, (did + contact + "markRead").hashCode(),
markReadIntent, markReadFlags
)
val markReadAction = NotificationCompat.Action.Builder(
R.drawable.ic_drafts_toolbar_24dp,
context.getString(R.string.notifications_button_mark_read),
markReadPendingIntent
)
.setSemanticAction(
NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ
)
.setShowsUserInterface(false)
.build()
notification.addAction(markReadAction)
// Reply button
val replyIntent = SendMessageReceiver.getIntent(
context, did, contact
)
replyIntent.component = ComponentName(
context, SendMessageReceiver::class.java
)
val replyFlags = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_MUTABLE
} else {
PendingIntent.FLAG_CANCEL_CURRENT
}
val replyPendingIntent = PendingIntent.getBroadcast(
context, (did + contact + "reply").hashCode(),
replyIntent, replyFlags
)
val remoteInput = RemoteInput.Builder(
context.getString(
R.string.notifications_reply_key
)
)
.setLabel(context.getString(R.string.notifications_button_reply))
.build()
val replyActionBuilder = NotificationCompat.Action.Builder(
R.drawable.ic_reply_toolbar_24dp,
context.getString(R.string.notifications_button_reply),
replyPendingIntent
)
.setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
.setShowsUserInterface(false)
.setAllowGeneratedReplies(true)
.addRemoteInput(remoteInput)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
notification.addAction(replyActionBuilder.build())
} else {
notification.addInvisibleAction(replyActionBuilder.build())
// Inline reply is not supported, so just show the conversation
// activity
val visibleReplyIntent = Intent(
context,
ConversationActivity::class.java
)
visibleReplyIntent.putExtra(
context.getString(
R.string.conversation_did
), did
)
visibleReplyIntent.putExtra(
context.getString(
R.string.conversation_contact
), contact
)
visibleReplyIntent.putExtra(
context.getString(
R.string.conversation_extra_focus
), true
)
visibleReplyIntent.flags = Intent.FLAG_ACTIVITY_NEW_DOCUMENT
val visibleReplyFlags =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_MUTABLE
} else {
PendingIntent.FLAG_CANCEL_CURRENT
}
val visibleReplyPendingIntent = PendingIntent.getActivity(
context, (did + contact + "replyVisible").hashCode(),
visibleReplyIntent, visibleReplyFlags
)
val visibleReplyActionBuilder = NotificationCompat.Action.Builder(
R.drawable.ic_reply_toolbar_24dp,
context.getString(R.string.notifications_button_reply),
visibleReplyPendingIntent
)
.setSemanticAction(
NotificationCompat.Action.SEMANTIC_ACTION_REPLY
)
.setShowsUserInterface(true)
.addRemoteInput(remoteInput)
notification.addAction(visibleReplyActionBuilder.build())
}
// Group notification
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val groupNotification = NotificationCompat.Builder(context, channel)
groupNotification.setSmallIcon(R.drawable.ic_chat_toolbar_24dp)
groupNotification.setGroup(
context.getString(
R.string.notifications_group_key
)
)
groupNotification.setGroupSummary(true)
groupNotification.setAutoCancel(true)
groupNotification.setGroupAlertBehavior(
NotificationCompat.GROUP_ALERT_CHILDREN
)
val intent = Intent(context, ConversationsActivity::class.java)
val stackBuilder = TaskStackBuilder.create(context)
stackBuilder.addNextIntentWithParentStack(intent)
val groupFlags =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE
} else {
PendingIntent.FLAG_CANCEL_CURRENT
}
groupNotification.setContentIntent(
stackBuilder.getPendingIntent(
"group".hashCode(),
groupFlags
)
)
try {
NotificationManagerCompat.from(context).notify(
GROUP_NOTIFICATION_ID, groupNotification.build()
)
} catch (e: SecurityException) {
Toast.makeText(
context,
context.getString(R.string.notifications_security_error),
Toast.LENGTH_LONG
).show()
}
}
// Primary notification action
val intent = Intent(context, ConversationActivity::class.java)
intent.putExtra(
context.getString(
R.string.conversation_did
), did
)
intent.putExtra(
context.getString(
R.string.conversation_contact
), contact
)
val stackBuilder = TaskStackBuilder.create(context)
stackBuilder.addNextIntentWithParentStack(intent)
val primaryFlags =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE
} else {
PendingIntent.FLAG_CANCEL_CURRENT
}
notification.setContentIntent(
stackBuilder.getPendingIntent(
(did + contact).hashCode(),
primaryFlags
)
)
// Bubble
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val bubbleIntent = Intent(
context,
ConversationBubbleActivity::class.java
)
bubbleIntent.putExtra(
context.getString(
R.string.conversation_did
), did
)
bubbleIntent.putExtra(
context.getString(
R.string.conversation_contact
), contact
)
val bubbleFlags =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
PendingIntent.FLAG_MUTABLE
} else {
0
}
val bubblePendingIntent = PendingIntent.getActivity(
context, 0,
bubbleIntent, bubbleFlags
)
val bubbleMetadata =
NotificationCompat.BubbleMetadata.Builder(
bubblePendingIntent,
adaptiveIcon
)
.setDesiredHeight(600)
.setSuppressNotification(bubbleOnly)
.setAutoExpandBubble(autoLaunchBubble)
.build()
notification.bubbleMetadata = bubbleMetadata
}
// Notification ID
var id = notificationIds[conversationId]
if (id == null) {
id = notificationIdCount++
if (notificationIdCount == Int.MAX_VALUE) {
notificationIdCount = MESSAGE_START_NOTIFICATION_ID
}
notificationIds[conversationId] = id
}
try {
NotificationManagerCompat.from(context).notify(
id, notification.build()
)
} catch (e: SecurityException) {
logException(e)
}
}
/**
* Cancels the notification associated with the specified conversation ID.
*/
fun cancelNotification(conversationId: ConversationId) {
val id = notificationIds[conversationId] ?: return
NotificationManagerCompat.from(context).cancel(id)
clearNotificationState(conversationId)
}
/**
* Clears our internal state associated with a notification, cancelling
* the group notification if required.
*/
fun clearNotificationState(conversationId: ConversationId) {
notificationMessages.remove(conversationId)
validateGroupNotification()
}
/**
* Gets the notification channel ID for the provided DID and contact. The
* channel is guaranteed to exist.
*/
private fun getNotificationChannelId(did: String, contact: String): String {
createDefaultNotificationChannel()
return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
// Prior to Android O, this doesn't matter.
context.getString(R.string.notifications_channel_default)
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
// Prior to Android R, conversations did not have a separate
// section in the notification settings, so we only create the
// conversation specific channel if the user requested it.
val channel = notificationManager.getNotificationChannel(
context.getString(
R.string.notifications_channel_contact,
did, contact
)
)
if (channel == null) {
context.getString(R.string.notifications_channel_default)
} else {
context.getString(
R.string.notifications_channel_contact,
did, contact
)
}
} else {
// As of Android R, conversations have a separate section in the
// notification settings, so we always create the conversation
// specific channel.
createDidNotificationChannel(did, contact)
context.getString(
R.string.notifications_channel_contact,
did, contact
)
}
}
/**
* Cancels the group notification if required.
*/
private fun validateGroupNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val noOtherNotifications = notificationManager.activeNotifications
.filter {
it.id != SYNC_DATABASE_NOTIFICATION_ID
&& it.id != SYNC_SEND_MESSAGE_NOTIFICATION_ID
&& it.id != SYNC_VERIFY_CREDENTIALS_NOTIFICATION_ID
&& it.id != SYNC_RETRIEVE_DIDS_NOTIFICATION_ID
&& it.id != SYNC_REGISTER_PUSH_NOTIFICATION_ID
&& it.id != GROUP_NOTIFICATION_ID
}
.none()
if (noOtherNotifications) {
NotificationManagerCompat.from(context).cancel(
GROUP_NOTIFICATION_ID
)
}
}
}
companion object {
// It is not a leak to store an instance to the application context,
// since it has the same lifetime as the application itself
@SuppressLint("StaticFieldLeak")
private var instance: Notifications? = null
// Notification ID for the database synchronization notification.
const val SYNC_DATABASE_NOTIFICATION_ID = 1
// Notification ID for the send message notification.
const val SYNC_SEND_MESSAGE_NOTIFICATION_ID =
SYNC_DATABASE_NOTIFICATION_ID + 1
// Notification ID for the verify credentials notification.
const val SYNC_VERIFY_CREDENTIALS_NOTIFICATION_ID =
SYNC_SEND_MESSAGE_NOTIFICATION_ID + 1
// Notification ID for the retrieve DIDs notification.
const val SYNC_RETRIEVE_DIDS_NOTIFICATION_ID =
SYNC_VERIFY_CREDENTIALS_NOTIFICATION_ID + 1
// Notification ID for the register for push notifications notification.
const val SYNC_REGISTER_PUSH_NOTIFICATION_ID =
SYNC_RETRIEVE_DIDS_NOTIFICATION_ID + 1
// Notification ID for the group notification, which contains all other
// notifications
const val GROUP_NOTIFICATION_ID = SYNC_REGISTER_PUSH_NOTIFICATION_ID + 1
// Starting notification ID for ordinary message notifications
const val MESSAGE_START_NOTIFICATION_ID = GROUP_NOTIFICATION_ID + 1
/**
* Gets the sole instance of the Notifications class. Initializes the
* instance if it does not already exist.
*/
fun getInstance(context: Context): Notifications =
instance ?: synchronized(this) {
instance ?: Notifications(
context.applicationContext
).also { instance = it }
}
}
}
| voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/notifications/Notifications.kt | 3226059471 |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.vcs.log.graph.impl
import com.intellij.vcs.log.graph.api.LinearGraph
import com.intellij.vcs.log.graph.api.LiteLinearGraph
import com.intellij.vcs.log.graph.collapsing.FragmentGenerator
import com.intellij.vcs.log.graph.graph
import com.intellij.vcs.log.graph.utils.LinearGraphUtils
import org.junit.Assert.assertEquals
import org.junit.Test
private val LinearGraph.lite: LiteLinearGraph get() = LinearGraphUtils.asLiteLinearGraph(this)
private fun LinearGraph.getMiddleNodes(upNode: Int, downNode: Int) = FragmentGenerator(lite) { false }.getMiddleNodes(upNode, downNode, false)
private infix fun Collection<Int>.assert(s: String) = assertEquals(s, sorted().joinToString(","))
private infix fun Int?.assert(i: Int?) = assertEquals(i, this)
private fun LinearGraph.redNodes(vararg redNode: Int = IntArray(0)): FragmentGenerator {
val redNodes = redNode.toSet()
return FragmentGenerator(lite) {
getNodeId(it) in redNodes
}
}
private val Int?.s: String get() = if (this == null) "n" else toString()
private infix fun FragmentGenerator.GreenFragment.assert(s: String)
= assertEquals(s, "${getUpRedNode().s}|${getDownRedNode().s}|${getMiddleGreenNodes().sorted().joinToString(",")}")
/*
0
|
1
|
2
*/
val simple = graph {
0(1, 2)
1(2)
2()
}
/*
0
| 1
|/
2
*/
val twoBranch = graph {
0(2)
1(2)
2()
}
/*
0
|\
1 2
|\|\
3 4 5
*/
val downTree = graph {
0(1, 2)
1(3, 4)
2(4, 5)
3()
4()
5()
}
/*
0 1 2
\/\/
3 4
\/
5
*/
val upTree = graph {
0(3)
1(3, 4)
2(4)
3(5)
4(5)
5()
}
/*
0
|\
| 1
2 |\
| | 3
| 4 |
|/ 5
6 /|
|\/ /
|7 /
\ /
8
*/
val difficult = graph {
0(1, 2)
1(3, 4)
2(6)
3(5)
4(6)
5(7, 8)
6(7, 8)
7()
8()
}
class FragmentGeneratorTest {
class MiddleNodesTest {
@Test fun simple() = simple.getMiddleNodes(0, 2) assert "0,1,2"
@Test fun empty() = twoBranch.getMiddleNodes(0, 1) assert ""
@Test fun withDownRedundantBranches() = downTree.getMiddleNodes(0, 4) assert "0,1,2,4"
@Test fun withUpRedundantBranches() = upTree.getMiddleNodes(1, 5) assert "1,3,4,5"
@Test fun difficult1() = difficult.getMiddleNodes(1, 7) assert "1,3,4,5,6,7"
@Test fun difficult2() = difficult.getMiddleNodes(0, 5) assert "0,1,3,5"
@Test fun difficult3() = difficult.getMiddleNodes(1, 8) assert "1,3,4,5,6,8"
}
class NearRedNode {
@Test fun simple1() = simple.redNodes(0).getNearRedNode(2, 10, true) assert 0
@Test fun simple2() = simple.redNodes(2).getNearRedNode(0, 10, false) assert 2
@Test fun simple3() = simple.redNodes(2, 1).getNearRedNode(0, 10, false) assert 1
@Test fun simple4() = simple.redNodes(0, 1).getNearRedNode(0, 10, false) assert 0
@Test fun simple5() = simple.redNodes(0, 1).getNearRedNode(2, 10, true) assert 1
@Test fun downTree1() = downTree.redNodes(4, 5).getNearRedNode(0, 10, false) assert 4
@Test fun downTree2() = downTree.redNodes(2, 3).getNearRedNode(0, 10, false) assert 2
@Test fun upTree1() = upTree.redNodes(1, 2).getNearRedNode(5, 10, true) assert 2
@Test fun upTree2() = upTree.redNodes(4, 0).getNearRedNode(5, 10, true) assert 4
@Test fun difficult1() = difficult.redNodes(4, 5, 6).getNearRedNode(0, 10, false) assert 4
@Test fun difficult2() = difficult.redNodes(2, 5, 6).getNearRedNode(1, 10, false) assert 5
@Test fun nullAnswer1() = difficult.redNodes(8).getNearRedNode(0, 6, false) assert null
@Test fun nullAnswer2() = difficult.redNodes(8).getNearRedNode(0, 7, false) assert 8
}
class GreenFragment {
@Test fun simple1() = simple.redNodes(0).getGreenFragmentForCollapse(2, 10) assert "0|n|1,2"
@Test fun simple2() = simple.redNodes(0, 2).getGreenFragmentForCollapse(1, 10) assert "0|2|1"
@Test fun simple3() = simple.redNodes(0, 2).getGreenFragmentForCollapse(0, 10) assert "n|n|"
@Test fun downTree1() = downTree.redNodes(4).getGreenFragmentForCollapse(2, 10) assert "n|4|0,2"
@Test fun downTree2() = downTree.redNodes(4).getGreenFragmentForCollapse(1, 10) assert "n|4|0,1"
@Test fun difficult1() = difficult.redNodes(1, 7).getGreenFragmentForCollapse(3, 10) assert "1|7|3,5"
@Test fun difficult2() = difficult.redNodes(1, 7).getGreenFragmentForCollapse(8, 10) assert "1|n|3,4,5,6,8"
@Test fun difficult3() = difficult.redNodes(1, 7).getGreenFragmentForCollapse(2, 10) assert "n|7|0,2,6"
}
} | platform/vcs-log/graph/test/com/intellij/vcs/log/graph/impl/FragmentGeneratorTest.kt | 3671449648 |
// 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 com.intellij.codeInspection.incorrectFormatting
import com.intellij.codeHighlighting.HighlightDisplayLevel
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ui.InspectionOptionsPanel
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.lang.LangBundle
import com.intellij.lang.Language
import com.intellij.lang.injection.InjectedLanguageManager
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
val INSPECTION_KEY = Key.create<IncorrectFormattingInspection>(IncorrectFormattingInspection().shortName)
class IncorrectFormattingInspection(
@JvmField var reportPerFile: Boolean = false, // generate only one warning per file
@JvmField var kotlinOnly: Boolean = false // process kotlin files normally even in silent mode, compatibility
) : LocalInspectionTool() {
val isKotlinPlugged: Boolean by lazy { PluginManagerCore.getPlugin(PluginId.getId("org.jetbrains.kotlin")) != null }
override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? {
// Skip files we are not able to fix
if (!file.isWritable) return null
// Skip injections
val host = InjectedLanguageManager.getInstance(file.project).getInjectionHost(file)
if (host != null) {
return null
}
// Perform only for main PSI tree
val baseLanguage: Language = file.viewProvider.baseLanguage
val mainFile = file.viewProvider.getPsi(baseLanguage)
if (file != mainFile) {
return null
}
if (isKotlinPlugged && kotlinOnly && file.language.id != "kotlin") {
return null
}
val document = PsiDocumentManager.getInstance(file.project).getDocument(file) ?: return null
val scope = CheckingScope(file, document, manager, isOnTheFly)
val changes = scope
.getChanges()
.takeIf { it.isNotEmpty() }
?: return null
return if (reportPerFile) {
arrayOf(scope.createGlobalReport())
}
else {
scope.createAllReports(changes)
}
}
override fun createOptionsPanel() = object : InspectionOptionsPanel(this) {
init {
addCheckbox(LangBundle.message("inspection.incorrect.formatting.setting.report.per.file"), "reportPerFile")
if (isKotlinPlugged) {
addCheckbox(LangBundle.message("inspection.incorrect.formatting.setting.kotlin.only"), "kotlinOnly")
}
}
}
override fun runForWholeFile() = true
override fun getDefaultLevel(): HighlightDisplayLevel = HighlightDisplayLevel.WEAK_WARNING
override fun isEnabledByDefault() = false
}
| platform/lang-impl/src/com/intellij/codeInspection/incorrectFormatting/IncorrectFormattingInspection.kt | 413946656 |
// "Replace with 'newFun(p2)'" "true"
// WITH_STDLIB
@Deprecated("", ReplaceWith("newFun(p2)"))
fun oldFun(p1: Int, p2: Int): Boolean {
return newFun(p2)
}
fun newFun(p: Int) = false
fun foo(list: List<Int>) {
list.filter { !<caret>oldFun(bar(), it) }
}
fun bar(): Int = 0
| plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/argumentSideEffects/complexExpressionNotUsed5Runtime.kt | 991937204 |
package com.intellij.workspaceModel.storage.bridgeEntities.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.PersistentEntityId
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.SoftLinkable
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class FacetEntityImpl: FacetEntity, WorkspaceEntityBase() {
companion object {
internal val MODULE_CONNECTION_ID: ConnectionId = ConnectionId.create(ModuleEntity::class.java, FacetEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, false)
internal val UNDERLYINGFACET_CONNECTION_ID: ConnectionId = ConnectionId.create(FacetEntity::class.java, FacetEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true)
val connections = listOf<ConnectionId>(
MODULE_CONNECTION_ID,
UNDERLYINGFACET_CONNECTION_ID,
)
}
@JvmField var _name: String? = null
override val name: String
get() = _name!!
override val module: ModuleEntity
get() = snapshot.extractOneToManyParent(MODULE_CONNECTION_ID, this)!!
@JvmField var _facetType: String? = null
override val facetType: String
get() = _facetType!!
@JvmField var _configurationXmlTag: String? = null
override val configurationXmlTag: String?
get() = _configurationXmlTag
@JvmField var _moduleId: ModuleId? = null
override val moduleId: ModuleId
get() = _moduleId!!
override val underlyingFacet: FacetEntity?
get() = snapshot.extractOneToManyParent(UNDERLYINGFACET_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: FacetEntityData?): ModifiableWorkspaceEntityBase<FacetEntity>(), FacetEntity.Builder {
constructor(): this(FacetEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity FacetEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isNameInitialized()) {
error("Field FacetEntity#name should be initialized")
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field FacetEntity#entitySource should be initialized")
}
if (_diff != null) {
if (_diff.extractOneToManyParent<WorkspaceEntityBase>(MODULE_CONNECTION_ID, this) == null) {
error("Field FacetEntity#module should be initialized")
}
}
else {
if (this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] == null) {
error("Field FacetEntity#module should be initialized")
}
}
if (!getEntityData().isFacetTypeInitialized()) {
error("Field FacetEntity#facetType should be initialized")
}
if (!getEntityData().isModuleIdInitialized()) {
error("Field FacetEntity#moduleId should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var name: String
get() = getEntityData().name
set(value) {
checkModificationAllowed()
getEntityData().name = value
changedProperty.add("name")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var module: ModuleEntity
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(MODULE_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleEntity
} else {
this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)]!! as ModuleEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(MODULE_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, MODULE_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, MODULE_CONNECTION_ID)] = value
}
changedProperty.add("module")
}
override var facetType: String
get() = getEntityData().facetType
set(value) {
checkModificationAllowed()
getEntityData().facetType = value
changedProperty.add("facetType")
}
override var configurationXmlTag: String?
get() = getEntityData().configurationXmlTag
set(value) {
checkModificationAllowed()
getEntityData().configurationXmlTag = value
changedProperty.add("configurationXmlTag")
}
override var moduleId: ModuleId
get() = getEntityData().moduleId
set(value) {
checkModificationAllowed()
getEntityData().moduleId = value
changedProperty.add("moduleId")
}
override var underlyingFacet: FacetEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(UNDERLYINGFACET_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, UNDERLYINGFACET_CONNECTION_ID)] as? FacetEntity
} else {
this.entityLinks[EntityLink(false, UNDERLYINGFACET_CONNECTION_ID)] as? FacetEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, UNDERLYINGFACET_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, UNDERLYINGFACET_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(UNDERLYINGFACET_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, UNDERLYINGFACET_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, UNDERLYINGFACET_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, UNDERLYINGFACET_CONNECTION_ID)] = value
}
changedProperty.add("underlyingFacet")
}
override fun getEntityData(): FacetEntityData = result ?: super.getEntityData() as FacetEntityData
override fun getEntityClass(): Class<FacetEntity> = FacetEntity::class.java
}
}
class FacetEntityData : WorkspaceEntityData.WithCalculablePersistentId<FacetEntity>(), SoftLinkable {
lateinit var name: String
lateinit var facetType: String
var configurationXmlTag: String? = null
lateinit var moduleId: ModuleId
fun isNameInitialized(): Boolean = ::name.isInitialized
fun isFacetTypeInitialized(): Boolean = ::facetType.isInitialized
fun isModuleIdInitialized(): Boolean = ::moduleId.isInitialized
override fun getLinks(): Set<PersistentEntityId<*>> {
val result = HashSet<PersistentEntityId<*>>()
result.add(moduleId)
return result
}
override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
index.index(this, moduleId)
}
override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
// TODO verify logic
val mutablePreviousSet = HashSet(prev)
val removedItem_moduleId = mutablePreviousSet.remove(moduleId)
if (!removedItem_moduleId) {
index.index(this, moduleId)
}
for (removed in mutablePreviousSet) {
index.remove(this, removed)
}
}
override fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean {
var changed = false
val moduleId_data = if (moduleId == oldLink) {
changed = true
newLink as ModuleId
}
else {
null
}
if (moduleId_data != null) {
moduleId = moduleId_data
}
return changed
}
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<FacetEntity> {
val modifiable = FacetEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): FacetEntity {
val entity = FacetEntityImpl()
entity._name = name
entity._facetType = facetType
entity._configurationXmlTag = configurationXmlTag
entity._moduleId = moduleId
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun persistentId(): PersistentEntityId<*> {
return FacetId(name, facetType, moduleId)
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return FacetEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as FacetEntityData
if (this.name != other.name) return false
if (this.entitySource != other.entitySource) return false
if (this.facetType != other.facetType) return false
if (this.configurationXmlTag != other.configurationXmlTag) return false
if (this.moduleId != other.moduleId) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as FacetEntityData
if (this.name != other.name) return false
if (this.facetType != other.facetType) return false
if (this.configurationXmlTag != other.configurationXmlTag) return false
if (this.moduleId != other.moduleId) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + facetType.hashCode()
result = 31 * result + configurationXmlTag.hashCode()
result = 31 * result + moduleId.hashCode()
return result
}
} | platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/FacetEntityImpl.kt | 15879276 |
// 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.codeinsight.api.applicators
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt
import org.jetbrains.kotlin.analysis.api.analyzeWithReadAction
import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.util.application.runWriteActionIfPhysical
import org.jetbrains.kotlin.psi.KtElement
import kotlin.reflect.KClass
abstract class AbstractKotlinApplicatorBasedIntention<PSI : KtElement, INPUT : KotlinApplicatorInput>(
elementType: KClass<PSI>,
) : SelfTargetingIntention<PSI>(elementType.java, { "" }) {
abstract fun getApplicator(): KotlinApplicator<PSI, INPUT>
abstract fun getApplicabilityRange(): KotlinApplicabilityRange<PSI>
abstract fun getInputProvider(): KotlinApplicatorInputProvider<PSI, INPUT>
init {
setFamilyNameGetter { getApplicator().getFamilyName() }
}
final override fun isApplicableTo(element: PSI, caretOffset: Int): Boolean {
val project = element.project// TODO expensive operation, may require traversing the tree up to containing PsiFile
val applicator = getApplicator()
if (!applicator.isApplicableByPsi(element, project)) return false
val ranges = getApplicabilityRange().getApplicabilityRanges(element)
if (ranges.isEmpty()) return false
// An KotlinApplicabilityRange should be relative to the element, while `caretOffset` is absolute
val relativeCaretOffset = caretOffset - element.textRange.startOffset
if (ranges.none { it.containsOffset(relativeCaretOffset) }) return false
val input = getInput(element)
if (input != null && input.isValidFor(element)) {
val actionText = applicator.getActionName(element, input)
val familyName = applicator.getFamilyName()
setFamilyNameGetter { familyName }
setTextGetter { actionText }
return true
}
return false
}
final override fun applyTo(element: PSI, project: Project, editor: Editor?) {
val input = getInput(element) ?: return
if (input.isValidFor(element)) {
val applicator = getApplicator() // TODO reuse existing applicator
runWriteActionIfPhysical(element) {
applicator.applyTo(element, input, project, editor)
}
}
}
final override fun applyTo(element: PSI, editor: Editor?) {
applyTo(element, element.project, editor)
}
@OptIn(KtAllowAnalysisOnEdt::class)
private fun getInput(element: PSI): INPUT? = allowAnalysisOnEdt {
analyzeWithReadAction(element) {
with(getInputProvider()) { provideInput(element) }
}
}
}
| plugins/kotlin/code-insight/api/src/org/jetbrains/kotlin/idea/codeinsight/api/applicators/AbstractKotlinApplicatorBasedIntention.kt | 3347289268 |
package com.droidsmith.tireguide.extensions
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.util.Log
fun Activity.openExternalUrl(url: String) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
Log.e(Intent.ACTION_VIEW, "Intent could not be resolved to open external URL: $url", e)
}
}
fun Activity?.requireActivity(): Activity =
this ?: throw IllegalStateException("Activity is null. View may not be attached.") | tireguide/src/main/java/com/droidsmith/tireguide/extensions/ActivityExtensions.kt | 1494359411 |
/**
* Copyright 2016 Stealth2800 <http://stealthyone.com/>
* Copyright 2016 Contributors <https://github.com/FlexSeries>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.st28.flexseries.flexlib.util
import org.bukkit.Bukkit
import org.bukkit.plugin.java.JavaPlugin
object SchedulerUtils {
fun runSync(plugin: JavaPlugin, function: () -> Unit) {
if (Bukkit.isPrimaryThread()) {
function.invoke()
} else {
Bukkit.getScheduler().runTask(plugin, function)
}
}
fun runAsync(plugin: JavaPlugin, function: () -> Unit) {
if (Bukkit.isPrimaryThread()) {
Bukkit.getScheduler().runTaskAsynchronously(plugin, function)
} else {
function.invoke()
}
}
fun runAsap(plugin: JavaPlugin, function: () -> Unit, async: Boolean) {
if (async) {
runAsync(plugin, function)
} else {
runSync(plugin, function)
}
}
} | src/main/kotlin/me/st28/flexseries/flexlib/util/SchedulerUtils.kt | 2496254345 |
package org.snakeskin.auto
import org.snakeskin.executor.ExceptionHandlingRunnable
import org.snakeskin.executor.IExecutorTaskHandle
import org.snakeskin.measure.time.TimeMeasureSeconds
import org.snakeskin.runtime.SnakeskinRuntime
/**
* @author Cameron Earle
* @version 4/3/18
*/
object AutoManager {
private val executor = SnakeskinRuntime.primaryExecutor
private var autoTaskHandle: IExecutorTaskHandle? = null
private var wasRunning = false
private var time: TimeMeasureSeconds = TimeMeasureSeconds(0.0)
private var lastTime: TimeMeasureSeconds = TimeMeasureSeconds(0.0)
private var auto: AutoLoop = object : AutoLoop() {
override val rate = TimeMeasureSeconds(0.02)
override fun startTasks() {}
override fun stopTasks() {}
override fun entry(currentTime: TimeMeasureSeconds) {}
override fun action(currentTime: TimeMeasureSeconds, lastTime: TimeMeasureSeconds) {}
override fun exit(currentTime: TimeMeasureSeconds) {}
}
fun setAutoLoop(loop: AutoLoop) {
auto.stopTasks()
auto = loop
auto.startTasks()
}
private fun tick() {
time = SnakeskinRuntime.timestamp
if (auto.tick(time, lastTime)) {
stop()
}
lastTime = time
}
@Synchronized fun start() {
time = SnakeskinRuntime.timestamp
auto.entry(time)
wasRunning = true
lastTime = TimeMeasureSeconds(0.0)
autoTaskHandle = executor.schedulePeriodicTask(ExceptionHandlingRunnable(::tick), auto.rate)
}
@Synchronized fun stop() {
time = SnakeskinRuntime.timestamp
autoTaskHandle?.stopTask(true)
if (wasRunning) {
auto.exit(time)
}
wasRunning = false
}
} | SnakeSkin-FRC/src/main/kotlin/org/snakeskin/auto/AutoManager.kt | 3916206371 |
package net.squanchy.wificonfig
enum class WifiConfigOrigin(val rawOrigin: String) {
ONBOARDING("onboarding"),
SETTINGS("settings")
}
| app/src/main/java/net/squanchy/wificonfig/WifiConfigOrigin.kt | 4136599532 |
package com.gmail.htaihm.diceroller
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("com.gmail.htaihm.diceroller", appContext.packageName)
}
}
| android/udacity-kotlin/DiceRoller/app/src/androidTest/java/com/gmail/htaihm/diceroller/ExampleInstrumentedTest.kt | 1450353793 |
package net.squanchy.settings.preferences
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
import io.reactivex.Observable
fun showFavoritesInScheduleObservable(context: Context) =
context.defaultSharedPreferences.observeFlag("favorites_in_schedule_preference_key", false)
private val Context.defaultSharedPreferences
get() = PreferenceManager.getDefaultSharedPreferences(this)
private fun SharedPreferences.observeFlag(key: String, defaultValue: Boolean = false): Observable<Boolean> = Observable.create { emitter ->
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, changedKey ->
if (key == changedKey) {
emitter.onNext(getBoolean(key, defaultValue))
}
}
emitter.onNext(getBoolean(key, defaultValue))
registerOnSharedPreferenceChangeListener(listener)
emitter.setCancellable { unregisterOnSharedPreferenceChangeListener(listener) }
}
| app/src/main/java/net/squanchy/settings/preferences/LocalPreferences.kt | 92658924 |
/*
* Copyright (C) 2018 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
* Copyright (C) 2015 Ericsson
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.efficios.jabberwocky.lttng.kernel.analysis.os.handlers
import ca.polymtl.dorsal.libdelorean.IStateSystemWriter
import ca.polymtl.dorsal.libdelorean.statevalue.StateValue
import com.efficios.jabberwocky.lttng.kernel.analysis.os.StateValues
import com.efficios.jabberwocky.lttng.kernel.trace.layout.LttngKernelEventLayout
import com.efficios.jabberwocky.trace.event.FieldValue.IntegerValue
import com.efficios.jabberwocky.trace.event.TraceEvent
class IrqEntryHandler(layout: LttngKernelEventLayout) : KernelEventHandler(layout) {
override fun handleEvent(ss: IStateSystemWriter, event: TraceEvent) {
val cpu = event.cpu
val timestamp = event.timestamp
val irqId = (event.fields[layout.fieldIrq] as IntegerValue).value
/*
* Mark this IRQ as active in the resource tree.
*/
ss.modifyAttribute(timestamp,
StateValue.newValueInt(StateValues.CPU_STATUS_IRQ),
ss.getQuarkRelativeAndAdd(ss.getNodeIRQs(cpu), irqId.toString()))
/* Change the status of the running process to interrupted */
ss.getCurrentThreadNode(cpu)?.let {
ss.modifyAttribute(timestamp,
StateValues.PROCESS_STATUS_INTERRUPTED_VALUE,
it)
}
/* Change the status of the CPU to interrupted */
ss.modifyAttribute(timestamp,
StateValues.CPU_STATUS_IRQ_VALUE,
ss.getCPUNode(cpu))
}
}
| jabberwocky-lttng/src/main/kotlin/com/efficios/jabberwocky/lttng/kernel/analysis/os/handlers/IrqEntryHandler.kt | 2186218774 |
/*******************************************************************************
* 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.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.util
internal fun String?.nullIfBlank(): String? = if (isNullOrBlank()) null else this
private val nonWordCharacterRegex = "\\W".toRegex()
internal fun String.replaceNonWordCharactersWithSpaces(): String = replace(nonWordCharacterRegex, " ")
internal fun String.makeBreakableAroundNonWordCharacters(): String = replace(nonWordCharacterRegex) {
"\u200B${it.value}\u200B" // Inserting zero-width spaces around
}
| plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/util/StringExtensions.kt | 274202582 |
// 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.intellij.build
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.common.Attributes
import io.opentelemetry.api.trace.Span
import kotlinx.collections.immutable.PersistentMap
import org.jetbrains.intellij.build.fus.FeatureUsageStatisticsProperties
import java.nio.file.Path
/**
* Describes proprietary tools which are used to build the product. Pass the instance of this class to {@link BuildContext#createContext} method.
*/
class ProprietaryBuildTools(
/**
* This tool is required to sign *.exe files in Windows distribution. If it is {@code null} the files won't be signed and Windows may show
* a warning when user tries to run them.
*/
val signTool: SignTool,
/**
* This tool is used to scramble the main product JAR file if {@link ProductProperties#scrambleMainJar} is {@code true}
*/
val scrambleTool: ScrambleTool?,
/**
* Describes address and credentials of Mac machine which is used to sign and build *.dmg installer for macOS. If {@code null} only *.sit
* archive will be built.
*/
val macHostProperties: MacHostProperties?,
/**
* Describes a server that can be used to download built artifacts to install plugins into IDE
*/
val artifactsServer: ArtifactsServer?,
/**
* Properties required to bundle a default version of feature usage statistics white list into IDE
*/
val featureUsageStatisticsProperties: FeatureUsageStatisticsProperties?,
/**
* Generation of shared indexes and other tasks may require a valid license to run,
* specify the license server URL to avoid hard-coding any license.
*/
val licenseServerHost: String?
) {
companion object {
val DUMMY = ProprietaryBuildTools(
signTool = object : SignTool {
override val usePresignedNativeFiles: Boolean
get() = false
override suspend fun signFiles(files: List<Path>, context: BuildContext?, options: PersistentMap<String, String>) {
Span.current().addEvent("files won't be signed", Attributes.of(
AttributeKey.stringArrayKey("files"), files.map(Path::toString),
AttributeKey.stringKey("reason"), "sign tool isn't defined",
))
}
override suspend fun getPresignedLibraryFile(path: String, libName: String, libVersion: String, context: BuildContext): Path? {
error("Must be not called if usePresignedNativeFiles is false")
}
override suspend fun commandLineClient(context: BuildContext, os: OsFamily, arch: JvmArchitecture): Path? {
return null
}
},
scrambleTool = null,
macHostProperties = null,
artifactsServer = null,
featureUsageStatisticsProperties = null,
licenseServerHost = null
)
}
}
| platform/build-scripts/src/org/jetbrains/intellij/build/ProprietaryBuildTools.kt | 3666106350 |
// WITH_STDLIB
val s = ""
val empty = s<caret>.isNullOrEmpty() | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/uselessCallOnNotNull/NullOrEmpty.kt | 1217732113 |
// 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.codeInspection.inspectionProfile
import com.intellij.codeHighlighting.HighlightDisplayLevel
import com.intellij.codeInspection.ex.InspectionProfileImpl
import com.intellij.codeInspection.ex.InspectionToolRegistrar
import com.intellij.codeInspection.ex.InspectionToolWrapper
import com.intellij.openapi.project.Project
import com.intellij.profile.codeInspection.PROFILE_DIR
import com.intellij.profile.codeInspection.ProjectInspectionProfileManager
import com.intellij.psi.PsiElement
import com.intellij.psi.search.scope.packageSet.NamedScope
import com.intellij.psi.search.scope.packageSet.PackageSetFactory
import org.jdom.Element
import java.io.File
import java.lang.IllegalArgumentException
class YamlInspectionConfigImpl(override val inspection: String,
override val enabled: Boolean?,
override val severity: String?,
override val ignore: List<String>,
override val options: Map<String, *>) : YamlInspectionConfig
class YamlGroupConfigImpl(override val group: String,
override val enabled: Boolean?,
override val severity: String?,
override val ignore: List<String>) : YamlGroupConfig
class YamlInspectionGroupImpl(override val groupId: String, val inspections: Set<String>) : YamlInspectionGroup {
override fun includesInspection(tool: InspectionToolWrapper<*, *>): Boolean {
return tool.shortName in inspections
}
}
class YamlCompositeGroupImpl(override val groupId: String,
private val groupProvider: InspectionGroupProvider,
private val groupRules: List<String>) : YamlInspectionGroup {
override fun includesInspection(tool: InspectionToolWrapper<*, *>): Boolean {
for (groupRule in groupRules.asReversed()) {
val groupId = groupRule.removePrefix("!")
if (groupProvider.findGroup(groupId).includesInspection(tool)) {
return groupId == groupRule
}
}
return false
}
}
class CompositeGroupProvider : InspectionGroupProvider {
private val providers = mutableListOf<InspectionGroupProvider>()
fun addProvider(groupProvider: InspectionGroupProvider) {
providers.add(groupProvider)
}
override fun findGroup(groupId: String): YamlInspectionGroup {
return object: YamlInspectionGroup {
override val groupId: String = groupId
override fun includesInspection(tool: InspectionToolWrapper<*, *>): Boolean {
return providers.any { it.findGroup(groupId)?.includesInspection(tool) == true }
}
}
}
}
class YamlInspectionProfileImpl private constructor(override val profileName: String?,
override val baseProfile: InspectionProfileImpl,
override val configurations: List<YamlBaseConfig>,
override val groups: List<YamlInspectionGroup>,
private val groupProvider: InspectionGroupProvider) : YamlInspectionProfile, InspectionGroupProvider {
companion object {
@JvmStatic
fun loadFrom(project: Project, filepath: String = "${getDefaultProfileDirectory(project)}/profile.yaml"): YamlInspectionProfileImpl {
val profile = readConfig(project, filepath)
val baseProfile = findBaseProfile(project, profile.baseProfile)
val configurations = profile.inspections.map(::createInspectionConfig)
val groupProvider = CompositeGroupProvider()
groupProvider.addProvider(InspectionGroupProvider.createDynamicGroupProvider())
val groups = profile.groups.map { group -> createGroup(groupProvider, group) }
val customGroupProvider = object : InspectionGroupProvider {
val groupMap = groups.associateBy { group -> group.groupId }
override fun findGroup(groupId: String): YamlInspectionGroup? {
return groupMap[groupId]
}
}
groupProvider.addProvider(customGroupProvider)
return YamlInspectionProfileImpl(profile.name, baseProfile, configurations, groups, groupProvider)
}
private fun findBaseProfile(project: Project, profileName: String?): InspectionProfileImpl {
return profileName
?.let { ProjectInspectionProfileManager.getInstance(project).getProfile(profileName, false) }
?: InspectionProfileImpl("Default")
}
@JvmStatic
fun isYamlFile(filepath: String): Boolean {
val extension = File(filepath).extension
return extension == "yaml" || extension == "yml"
}
private fun createGroup(groupProvider: InspectionGroupProvider, group: YamlInspectionGroupRaw): YamlInspectionGroup {
return if (group.groups.isNotEmpty()) {
YamlCompositeGroupImpl(group.groupId, groupProvider, group.groups)
}
else {
YamlInspectionGroupImpl(group.groupId, group.inspections.toSet())
}
}
private fun getDefaultProfileDirectory(project: Project): String = "${project.basePath}/${Project.DIRECTORY_STORE_FOLDER}/$PROFILE_DIR"
private fun createInspectionConfig(config: YamlInspectionConfigRaw): YamlBaseConfig {
val inspectionId = config.inspection
if (inspectionId != null) {
return YamlInspectionConfigImpl(inspectionId, config.enabled, config.severity, config.ignore,
config.options ?: emptyMap<String, Any>())
}
val groupId = config.group
if (groupId != null) {
return YamlGroupConfigImpl(groupId, config.enabled, config.severity, config.ignore)
}
throw IllegalArgumentException("Missing group or inspection id in the inspection configuration.")
}
}
fun buildEffectiveProfile(): InspectionProfileImpl {
val effectiveProfile: InspectionProfileImpl = InspectionProfileImpl("Default", InspectionToolRegistrar.getInstance(), baseProfile)
.also { profile ->
profile.initInspectionTools()
profile.copyFrom(baseProfile)
profile.name = profileName ?: "Default"
}
configurations.forEach { configuration ->
val tools = findTools(configuration)
val scopes = configuration.ignore.map { pattern ->
if (pattern.startsWith("!")) {
Pair(NamedScope.UnnamedScope(PackageSetFactory.getInstance().compile(pattern.drop(1))), true)
}
else {
Pair(NamedScope.UnnamedScope(PackageSetFactory.getInstance().compile(pattern)), false)
}
}
tools.asSequence().mapNotNull { tool -> effectiveProfile.getToolsOrNull(tool.shortName, null) }.forEach { inspectionTools ->
val enabled = configuration.enabled
if (enabled != null) {
inspectionTools.isEnabled = enabled
}
val severity = HighlightDisplayLevel.find(configuration.severity)
if (severity != null) {
inspectionTools.tools.forEach {
it.level = severity
}
}
val options = (configuration as? YamlInspectionConfig)?.options
if (options != null) {
val element = Element("tool")
ProfileMigrationUtils.writeXmlOptions(element, options)
inspectionTools.defaultState.tool.tool.readSettings(element)
}
scopes.forEach { (scope, enabled) ->
inspectionTools.prependTool(scope, inspectionTools.defaultState.tool, enabled, inspectionTools.level)
}
}
}
return effectiveProfile
}
private fun findTools(configuration: YamlBaseConfig): List<InspectionToolWrapper<*, *>> {
return when (configuration) {
is YamlGroupConfig -> baseProfile.getInspectionTools(null).filter { findGroup(configuration.group).includesInspection(it) }
is YamlInspectionConfig -> listOfNotNull(baseProfile.getInspectionTool(configuration.inspection, null as PsiElement?))
}
}
override fun findGroup(groupId: String): YamlInspectionGroup? {
return groupProvider.findGroup(groupId)
}
} | platform/inspect/src/com/intellij/codeInspection/inspectionProfile/YamlInspectionProfileImpl.kt | 837869241 |
interface Base {
fun foo(): Int
var bar: Int
val qux: Int
}
class Derived : Base {
override fun foo(): <error descr="[RETURN_TYPE_MISMATCH_ON_OVERRIDE] Return type of 'foo' is not a subtype of the return type of the overridden member 'foo'">String</error> = ""
override var bar: <error descr="[VAR_TYPE_MISMATCH_ON_OVERRIDE] Type of 'bar' doesn't match the type of the overridden var-property 'bar'">String</error> = ""
override val qux: <error descr="[PROPERTY_TYPE_MISMATCH_ON_OVERRIDE] Type of 'qux' is not a subtype of the overridden property 'qux'">String</error> = ""
}
| plugins/kotlin/idea/tests/testData/checker/ReturnTypeMismatchOnOverride.fir.kt | 104003583 |
package com.sevenander.timetable
import androidx.test.InstrumentationRegistry
import androidx.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumentation test, which will execute on an Android device.
*
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
@Throws(Exception::class)
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("com.sevenander.timetable", appContext.packageName)
}
}
| app/src/androidTest/java/com/sevenander/timetable/ExampleInstrumentedTest.kt | 2306571709 |
package org.thoughtcrime.securesms.conversation
import android.animation.LayoutTransition
class BodyBubbleLayoutTransition : LayoutTransition() {
init {
disableTransitionType(APPEARING)
disableTransitionType(DISAPPEARING)
disableTransitionType(CHANGE_APPEARING)
disableTransitionType(CHANGING)
setDuration(100L)
}
}
| app/src/main/java/org/thoughtcrime/securesms/conversation/BodyBubbleLayoutTransition.kt | 301682593 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.project.workspace
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import org.rust.cargo.toolchain.impl.CleanCargoMetadata
import org.rust.cargo.util.StdLibType
import java.util.*
import java.util.concurrent.atomic.AtomicReference
/**
* Rust project model represented roughly in the same way as in Cargo itself.
*
* [CargoProjectWorkspaceService] is responsible for providing a [CargoWorkspace] for
* an IDEA module.
*/
class CargoWorkspace private constructor(
val packages: Collection<Package>
) {
class Package(
private val contentRootUrl: String,
val name: String,
val version: String,
val targets: Collection<Target>,
val source: String?,
val origin: PackageOrigin
) {
val normName = name.replace('-', '_')
val dependencies: MutableList<Package> = ArrayList()
val libTarget: Target? get() = targets.find { it.isLib }
val contentRoot: VirtualFile? get() = VirtualFileManager.getInstance().findFileByUrl(contentRootUrl)
override fun toString() = "Package(contentRootUrl='$contentRootUrl', name='$name')"
fun initTargets(): Package {
targets.forEach { it.initPackage(this) }
return this
}
fun findCrateByName(normName: String): Target? =
if (this.normName == normName) libTarget else dependencies.findLibrary(normName)
}
class Target(
/**
* Absolute path to the crate root file
*/
internal val crateRootUrl: String,
val name: String,
val kind: TargetKind
) {
// target name must be a valid Rust identifier, so normalize it by mapping `-` to `_`
// https://github.com/rust-lang/cargo/blob/ece4e963a3054cdd078a46449ef0270b88f74d45/src/cargo/core/manifest.rs#L299
val normName = name.replace('-', '_')
val isLib: Boolean get() = kind == TargetKind.LIB
val isBin: Boolean get() = kind == TargetKind.BIN
val isExample: Boolean get() = kind == TargetKind.EXAMPLE
private val crateRootCache = AtomicReference<VirtualFile>()
val crateRoot: VirtualFile? get() {
val cached = crateRootCache.get()
if (cached != null && cached.isValid) return cached
val file = VirtualFileManager.getInstance().findFileByUrl(crateRootUrl)
crateRootCache.set(file)
return file
}
private lateinit var myPackage: Package
fun initPackage(pkg: Package) {
myPackage = pkg
}
val pkg: Package get() = myPackage
override fun toString(): String
= "Target(crateRootUrl='$crateRootUrl', name='$name', kind=$kind)"
}
enum class TargetKind {
LIB, BIN, TEST, EXAMPLE, BENCH, UNKNOWN
}
private val targetByCrateRootUrl = packages.flatMap { it.targets }.associateBy { it.crateRootUrl }
fun findCrateByNameApproximately(normName: String): Target? = packages.findLibrary(normName)
/**
* If the [file] is a crate root, returns the corresponding [Target]
*/
fun findTargetForCrateRootFile(file: VirtualFile): Target? {
val canonicalFile = file.canonicalFile ?: return null
return targetByCrateRootUrl[canonicalFile.url]
}
fun findPackage(name: String): Package? = packages.find { it.name == name }
fun isCrateRoot(file: VirtualFile): Boolean = findTargetForCrateRootFile(file) != null
fun withStdlib(libs: List<StandardLibrary.StdCrate>): CargoWorkspace {
val stdlib = libs.map { crate ->
val pkg = Package(
contentRootUrl = crate.packageRootUrl,
name = crate.name,
version = "",
targets = listOf(Target(crate.crateRootUrl, name = crate.name, kind = TargetKind.LIB)),
source = null,
origin = PackageOrigin.STDLIB
).initTargets()
(crate.name to pkg)
}.toMap()
// Bind dependencies and collect roots
val roots = ArrayList<Package>()
val featureGated = ArrayList<Package>()
libs.forEach { lib ->
val slib = stdlib[lib.name] ?: error("Std lib ${lib.name} not found")
val depPackages = lib.dependencies.mapNotNull { stdlib[it] }
slib.dependencies.addAll(depPackages)
if (lib.type == StdLibType.ROOT) {
roots.add(slib)
} else if (lib.type == StdLibType.FEATURE_GATED) {
featureGated.add(slib)
}
}
roots.forEach { it.dependencies.addAll(roots) }
packages.forEach { pkg ->
// Only add feature gated crates which names don't conflict with own dependencies
val packageFeatureGated = featureGated.filter { o -> pkg.dependencies.none { it.name == o.name } }
pkg.dependencies.addAll(roots + packageFeatureGated)
}
return CargoWorkspace(packages + roots)
}
val hasStandardLibrary: Boolean get() = packages.any { it.origin == PackageOrigin.STDLIB }
companion object {
fun deserialize(data: CleanCargoMetadata): CargoWorkspace {
// Packages form mostly a DAG. "Why mostly?", you say.
// Well, a dev-dependency `X` of package `P` can depend on the `P` itself.
// This is ok, because cargo can compile `P` (without `X`, because dev-deps
// are used only for tests), then `X`, and then `P`s tests. So we need to
// handle cycles here.
// Figure out packages origins:
// - if a package is a workspace member, or if it resides inside a workspace member directory, it's WORKSPACE
// - if a package is a direct dependency of a workspace member, it's DEPENDENCY
// - otherwise, it's TRANSITIVE_DEPENDENCY
val idToOrigin = HashMap<String, PackageOrigin>(data.packages.size)
val workspacePaths = data.packages
.filter { it.isWorkspaceMember }
.map { it.manifestPath.substringBeforeLast("Cargo.toml", "") }
.filter(String::isNotEmpty)
.toList()
data.packages.forEachIndexed pkgs@ { index, pkg ->
if (pkg.isWorkspaceMember || workspacePaths.any { pkg.manifestPath.startsWith(it) }) {
idToOrigin[pkg.id] = PackageOrigin.WORKSPACE
val depNode = data.dependencies.getOrNull(index) ?: return@pkgs
depNode.dependenciesIndexes
.mapNotNull { data.packages.getOrNull(it) }
.forEach {
idToOrigin.merge(it.id, PackageOrigin.DEPENDENCY, { o1, o2 -> PackageOrigin.min(o1, o2) })
}
} else {
idToOrigin.putIfAbsent(pkg.id, PackageOrigin.TRANSITIVE_DEPENDENCY)
}
}
val packages = data.packages.map { pkg ->
val origin = idToOrigin[pkg.id] ?: error("Origin is undefined for package ${pkg.name}")
Package(
pkg.url,
pkg.name,
pkg.version,
pkg.targets.map { Target(it.url, it.name, it.kind) },
pkg.source,
origin
).initTargets()
}.toList()
// Fill package dependencies
packages.forEachIndexed pkgs@ { index, pkg ->
val depNode = data.dependencies.getOrNull(index) ?: return@pkgs
pkg.dependencies.addAll(depNode.dependenciesIndexes.map { packages[it] })
}
return CargoWorkspace(packages)
}
}
}
private fun Collection<CargoWorkspace.Package>.findLibrary(normName: String): CargoWorkspace.Target? =
filter { it.normName == normName }
.mapNotNull { it.libTarget }
.firstOrNull()
| src/main/kotlin/org/rust/cargo/project/workspace/CargoWorkspace.kt | 2036744051 |
package io.ktor.utils.io.js
import io.ktor.utils.io.charsets.*
import io.ktor.utils.io.core.*
import org.khronos.webgl.*
@Deprecated(
"Use readText with charset instead",
ReplaceWith(
"readText(Charset.forName(encoding), max)",
"io.ktor.utils.io.core.readText",
"io.ktor.utils.io.charsets.Charset"
)
)
public fun ByteReadPacket.readText(encoding: String, max: Int = Int.MAX_VALUE): String =
readText(Charset.forName(encoding), max)
@Deprecated(
"Use readText with charset instead",
ReplaceWith(
"readText(out, Charset.forName(encoding), max)",
"io.ktor.utils.io.core.readText",
"io.ktor.utils.io.charsets.Charset"
)
)
public fun ByteReadPacket.readText(encoding: String = "UTF-8", out: Appendable, max: Int = Int.MAX_VALUE): Int {
return readText(out, Charset.forName(encoding), max)
}
internal inline fun <R> decodeWrap(block: () -> R): R {
try {
return block()
} catch (t: Throwable) {
throw MalformedInputException("Failed to decode bytes: ${t.message ?: "no cause provided"}")
}
}
| ktor-io/js/src/io/ktor/utils/io/js/TextDecoders.kt | 2695493935 |
package org.roylance.yaclib.core.services.typescript
import org.roylance.common.service.IBuilder
import org.roylance.yaclib.YaclibModel
import org.roylance.yaclib.core.enums.CommonTokens
import org.roylance.yaclib.core.utilities.StringUtilities
import org.roylance.yaclib.core.utilities.TypeScriptUtilities
class TypeScriptServiceBuilder(
private val controller: YaclibModel.Controller) : IBuilder<YaclibModel.File> {
override fun build(): YaclibModel.File {
val workspace = StringBuilder()
val interfaceName = StringUtilities.convertServiceNameToInterfaceName(controller)
val initialTemplate = """${CommonTokens.DoNotAlterMessage}
export interface $interfaceName {
"""
workspace.append(initialTemplate)
controller.actionsList.forEach { action ->
val colonSeparatedInputs = action.inputsList.map { input ->
"${input.argumentName}: ${input.filePackage}.${input.messageClass}"
}.joinToString()
val actionTemplate = "\t${action.name}($colonSeparatedInputs, onSuccess:(response: ${action.output.filePackage}.${action.output.messageClass})=>void, onError:(response:any)=>void)\n"
workspace.append(actionTemplate)
}
workspace.append("}")
val returnFile = YaclibModel.File.newBuilder()
.setFileToWrite(workspace.toString())
.setFileExtension(YaclibModel.FileExtension.TS_EXT)
.setFileName(interfaceName)
.setFullDirectoryLocation("")
.build()
return returnFile
}
} | core/src/main/java/org/roylance/yaclib/core/services/typescript/TypeScriptServiceBuilder.kt | 2582414823 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.