repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
google/intellij-community | platform/lang-impl/src/com/intellij/lang/documentation/impl/impl.kt | 2 | 8662 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("TestOnlyProblems") // KTIJ-19938
package com.intellij.lang.documentation.impl
import com.intellij.codeInsight.documentation.DocumentationManager
import com.intellij.lang.documentation.*
import com.intellij.lang.documentation.psi.psiDocumentationTarget
import com.intellij.model.Pointer
import com.intellij.model.psi.impl.mockEditor
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.readAction
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.component1
import com.intellij.openapi.util.component2
import com.intellij.psi.PsiFile
import com.intellij.util.AsyncSupplier
import com.intellij.util.SmartList
import kotlinx.coroutines.*
import org.jetbrains.annotations.ApiStatus.*
import org.jetbrains.annotations.TestOnly
@Internal // for Fleet
fun documentationTargets(file: PsiFile, offset: Int): List<DocumentationTarget> {
val targets = SmartList<DocumentationTarget>()
for (ext in DocumentationTargetProvider.EP_NAME.extensionList) {
targets.addAll(ext.documentationTargets(file, offset))
}
if (!targets.isEmpty()) {
return targets
}
// fallback to PSI
// TODO this fallback should be implemented inside DefaultTargetSymbolDocumentationTargetProvider, but first:
// - PsiSymbol has to hold information about origin element;
// - documentation target by argument list should be also implemented separately.
val editor = mockEditor(file) ?: return emptyList()
val documentationManager = DocumentationManager.getInstance(file.project)
val (targetElement, sourceElement) = documentationManager.findTargetElementAndContext(editor, offset, file)
?: return emptyList()
return listOf(psiDocumentationTarget(targetElement, sourceElement))
}
internal fun DocumentationTarget.documentationRequest(): DocumentationRequest {
ApplicationManager.getApplication().assertReadAccessAllowed()
return DocumentationRequest(createPointer(), presentation)
}
@Internal
fun CoroutineScope.computeDocumentationAsync(targetPointer: Pointer<out DocumentationTarget>): Deferred<DocumentationResultData?> {
return async(Dispatchers.Default) {
computeDocumentation(targetPointer)
}
}
internal suspend fun computeDocumentation(targetPointer: Pointer<out DocumentationTarget>): DocumentationResultData? {
return withContext(Dispatchers.Default) {
val documentationResult: DocumentationResult? = readAction {
targetPointer.dereference()?.computeDocumentation()
}
@Suppress("REDUNDANT_ELSE_IN_WHEN")
when (documentationResult) {
is DocumentationResultData -> documentationResult
is AsyncDocumentation -> documentationResult.supplier.invoke() as DocumentationResultData?
null -> null
else -> error("Unexpected result: $documentationResult") // this fixes Kotlin incremental compilation
}
}
}
@Internal
suspend fun handleLink(targetPointer: Pointer<out DocumentationTarget>, url: String): InternalLinkResult {
return withContext(Dispatchers.Default) {
tryResolveLink(targetPointer, url)
?: tryContentUpdater(targetPointer, url)
?: InternalLinkResult.CannotResolve
}
}
private suspend fun tryResolveLink(targetPointer: Pointer<out DocumentationTarget>, url: String): InternalLinkResult? {
return when (val resolveResult = resolveLink(targetPointer::dereference, url)) {
InternalResolveLinkResult.InvalidTarget -> InternalLinkResult.InvalidTarget
InternalResolveLinkResult.CannotResolve -> null
is InternalResolveLinkResult.Value -> InternalLinkResult.Request(resolveResult.value)
}
}
internal sealed class InternalResolveLinkResult<out X> {
object InvalidTarget : InternalResolveLinkResult<Nothing>()
object CannotResolve : InternalResolveLinkResult<Nothing>()
class Value<X>(val value: X) : InternalResolveLinkResult<X>()
}
/**
* @return `null` if [contextTarget] was invalidated, or [url] cannot be resolved
*/
@Internal // for Fleet
suspend fun resolveLinkToTarget(contextTarget: Pointer<out DocumentationTarget>, url: String): Pointer<out DocumentationTarget>? {
return when (val resolveLinkResult = resolveLink(contextTarget::dereference, url, DocumentationTarget::createPointer)) {
InternalResolveLinkResult.CannotResolve -> null
InternalResolveLinkResult.InvalidTarget -> null
is InternalResolveLinkResult.Value -> resolveLinkResult.value
}
}
internal suspend fun resolveLink(
targetSupplier: () -> DocumentationTarget?,
url: String,
): InternalResolveLinkResult<DocumentationRequest> {
return resolveLink(targetSupplier, url, DocumentationTarget::documentationRequest)
}
/**
* @param ram read action mapper - a function which would be applied to resolved [DocumentationTarget] while holding the read action
*/
internal suspend fun <X> resolveLink(
targetSupplier: () -> DocumentationTarget?,
url: String,
ram: (DocumentationTarget) -> X,
): InternalResolveLinkResult<X> {
val readActionResult = readAction {
resolveLinkInReadAction(targetSupplier, url, ram)
}
return when (readActionResult) {
is ResolveLinkInReadActionResult.Sync -> readActionResult.syncResult
is ResolveLinkInReadActionResult.Async -> asyncTarget(readActionResult.supplier, ram)
}
}
private suspend fun <X> asyncTarget(
supplier: AsyncSupplier<LinkResolveResult.Async?>,
ram: (DocumentationTarget) -> X,
): InternalResolveLinkResult<X> {
val asyncLinkResolveResult: LinkResolveResult.Async? = supplier.invoke()
if (asyncLinkResolveResult == null) {
return InternalResolveLinkResult.CannotResolve
}
when (asyncLinkResolveResult) {
is AsyncResolvedTarget -> {
val pointer = asyncLinkResolveResult.pointer
return readAction {
val target: DocumentationTarget? = pointer.dereference()
if (target == null) {
InternalResolveLinkResult.InvalidTarget
}
else {
InternalResolveLinkResult.Value(ram(target))
}
}
}
else -> error("Unexpected result: $asyncLinkResolveResult")
}
}
private sealed class ResolveLinkInReadActionResult<out X> {
class Sync<X>(val syncResult: InternalResolveLinkResult<X>) : ResolveLinkInReadActionResult<X>()
class Async(val supplier: AsyncSupplier<LinkResolveResult.Async?>) : ResolveLinkInReadActionResult<Nothing>()
}
private fun <X> resolveLinkInReadAction(
targetSupplier: () -> DocumentationTarget?,
url: String,
m: (DocumentationTarget) -> X,
): ResolveLinkInReadActionResult<X> {
val documentationTarget = targetSupplier()
?: return ResolveLinkInReadActionResult.Sync(InternalResolveLinkResult.InvalidTarget)
@Suppress("REDUNDANT_ELSE_IN_WHEN")
return when (val linkResolveResult: LinkResolveResult? = resolveLink(documentationTarget, url)) {
null -> ResolveLinkInReadActionResult.Sync(InternalResolveLinkResult.CannotResolve)
is ResolvedTarget -> ResolveLinkInReadActionResult.Sync(InternalResolveLinkResult.Value(m(linkResolveResult.target)))
is AsyncLinkResolveResult -> ResolveLinkInReadActionResult.Async(linkResolveResult.supplier)
else -> error("Unexpected result: $linkResolveResult") // this fixes Kotlin incremental compilation
}
}
private fun resolveLink(target: DocumentationTarget, url: String): LinkResolveResult? {
for (handler in DocumentationLinkHandler.EP_NAME.extensionList) {
ProgressManager.checkCanceled()
return handler.resolveLink(target, url) ?: continue
}
return null
}
private suspend fun tryContentUpdater(targetPointer: Pointer<out DocumentationTarget>, url: String): InternalLinkResult? {
return readAction {
contentUpdaterInReadAction(targetPointer, url)
}
}
private fun contentUpdaterInReadAction(targetPointer: Pointer<out DocumentationTarget>, url: String): InternalLinkResult? {
val target = targetPointer.dereference()
?: return InternalLinkResult.InvalidTarget
val updater = contentUpdater(target, url)
?: return null
return InternalLinkResult.Updater(updater)
}
private fun contentUpdater(target: DocumentationTarget, url: String): ContentUpdater? {
for (handler in DocumentationLinkHandler.EP_NAME.extensionList) {
ProgressManager.checkCanceled()
return handler.contentUpdater(target, url) ?: continue
}
return null
}
@TestOnly
fun computeDocumentationBlocking(targetPointer: Pointer<out DocumentationTarget>): DocumentationResultData? {
return runBlocking {
withTimeout(1000 * 60) {
computeDocumentation(targetPointer)
}
}
}
| apache-2.0 |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/MovePropertyToClassBodyIntention.kt | 1 | 4764 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.descriptors.annotations.KotlinTarget
import org.jetbrains.kotlin.idea.base.psi.mustHaveOnlyPropertiesInPrimaryConstructor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.psi.psiUtil.isPropertyParameter
import org.jetbrains.kotlin.resolve.AnnotationChecker
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class MovePropertyToClassBodyIntention : SelfTargetingIntention<KtParameter>(
KtParameter::class.java,
KotlinBundle.lazyMessage("move.to.class.body")
) {
override fun isApplicableTo(element: KtParameter, caretOffset: Int): Boolean {
if (!element.isPropertyParameter()) return false
val containingClass = element.containingClass() ?: return false
return !containingClass.mustHaveOnlyPropertiesInPrimaryConstructor()
}
override fun applyTo(element: KtParameter, editor: Editor?) {
val parentClass = PsiTreeUtil.getParentOfType(element, KtClass::class.java) ?: return
val propertyDeclaration = KtPsiFactory(element.project)
.createProperty("${element.valOrVarKeyword?.text} ${element.name} = ${element.name}")
val firstProperty = parentClass.getProperties().firstOrNull()
parentClass.addDeclarationBefore(propertyDeclaration, firstProperty).apply {
val propertyModifierList = element.modifierList?.copy() as? KtModifierList
propertyModifierList?.getModifier(KtTokens.VARARG_KEYWORD)?.delete()
propertyModifierList?.let { modifierList?.replace(it) ?: addBefore(it, firstChild) }
modifierList?.annotationEntries?.forEach {
if (!it.isAppliedToProperty()) {
it.delete()
} else if (it.useSiteTarget?.getAnnotationUseSiteTarget() == AnnotationUseSiteTarget.PROPERTY) {
it.useSiteTarget?.removeWithColon()
}
}
}
element.valOrVarKeyword?.delete()
val parameterAnnotationsText = element.modifierList?.annotationEntries
?.filter { it.isAppliedToConstructorParameter() }
?.takeIf { it.isNotEmpty() }
?.joinToString(separator = " ") { it.textWithoutUseSite() }
val hasVararg = element.hasModifier(KtTokens.VARARG_KEYWORD)
if (parameterAnnotationsText != null) {
element.modifierList?.replace(KtPsiFactory(element.project).createModifierList(parameterAnnotationsText))
} else {
element.modifierList?.delete()
}
if (hasVararg) element.addModifier(KtTokens.VARARG_KEYWORD)
}
private fun KtAnnotationEntry.isAppliedToProperty(): Boolean {
useSiteTarget?.getAnnotationUseSiteTarget()?.let {
return it == AnnotationUseSiteTarget.FIELD
|| it == AnnotationUseSiteTarget.PROPERTY
|| it == AnnotationUseSiteTarget.PROPERTY_GETTER
|| it == AnnotationUseSiteTarget.PROPERTY_SETTER
|| it == AnnotationUseSiteTarget.SETTER_PARAMETER
}
return !isApplicableToConstructorParameter()
}
private fun KtAnnotationEntry.isAppliedToConstructorParameter(): Boolean {
useSiteTarget?.getAnnotationUseSiteTarget()?.let {
return it == AnnotationUseSiteTarget.CONSTRUCTOR_PARAMETER
}
return isApplicableToConstructorParameter()
}
private fun KtAnnotationEntry.isApplicableToConstructorParameter(): Boolean {
val context = analyze(BodyResolveMode.PARTIAL)
val descriptor = context[BindingContext.ANNOTATION, this] ?: return false
val applicableTargets = AnnotationChecker.applicableTargetSet(descriptor)
return applicableTargets.contains(KotlinTarget.VALUE_PARAMETER)
}
private fun KtAnnotationEntry.textWithoutUseSite() = "@" + typeReference?.text.orEmpty() + valueArgumentList?.text.orEmpty()
private fun KtAnnotationUseSiteTarget.removeWithColon() {
nextSibling?.delete() // ':' symbol after use site
delete()
}
}
| apache-2.0 |
JetBrains/intellij-community | plugins/devkit/devkit-kotlin-tests/testData/inspections/getFamilyNameViolation/NotViolatedByGetName.kt | 1 | 467 | import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.QuickFix
import com.intellij.openapi.project.Project
class NotViolatedByGetName : QuickFix<ProblemDescriptor> {
private var someField: String? = null
override fun getName(): String {
return someField!!
}
override fun getFamilyName(): String {
return name + "123"
}
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
// any
}
}
| apache-2.0 |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/sdk/HaskellSdkType.kt | 1 | 9000 | package org.jetbrains.haskell.sdk
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.projectRoots.*
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VirtualFile
import org.jdom.Element
import org.jetbrains.annotations.Nullable
import org.jetbrains.haskell.icons.HaskellIcons
import org.jetbrains.haskell.util.ProcessRunner
import javax.swing.*
import java.io.File
import java.io.FileFilter
import java.io.FilenameFilter
import java.util.*
import org.jetbrains.haskell.util.GHCVersion
import org.jetbrains.haskell.util.GHCUtil
import org.jetbrains.haskell.sdk.HaskellSdkType.SDKInfo
import kotlin.text.Regex
class HaskellSdkType : SdkType("GHC") {
companion object {
private val WINDOWS_EXECUTABLE_SUFFIXES = arrayOf("cmd", "exe", "bat", "com")
val INSTANCE: HaskellSdkType = HaskellSdkType()
private val GHC_ICON: Icon = HaskellIcons.HASKELL
private fun getLatestVersion(ghcPaths: List<File>): SDKInfo? {
val length = ghcPaths.size
if (length == 0)
return null
if (length == 1)
return SDKInfo(ghcPaths[0])
val ghcDirs = ArrayList<SDKInfo>()
for (name in ghcPaths) {
ghcDirs.add(SDKInfo(name))
}
Collections.sort(ghcDirs, object : Comparator<SDKInfo> {
override fun compare(d1: SDKInfo, d2: SDKInfo): Int {
return d1.version.compareTo(d2.version)
}
})
return ghcDirs.get(ghcDirs.size - 1)
}
fun checkForGhc(path: String): Boolean {
val file = File(path)
if (file.isDirectory) {
val children = file.listFiles(object : FileFilter {
override fun accept(f: File): Boolean {
if (f.isDirectory)
return false
return f.name == "ghc"
}
})
return children.isNotEmpty()
} else {
return isGhc(file.name)
}
}
fun isGhc(name : String) : Boolean =
name == "ghc" || name.matches("ghc-[.0-9*]+".toRegex())
fun getGhcVersion(ghcPath: File): String? {
if (ghcPath.isDirectory) {
return null
}
try {
return ProcessRunner(null).executeOrFail(ghcPath.toString(), "--numeric-version").trim()
} catch (ex: Exception) {
// ignore
}
return null
}
}
class SDKInfo(val ghcPath: File) {
val version: GHCVersion = getVersion(ghcPath.name)
companion object {
fun getVersion(name: String?): GHCVersion {
val versionStr : List<String> = if (name == null) {
listOf<String>()
} else {
name.split("[^0-9]+".toRegex()).filter { !it.isEmpty() }
}
val parts = ArrayList<Int>()
for (part in versionStr) {
if (part.isEmpty())
continue
try {
parts.add(part.toInt())
} catch (nfex: NumberFormatException) {
// ignore
}
}
return GHCVersion(parts)
}
}
}
override fun getHomeChooserDescriptor(): FileChooserDescriptor {
val isWindows = SystemInfo.isWindows
return object : FileChooserDescriptor(true, false, false, false, false, false) {
@Throws(Exception::class)
override fun validateSelectedFiles(files: Array<VirtualFile>?) {
if (files!!.size != 0) {
if (!isValidSdkHome(files[0].path)) {
throw Exception("Not valid ghc " + files[0].name)
}
}
}
override fun isFileVisible(file: VirtualFile, showHiddenFiles: Boolean): Boolean {
if (!file.isDirectory) {
if (!file.name.toLowerCase().startsWith("ghc")) {
return false
}
if (isWindows) {
val path = file.path
var looksExecutable = false
for (ext in WINDOWS_EXECUTABLE_SUFFIXES) {
if (path.endsWith(ext)) {
looksExecutable = true
break
}
}
return looksExecutable && super.isFileVisible(file, showHiddenFiles)
}
}
return super.isFileVisible(file, showHiddenFiles)
}
}.withTitle("Select GHC executable").withShowHiddenFiles(SystemInfo.isUnix)
}
override fun suggestHomePath(): String? {
val versions: List<File>
if (SystemInfo.isLinux) {
val versionsRoot = File("/usr/bin")
if (!versionsRoot.isDirectory) {
return null
}
versions = (versionsRoot.listFiles(object : FilenameFilter {
override fun accept(dir: File, name: String): Boolean {
return !File(dir, name).isDirectory && isGhc(name.toLowerCase())
}
})?.toList() ?: listOf())
} else if (SystemInfo.isWindows) {
throw UnsupportedOperationException()
/*
var progFiles = System.getenv("ProgramFiles(x86)")
if (progFiles == null) {
progFiles = System.getenv("ProgramFiles")
}
if (progFiles == null)
return null
val versionsRoot = File(progFiles, "Haskell Platform")
if (!versionsRoot.isDirectory)
return progFiles
versions = versionsRoot.listFiles()?.toList() ?: listOf()
*/
} else if (SystemInfo.isMac) {
throw UnsupportedOperationException()
/*
val macVersions = ArrayList<File>()
val versionsRoot = File("/Library/Frameworks/GHC.framework/Versions/")
if (versionsRoot.isDirectory()) {
macVersions.addAll(versionsRoot.listFiles()?.toList() ?: listOf())
}
val brewVersionsRoot = File("/usr/local/Cellar/ghc")
if (brewVersionsRoot.isDirectory()) {
macVersions.addAll(brewVersionsRoot.listFiles()?.toList() ?: listOf())
}
versions = macVersions
*/
} else {
return null
}
val latestVersion = getLatestVersion(versions)
return latestVersion?.ghcPath?.absolutePath
}
override fun isValidSdkHome(path: String?): Boolean {
return checkForGhc(path!!)
}
override fun suggestSdkName(currentSdkName: String?, sdkHome: String?): String {
val suggestedName: String
if (currentSdkName != null && currentSdkName.length > 0) {
suggestedName = currentSdkName
} else {
val versionString = getVersionString(sdkHome)
if (versionString != null) {
suggestedName = "GHC " + versionString
} else {
suggestedName = "Unknown"
}
}
return suggestedName
}
override fun getVersionString(sdkHome: String?): String? {
if (sdkHome == null) {
return null
}
val versionString: String? = getGhcVersion(File(sdkHome))
if (versionString != null && versionString.length == 0) {
return null
}
return versionString
}
override fun createAdditionalDataConfigurable(sdkModel: SdkModel,
sdkModificator: SdkModificator): AdditionalDataConfigurable {
return HaskellSdkConfigurable()
}
override fun saveAdditionalData(additionalData: SdkAdditionalData, additional: Element) {
if (additionalData is HaskellSdkAdditionalData) {
additionalData.save(additional)
}
}
override fun loadAdditionalData(additional: Element?): SdkAdditionalData? {
return HaskellSdkAdditionalData.load(additional!!)
}
override fun getPresentableName(): String {
return "GHC"
}
override fun getIcon(): Icon {
return GHC_ICON
}
override fun getIconForAddAction(): Icon {
return icon
}
override fun setupSdkPaths(sdk: Sdk) {
}
override fun isRootTypeApplicable(rootType: OrderRootType): Boolean {
return false
}
}
| apache-2.0 |
exercism/xkotlin | exercises/practice/armstrong-numbers/src/test/kotlin/ArmstrongNumberTest.kt | 1 | 1170 | import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
import kotlin.test.assertFalse
class ArmstrongNumberTest {
@Test
fun `zero is an armstrong number`() = assertTrue(ArmstrongNumber.check(0))
@Test
fun `single digit numbers are armstrong numbers`() = assertTrue(ArmstrongNumber.check(5))
@Test
fun `there are no 2 digit armstrong numbers`() = assertFalse(ArmstrongNumber.check(10))
@Test
fun `three digit number that is an armstrong number`() = assertTrue(ArmstrongNumber.check(153))
@Test
fun `three digit number that is not an armstrong number`() = assertFalse(ArmstrongNumber.check(100))
@Test
fun `four digit number that is an armstrong number`() = assertTrue(ArmstrongNumber.check(9474))
@Test
fun `four digit number that is not an armstrong number`() = assertFalse(ArmstrongNumber.check(9475))
@Test
fun `seven digit number that is an armstrong number`() = assertTrue(ArmstrongNumber.check(9926315))
@Test
fun `seven digit number that is not an armstrong number`() = assertFalse(ArmstrongNumber.check(9926314))
}
| mit |
StepicOrg/stepik-android | model/src/main/java/org/stepik/android/model/StoryTemplate.kt | 2 | 4382 | package org.stepik.android.model
import android.os.Parcel
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
class StoryTemplate(
@SerializedName("id")
val id: Long,
@SerializedName("cover")
val cover: String,
@SerializedName("title")
val title: String,
@SerializedName("is_published")
val isPublished: Boolean,
@SerializedName("parts")
val parts: List<Part>,
@SerializedName("language")
val language: String,
@SerializedName("position")
val position: Int,
@SerializedName("version")
val version: Int
) {
class Part(
@SerializedName("duration")
val duration: Long,
@SerializedName("image")
val image: String,
@SerializedName("position")
val position: Int,
@SerializedName("type")
val type: String,
@SerializedName("feedback")
val feedback: Feedback?,
@SerializedName("button")
val button: Button?,
@SerializedName("text")
val text: Text?
)
class Text(
@SerializedName("background_style")
val backgroundStyle: String?,
@SerializedName("text")
val text: String?,
@SerializedName("text_color")
val textColor: String,
@SerializedName("title")
val title: String
) : Parcelable {
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(backgroundStyle)
parcel.writeString(text)
parcel.writeString(textColor)
parcel.writeString(title)
}
override fun describeContents(): Int = 0
companion object CREATOR : Parcelable.Creator<Text> {
override fun createFromParcel(parcel: Parcel) = Text(
parcel.readString(),
parcel.readString(),
parcel.readString()!!,
parcel.readString()!!
)
override fun newArray(size: Int) =
arrayOfNulls<Text?>(size)
}
}
class Button(
@SerializedName("background_color")
val backgroundColor: String,
@SerializedName("text_color")
val textColor: String,
@SerializedName("title")
val title: String,
@SerializedName("url")
val url: String,
@SerializedName("feedback_title")
val feedbackTitle: String?
) : Parcelable {
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(backgroundColor)
parcel.writeString(textColor)
parcel.writeString(title)
parcel.writeString(url)
parcel.writeString(feedbackTitle)
}
override fun describeContents(): Int = 0
companion object CREATOR : Parcelable.Creator<Button> {
override fun createFromParcel(parcel: Parcel) = Button(
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()!!,
parcel.readString()
)
override fun newArray(size: Int) =
arrayOfNulls<Button?>(size)
}
}
@Parcelize
data class Feedback(
@SerializedName("background_color")
val backgroundColor: String,
@SerializedName("text")
val text: String,
@SerializedName("text_color")
val textColor: String,
@SerializedName("icon_style")
val iconStyle: IconStyle,
@SerializedName("input_background_color")
val inputBackgroundColor: String,
@SerializedName("input_text_color")
val inputTextColor: String,
@SerializedName("placeholder_text")
val placeholderText: String,
@SerializedName("placeholder_text_color")
val placeholderTextColor: String
) : Parcelable {
enum class IconStyle(val style: String) {
@SerializedName("light")
LIGHT("light"),
@SerializedName("dark")
DARK("dark")
}
}
} | apache-2.0 |
allotria/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/importing/configurers/MavenEncodingConfigurer.kt | 3 | 4184 | /*
* 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.idea.maven.importing.configurers
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.encoding.EncodingProjectManager
import com.intellij.openapi.vfs.encoding.EncodingProjectManagerImpl
import org.jetbrains.idea.maven.project.MavenProject
import org.jetbrains.idea.maven.utils.MavenLog
import java.io.File
import java.nio.charset.Charset
import java.nio.charset.UnsupportedCharsetException
/**
* @author Sergey Evdokimov
*/
class MavenEncodingConfigurer : MavenModuleConfigurer() {
override fun configure(mavenProject: MavenProject, project: Project, module: Module) {
val newMap = LinkedHashMap<VirtualFile, Charset>()
val leaveAsIsMap = LinkedHashMap<VirtualFile, Charset>()
val projectManagerImpl = (EncodingProjectManager.getInstance(project) as EncodingProjectManagerImpl)
ReadAction.compute<Unit, Throwable> {
fillSourceEncoding(mavenProject, newMap, leaveAsIsMap, projectManagerImpl)
}
ReadAction.compute<Unit, Throwable> {
fillResourceEncoding(project, mavenProject, newMap, leaveAsIsMap, projectManagerImpl)
}
if (newMap.isEmpty()) {
return
}
newMap.putAll(leaveAsIsMap)
ApplicationManager.getApplication().invokeAndWait {
projectManagerImpl.setMapping(newMap)
}
}
private fun fillResourceEncoding(project: Project,
mavenProject: MavenProject,
newMap: LinkedHashMap<VirtualFile, Charset>,
leaveAsIsMap: LinkedHashMap<VirtualFile, Charset>,
projectManagerImpl: EncodingProjectManagerImpl) {
mavenProject.getResourceEncoding(project)?.let(this::getCharset)?.let { charset ->
mavenProject.resources.forEach { resource ->
val dirVfile = LocalFileSystem.getInstance().findFileByIoFile(File(resource.directory)) ?: return
newMap[dirVfile] = charset
projectManagerImpl.allMappings.forEach {
if (FileUtil.isAncestor(resource.directory, it.key.path, false)) {
newMap[it.key] = charset
}
else {
leaveAsIsMap[it.key] = it.value
}
}
}
}
}
private fun fillSourceEncoding(mavenProject: MavenProject,
newMap: LinkedHashMap<VirtualFile, Charset>,
leaveAsIsMap: LinkedHashMap<VirtualFile, Charset>,
projectManagerImpl: EncodingProjectManagerImpl) {
mavenProject.sourceEncoding?.let(this::getCharset)?.let { charset ->
mavenProject.sources.forEach { directory ->
val dirVfile = LocalFileSystem.getInstance().findFileByIoFile(File(directory)) ?: return
newMap[dirVfile] = charset
projectManagerImpl.allMappings.forEach {
if (FileUtil.isAncestor(directory, it.key.path, false)) {
newMap[it.key] = charset
}
else {
leaveAsIsMap[it.key] = it.value
}
}
}
}
}
private fun getCharset(name: String): Charset? {
try {
return Charset.forName(name)
}
catch (e: UnsupportedCharsetException) {
MavenLog.LOG.warn("Charset ${name} is not supported")
return null
}
}
}
| apache-2.0 |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/codeinsight/htl/annotator/HtlStringLiteralUtils.kt | 1 | 2145 | package com.aemtools.codeinsight.htl.annotator
import com.aemtools.lang.htl.psi.mixin.HtlStringLiteralMixin
/**
* Convert current string literal to singlequted string.
*
* @receiver [HtlStringLiteralMixin]
* @return singlequoted version of string literal
*/
fun HtlStringLiteralMixin.toSingleQuoted(): String {
return if (this.isDoubleQuoted()) {
text
// "input ' \" " -> 'input \' " '
// escape singlequotes inside the literal
.replace("\\'", "'")
.replace("'", "\\'")
// unescape doublequotes inside the literal
.replace("\\\"", "\"")
// swap quotes
.replaceFirst("\"", "'")
.replaceLast("\"", "'")
} else {
text
}
}
/**
* Convert current string literal to doublequoted string.
*
* @receiver [HtlStringLiteralMixin]
* @return doublequoted version of string literal
*/
fun HtlStringLiteralMixin.toDoubleQuoted(): String {
return if (!this.isDoubleQuoted()) {
text
// 'input " \' ' -> "input \" ' "
// escape doublequotes inside the literal
.replace("\\\"", "\"")
.replace("\"", "\\\"")
// unescape singlequotes inside the literal
.replace("\\'", "'")
// swap quotes
.replaceFirst("'", "\"")
.replaceLast("'", "\"")
} else {
text
}
}
/**
* Swap quotes of current [HtlStringLiteralMixin].
* Will return doublequoted for singlequoted and vice versa.
*
* @receiver [HtlStringLiteralMixin]
* @return string with swapped quote
*/
fun HtlStringLiteralMixin.swapQuotes(): String {
return if (this.isDoubleQuoted()) {
toSingleQuoted()
} else {
toDoubleQuoted()
}
}
/**
* Check if current [HtlStringLiteralMixin] is a doublequoted string.
*
* @receiver [HtlStringLiteralMixin]
* @return *true* if current string is doublequoted, *false* otherwise
*/
fun HtlStringLiteralMixin.isDoubleQuoted(): Boolean {
return this.text.startsWith("\"")
}
private fun String.replaceLast(oldValue: String, newValue: String, ignoreCase: Boolean = false): String =
reversed()
.replaceFirst(oldValue, newValue, ignoreCase)
.reversed()
| gpl-3.0 |
langerhans/discord-github-webhooks | src/main/kotlin/de/langerhans/discord/gitbot/util/GithubDateTypeAdapter.kt | 1 | 1741 | package de.langerhans.discord.gitbot.util
import com.google.gson.JsonSyntaxException
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
import java.io.IOException
import java.text.DateFormat
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
/**
* Adapted from http://stackoverflow.com/a/37438619
*/
class GithubDateTypeAdapter : TypeAdapter<Date>() {
private val iso8601Format = buildIso8601Format()
@Throws(IOException::class)
override fun read(reader: JsonReader): Date? {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull()
return null
}
return deserializeToDate(reader.nextString())
}
@Synchronized private fun deserializeToDate(json: String): Date {
try {
return iso8601Format.parse(json)
} catch (e: ParseException) {
try {
return Date(json.toLong())
} catch (e: NumberFormatException) {
throw JsonSyntaxException(json, e)
}
}
}
@Synchronized @Throws(IOException::class)
override fun write(out: JsonWriter, value: Date?) {
if (value == null) {
out.nullValue()
return
}
val dateFormatAsString = iso8601Format.format(value)
out.value(dateFormatAsString)
}
companion object {
private fun buildIso8601Format(): DateFormat {
val iso8601Format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US)
iso8601Format.timeZone = TimeZone.getTimeZone("UTC")
return iso8601Format
}
}
}
| mit |
ursjoss/sipamato | common/common-wicket/src/main/kotlin/ch/difty/scipamato/common/web/model/CodeClassLikeModel.kt | 2 | 1189 | package ch.difty.scipamato.common.web.model
import ch.difty.scipamato.common.entity.CodeClassLike
import ch.difty.scipamato.common.persistence.CodeClassLikeService
import org.apache.wicket.spring.injection.annot.SpringBean
/**
* Model used in core/public wicket pages to load [CodeClassLike] code class implementations
*
* @param [T] code class implementations of [CodeClassLike]
* @param [S] service implementations of [CodeClassLikeService]
*/
abstract class CodeClassLikeModel<T : CodeClassLike, in S : CodeClassLikeService<T>>(
private val languageCode: String,
) : InjectedLoadableDetachableModel<T>() {
@SpringBean
private lateinit var service: S
/**
* Protected constructor for testing without wicket application.
*
* @param languageCode the two character language code, e.g. 'en' or 'de'
* @param service the service to retrieve the code class like entities
*/
protected constructor(languageCode: String, service: S) : this(languageCode) {
this.service = service
}
public override fun load(): List<T> = service.find(languageCode)
companion object {
private const val serialVersionUID = 1L
}
}
| gpl-3.0 |
spring-projects/spring-framework | spring-webmvc/src/main/kotlin/org/springframework/web/servlet/function/RouterFunctionDsl.kt | 1 | 27951 | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.function
import org.springframework.core.io.Resource
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatusCode
import org.springframework.http.MediaType
import java.net.URI
import java.util.Optional
import java.util.function.Supplier
/**
* Allow to create easily a WebMvc.fn [RouterFunction] with a [Reactive router Kotlin DSL][RouterFunctionDsl].
*
* Example:
*
* ```
* @Configuration
* class RouterConfiguration {
*
* @Bean
* fun mainRouter(userHandler: UserHandler) = router {
* accept(TEXT_HTML).nest {
* (GET("/user/") or GET("/users/")).invoke(userHandler::findAllView)
* GET("/users/{login}", userHandler::findViewById)
* }
* accept(APPLICATION_JSON).nest {
* (GET("/api/user/") or GET("/api/users/")).invoke(userHandler::findAll)
* POST("/api/users/", userHandler::create)
* }
* }
*
* }
* ```
* @author Sebastien Deleuze
* @author Arjen Poutsma
* @since 5.2
*/
fun router(routes: (RouterFunctionDsl.() -> Unit)) = RouterFunctionDsl(routes).build()
/**
* Provide a WebMvc.fn [RouterFunction] Reactive Kotlin DSL created by [`router { }`][router] in order to be able to write idiomatic Kotlin code.
*
* @author Sebastien Deleuze
* @since 5.2
*/
class RouterFunctionDsl internal constructor (private val init: (RouterFunctionDsl.() -> Unit)) {
@PublishedApi
internal val builder = RouterFunctions.route()
/**
* Return a composed request predicate that tests against both this predicate AND
* the [other] predicate (String processed as a path predicate). When evaluating the
* composed predicate, if this predicate is `false`, then the [other] predicate is not
* evaluated.
* @see RequestPredicate.and
* @see RequestPredicates.path
*/
infix fun RequestPredicate.and(other: String): RequestPredicate = this.and(path(other))
/**
* Return a composed request predicate that tests against both this predicate OR
* the [other] predicate (String processed as a path predicate). When evaluating the
* composed predicate, if this predicate is `true`, then the [other] predicate is not
* evaluated.
* @see RequestPredicate.or
* @see RequestPredicates.path
*/
infix fun RequestPredicate.or(other: String): RequestPredicate = this.or(path(other))
/**
* Return a composed request predicate that tests against both this predicate (String
* processed as a path predicate) AND the [other] predicate. When evaluating the
* composed predicate, if this predicate is `false`, then the [other] predicate is not
* evaluated.
* @see RequestPredicate.and
* @see RequestPredicates.path
*/
infix fun String.and(other: RequestPredicate): RequestPredicate = path(this).and(other)
/**
* Return a composed request predicate that tests against both this predicate (String
* processed as a path predicate) OR the [other] predicate. When evaluating the
* composed predicate, if this predicate is `true`, then the [other] predicate is not
* evaluated.
* @see RequestPredicate.or
* @see RequestPredicates.path
*/
infix fun String.or(other: RequestPredicate): RequestPredicate = path(this).or(other)
/**
* Return a composed request predicate that tests against both this predicate AND
* the [other] predicate. When evaluating the composed predicate, if this
* predicate is `false`, then the [other] predicate is not evaluated.
* @see RequestPredicate.and
*/
infix fun RequestPredicate.and(other: RequestPredicate): RequestPredicate = this.and(other)
/**
* Return a composed request predicate that tests against both this predicate OR
* the [other] predicate. When evaluating the composed predicate, if this
* predicate is `true`, then the [other] predicate is not evaluated.
* @see RequestPredicate.or
*/
infix fun RequestPredicate.or(other: RequestPredicate): RequestPredicate = this.or(other)
/**
* Return a predicate that represents the logical negation of this predicate.
*/
operator fun RequestPredicate.not(): RequestPredicate = this.negate()
/**
* Route to the given router function if the given request predicate applies. This
* method can be used to create *nested routes*, where a group of routes share a
* common path (prefix), header, or other request predicate.
* @see RouterFunctions.nest
*/
fun RequestPredicate.nest(r: (RouterFunctionDsl.() -> Unit)) {
builder.nest(this, Supplier(RouterFunctionDsl(r)::build))
}
/**
* Route to the given router function if the given request predicate (String
* processed as a path predicate) applies. This method can be used to create
* *nested routes*, where a group of routes share a common path
* (prefix), header, or other request predicate.
* @see RouterFunctions.nest
* @see RequestPredicates.path
*/
fun String.nest(r: (RouterFunctionDsl.() -> Unit)) = path(this).nest(r)
/**
* Adds a route to the given handler function that handles all HTTP `GET` requests.
* @since 5.3
*/
fun GET(f: (ServerRequest) -> ServerResponse) {
builder.GET(HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `GET` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun GET(pattern: String, f: (ServerRequest) -> ServerResponse) {
builder.GET(pattern, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `GET` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun GET(predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.GET(predicate, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `GET` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun GET(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.GET(pattern, predicate, HandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `GET`
* and the given `pattern` matches against the request path.
* @see RequestPredicates.GET
*/
fun GET(pattern: String): RequestPredicate = RequestPredicates.GET(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `HEAD` requests.
* @since 5.3
*/
fun HEAD(f: (ServerRequest) -> ServerResponse) {
builder.HEAD(HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `HEAD` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun HEAD(pattern: String, f: (ServerRequest) -> ServerResponse) {
builder.HEAD(pattern, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `HEAD` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun HEAD(predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.HEAD(predicate, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `HEAD` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun HEAD(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.HEAD(pattern, predicate, HandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `HEAD`
* and the given `pattern` matches against the request path.
* @see RequestPredicates.HEAD
*/
fun HEAD(pattern: String): RequestPredicate = RequestPredicates.HEAD(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `POST` requests.
* @since 5.3
*/
fun POST(f: (ServerRequest) -> ServerResponse) {
builder.POST(HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `POST` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun POST(pattern: String, f: (ServerRequest) -> ServerResponse) {
builder.POST(pattern, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `POST` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun POST(predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.POST(predicate, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `POST` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun POST(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.POST(pattern, predicate, HandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `POST`
* and the given `pattern` matches against the request path.
* @see RequestPredicates.POST
*/
fun POST(pattern: String): RequestPredicate = RequestPredicates.POST(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `PUT` requests.
* @since 5.3
*/
fun PUT(f: (ServerRequest) -> ServerResponse) {
builder.PUT(HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `PUT` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun PUT(pattern: String, f: (ServerRequest) -> ServerResponse) {
builder.PUT(pattern, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `PUT` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun PUT(predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.PUT(predicate, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `PUT` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun PUT(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.PUT(pattern, predicate, HandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `PUT`
* and the given `pattern` matches against the request path.
* @see RequestPredicates.PUT
*/
fun PUT(pattern: String): RequestPredicate = RequestPredicates.PUT(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `PATCH` requests.
* @since 5.3
*/
fun PATCH(f: (ServerRequest) -> ServerResponse) {
builder.PATCH(HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `PATCH` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun PATCH(pattern: String, f: (ServerRequest) -> ServerResponse) {
builder.PATCH(pattern, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `PATCH` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun PATCH(predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.PATCH(predicate, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `PATCH` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun PATCH(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.PATCH(pattern, predicate, HandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `PATCH`
* and the given `pattern` matches against the request path.
* @param pattern the path pattern to match against
* @return a predicate that matches if the request method is `PATCH` and if the given pattern
* matches against the request path
*/
fun PATCH(pattern: String): RequestPredicate = RequestPredicates.PATCH(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `DELETE` requests.
* @since 5.3
*/
fun DELETE(f: (ServerRequest) -> ServerResponse) {
builder.DELETE(HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `DELETE` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun DELETE(pattern: String, f: (ServerRequest) -> ServerResponse) {
builder.DELETE(pattern, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `DELETE` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun DELETE(predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.DELETE(predicate, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `DELETE` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun DELETE(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.DELETE(pattern, predicate, HandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `DELETE`
* and the given `pattern` matches against the request path.
* @param pattern the path pattern to match against
* @return a predicate that matches if the request method is `DELETE` and if the given pattern
* matches against the request path
*/
fun DELETE(pattern: String): RequestPredicate = RequestPredicates.DELETE(pattern)
/**
* Adds a route to the given handler function that handles all HTTP `OPTIONS` requests.
* @since 5.3
*/
fun OPTIONS(f: (ServerRequest) -> ServerResponse) {
builder.OPTIONS(HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `OPTIONS` requests
* that match the given pattern.
* @param pattern the pattern to match to
*/
fun OPTIONS(pattern: String, f: (ServerRequest) -> ServerResponse) {
builder.OPTIONS(pattern, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `OPTIONS` requests
* that match the given predicate.
* @param predicate predicate to match
* @since 5.3
*/
fun OPTIONS(predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.OPTIONS(predicate, HandlerFunction(f))
}
/**
* Adds a route to the given handler function that handles all HTTP `OPTIONS` requests
* that match the given pattern and predicate.
* @param pattern the pattern to match to
* @param predicate additional predicate to match
* @since 5.2
*/
fun OPTIONS(pattern: String, predicate: RequestPredicate, f: (ServerRequest) -> ServerResponse) {
builder.OPTIONS(pattern, predicate, HandlerFunction(f))
}
/**
* Return a [RequestPredicate] that matches if request's HTTP method is `OPTIONS`
* and the given `pattern` matches against the request path.
* @param pattern the path pattern to match against
* @return a predicate that matches if the request method is `OPTIONS` and if the given pattern
* matches against the request path
*/
fun OPTIONS(pattern: String): RequestPredicate = RequestPredicates.OPTIONS(pattern)
/**
* Route to the given handler function if the given accept predicate applies.
* @see RouterFunctions.route
*/
fun accept(mediaType: MediaType, f: (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.accept(mediaType), HandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that tests if the request's
* [accept][ServerRequest.Headers.accept] } header is
* [compatible][MediaType.isCompatibleWith] with any of the given media types.
* @param mediaType the media types to match the request's accept header against
* @return a predicate that tests the request's accept header against the given media types
*/
fun accept(vararg mediaType: MediaType): RequestPredicate = RequestPredicates.accept(*mediaType)
/**
* Route to the given handler function if the given contentType predicate applies.
* @see RouterFunctions.route
*/
fun contentType(mediaType: MediaType, f: (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.contentType(mediaType), HandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that tests if the request's
* [content type][ServerRequest.Headers.contentType] is
* [included][MediaType.includes] by any of the given media types.
* @param mediaTypes the media types to match the request's content type against
* @return a predicate that tests the request's content type against the given media types
*/
fun contentType(vararg mediaTypes: MediaType): RequestPredicate = RequestPredicates.contentType(*mediaTypes)
/**
* Route to the given handler function if the given headers predicate applies.
* @see RouterFunctions.route
*/
fun headers(headersPredicate: (ServerRequest.Headers) -> Boolean, f: (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.headers(headersPredicate), HandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that tests the request's headers against the given headers predicate.
* @param headersPredicate a predicate that tests against the request headers
* @return a predicate that tests against the given header predicate
*/
fun headers(headersPredicate: (ServerRequest.Headers) -> Boolean): RequestPredicate =
RequestPredicates.headers(headersPredicate)
/**
* Route to the given handler function if the given method predicate applies.
* @see RouterFunctions.route
*/
fun method(httpMethod: HttpMethod, f: (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.method(httpMethod), HandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that tests against the given HTTP method.
* @param httpMethod the HTTP method to match to
* @return a predicate that tests against the given HTTP method
*/
fun method(httpMethod: HttpMethod): RequestPredicate = RequestPredicates.method(httpMethod)
/**
* Route to the given handler function if the given path predicate applies.
* @see RouterFunctions.route
*/
fun path(pattern: String, f: (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.path(pattern), HandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that tests the request path against the given path pattern.
* @see RequestPredicates.path
*/
fun path(pattern: String): RequestPredicate = RequestPredicates.path(pattern)
/**
* Route to the given handler function if the given pathExtension predicate applies.
* @see RouterFunctions.route
*/
fun pathExtension(extension: String, f: (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.pathExtension(extension), HandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that matches if the request's path has the given extension.
* @param extension the path extension to match against, ignoring case
* @return a predicate that matches if the request's path has the given file extension
*/
fun pathExtension(extension: String): RequestPredicate = RequestPredicates.pathExtension(extension)
/**
* Route to the given handler function if the given pathExtension predicate applies.
* @see RouterFunctions.route
*/
fun pathExtension(predicate: (String) -> Boolean, f: (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.pathExtension(predicate), HandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that matches if the request's path matches the given
* predicate.
* @see RequestPredicates.pathExtension
*/
fun pathExtension(predicate: (String) -> Boolean): RequestPredicate =
RequestPredicates.pathExtension(predicate)
/**
* Route to the given handler function if the given queryParam predicate applies.
* @see RouterFunctions.route
*/
fun param(name: String, predicate: (String) -> Boolean, f: (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.param(name, predicate), HandlerFunction(f)))
}
/**
* Return a [RequestPredicate] that tests the request's query parameter of the given name
* against the given predicate.
* @param name the name of the query parameter to test against
* @param predicate the predicate to test against the query parameter value
* @return a predicate that matches the given predicate against the query parameter of the given name
* @see ServerRequest#queryParam
*/
fun param(name: String, predicate: (String) -> Boolean): RequestPredicate =
RequestPredicates.param(name, predicate)
/**
* Route to the given handler function if the given request predicate applies.
* @see RouterFunctions.route
*/
operator fun RequestPredicate.invoke(f: (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(this, HandlerFunction(f)))
}
/**
* Route to the given handler function if the given predicate (String
* processed as a path predicate) applies.
* @see RouterFunctions.route
*/
operator fun String.invoke(f: (ServerRequest) -> ServerResponse) {
builder.add(RouterFunctions.route(RequestPredicates.path(this), HandlerFunction(f)))
}
/**
* Route requests that match the given pattern to resources relative to the given root location.
* @see RouterFunctions.resources
*/
fun resources(path: String, location: Resource) {
builder.resources(path, location)
}
/**
* Route to resources using the provided lookup function. If the lookup function provides a
* [Resource] for the given request, it will be it will be exposed using a
* [HandlerFunction] that handles GET, HEAD, and OPTIONS requests.
*/
fun resources(lookupFunction: (ServerRequest) -> Resource?) {
builder.resources {
Optional.ofNullable(lookupFunction.invoke(it))
}
}
/**
* Merge externally defined router functions into this one.
* @param routerFunction the router function to be added
* @since 5.2
*/
fun add(routerFunction: RouterFunction<ServerResponse>) {
builder.add(routerFunction)
}
/**
* Filters all routes created by this router with the given filter function. Filter
* functions are typically used to address cross-cutting concerns, such as logging,
* security, etc.
* @param filterFunction the function to filter all routes built by this router
* @since 5.2
*/
fun filter(filterFunction: (ServerRequest, (ServerRequest) -> ServerResponse) -> ServerResponse) {
builder.filter { request, next ->
filterFunction(request) { handlerRequest ->
next.handle(handlerRequest)
}
}
}
/**
* Filter the request object for all routes created by this builder with the given request
* processing function. Filters are typically used to address cross-cutting concerns, such
* as logging, security, etc.
* @param requestProcessor a function that transforms the request
* @since 5.2
*/
fun before(requestProcessor: (ServerRequest) -> ServerRequest) {
builder.before(requestProcessor)
}
/**
* Filter the response object for all routes created by this builder with the given response
* processing function. Filters are typically used to address cross-cutting concerns, such
* as logging, security, etc.
* @param responseProcessor a function that transforms the response
* @since 5.2
*/
fun after(responseProcessor: (ServerRequest, ServerResponse) -> ServerResponse) {
builder.after(responseProcessor)
}
/**
* Filters all exceptions that match the predicate by applying the given response provider
* function.
* @param predicate the type of exception to filter
* @param responseProvider a function that creates a response
* @since 5.2
*/
fun onError(predicate: (Throwable) -> Boolean, responseProvider: (Throwable, ServerRequest) -> ServerResponse) {
builder.onError(predicate, responseProvider)
}
/**
* Filters all exceptions that match the predicate by applying the given response provider
* function.
* @param E the type of exception to filter
* @param responseProvider a function that creates a response
* @since 5.2
*/
inline fun <reified E : Throwable> onError(noinline responseProvider: (Throwable, ServerRequest) -> ServerResponse) {
builder.onError({it is E}, responseProvider)
}
/**
* Add an attribute with the given name and value to the last route built with this builder.
* @param name the attribute name
* @param value the attribute value
* @since 6.0
*/
fun withAttribute(name: String, value: Any) {
builder.withAttribute(name, value)
}
/**
* Manipulate the attributes of the last route built with the given consumer.
*
* The map provided to the consumer is "live", so that the consumer can be used
* to [overwrite][MutableMap.put] existing attributes,
* [remove][MutableMap.remove] attributes, or use any of the other
* [MutableMap] methods.
* @param attributesConsumer a function that consumes the attributes map
* @since 6.0
*/
fun withAttributes(attributesConsumer: (MutableMap<String, Any>) -> Unit) {
builder.withAttributes(attributesConsumer)
}
/**
* Return a composed routing function created from all the registered routes.
*/
internal fun build(): RouterFunction<ServerResponse> {
init()
return builder.build()
}
/**
* @see ServerResponse.from
*/
fun from(other: ServerResponse) =
ServerResponse.from(other)
/**
* @see ServerResponse.created
*/
fun created(location: URI) =
ServerResponse.created(location)
/**
* @see ServerResponse.ok
*/
fun ok() = ServerResponse.ok()
/**
* @see ServerResponse.noContent
*/
fun noContent() = ServerResponse.noContent()
/**
* @see ServerResponse.accepted
*/
fun accepted() = ServerResponse.accepted()
/**
* @see ServerResponse.permanentRedirect
*/
fun permanentRedirect(location: URI) = ServerResponse.permanentRedirect(location)
/**
* @see ServerResponse.temporaryRedirect
*/
fun temporaryRedirect(location: URI) = ServerResponse.temporaryRedirect(location)
/**
* @see ServerResponse.seeOther
*/
fun seeOther(location: URI) = ServerResponse.seeOther(location)
/**
* @see ServerResponse.badRequest
*/
fun badRequest() = ServerResponse.badRequest()
/**
* @see ServerResponse.notFound
*/
fun notFound() = ServerResponse.notFound()
/**
* @see ServerResponse.unprocessableEntity
*/
fun unprocessableEntity() = ServerResponse.unprocessableEntity()
/**
* @see ServerResponse.status
*/
fun status(status: HttpStatusCode) = ServerResponse.status(status)
/**
* @see ServerResponse.status
*/
fun status(status: Int) = ServerResponse.status(status)
}
/**
* Equivalent to [RouterFunction.and].
*/
operator fun <T: ServerResponse> RouterFunction<T>.plus(other: RouterFunction<T>) =
this.and(other)
| apache-2.0 |
anthonycr/Lightning-Browser | app/src/main/java/acr/browser/lightning/Capabilities.kt | 1 | 379 | package acr.browser.lightning
import android.os.Build
/**
* Capabilities that are specific to certain API levels.
*/
enum class Capabilities {
FULL_INCOGNITO
}
/**
* Returns true if the capability is supported, false otherwise.
*/
val Capabilities.isSupported: Boolean
get() = when (this) {
Capabilities.FULL_INCOGNITO -> Build.VERSION.SDK_INT >= 28
}
| mpl-2.0 |
leafclick/intellij-community | platform/script-debugger/backend/src/debugger/sourcemap/SourceResolver.kt | 1 | 6225 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.debugger.sourcemap
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.Url
import com.intellij.util.Urls
import com.intellij.util.containers.ObjectIntHashMap
import com.intellij.util.io.URLUtil
import org.jetbrains.debugger.ScriptDebuggerUrls
import java.io.File
interface SourceFileResolver {
/**
* Return -1 if no match
*/
fun resolve(map: ObjectIntHashMap<Url>): Int = -1
fun resolve(rawSources: List<String>): Int = -1
}
class SourceResolver(private val rawSources: List<String>,
trimFileScheme: Boolean,
baseUrl: Url?,
baseUrlIsFile: Boolean = true) {
companion object {
fun isAbsolute(path: String): Boolean = path.startsWith('/') || (SystemInfo.isWindows && (path.length > 2 && path[1] == ':'))
}
val canonicalizedUrls: Array<Url> by lazy {
Array(rawSources.size) { canonicalizeUrl(rawSources[it], baseUrl, trimFileScheme, baseUrlIsFile) }
}
private val canonicalizedUrlToSourceIndex: ObjectIntHashMap<Url> by lazy {
(
if (SystemInfo.isFileSystemCaseSensitive) ObjectIntHashMap(rawSources.size)
else ObjectIntHashMap(rawSources.size, Urls.caseInsensitiveUrlHashingStrategy)
).also {
for (i in rawSources.indices) {
it.put(canonicalizedUrls[i], i)
}
}
}
fun getSource(entry: MappingEntry): Url? {
val index = entry.source
return if (index < 0) null else canonicalizedUrls[index]
}
fun getSourceIndex(url: Url): Int = canonicalizedUrlToSourceIndex[url]
internal fun findSourceIndex(resolver: SourceFileResolver): Int {
val resolveByCanonicalizedUrls = resolver.resolve(canonicalizedUrlToSourceIndex)
return if (resolveByCanonicalizedUrls != -1) resolveByCanonicalizedUrls else resolver.resolve(rawSources)
}
fun findSourceIndex(sourceUrl: Url, sourceFile: VirtualFile?, localFileUrlOnly: Boolean): Int {
val index = canonicalizedUrlToSourceIndex.get(sourceUrl)
if (index != -1) {
return index
}
if (sourceFile != null) {
return findSourceIndexByFile(sourceFile, localFileUrlOnly)
}
return -1
}
internal fun findSourceIndexByFile(sourceFile: VirtualFile, localFileUrlOnly: Boolean): Int {
if (!localFileUrlOnly) {
val index = canonicalizedUrlToSourceIndex.get(Urls.newFromVirtualFile(sourceFile).trimParameters())
if (index != -1) {
return index
}
}
if (!sourceFile.isInLocalFileSystem) {
return -1
}
val index = canonicalizedUrlToSourceIndex.get(ScriptDebuggerUrls.newLocalFileUrl(sourceFile))
if (index != -1) {
return index
}
// ok, search by canonical path
val canonicalFile = sourceFile.canonicalFile
if (canonicalFile != null && canonicalFile != sourceFile) {
for (i in canonicalizedUrls.indices) {
val url = canonicalizedUrls.get(i)
if (Urls.equalsIgnoreParameters(url, canonicalFile)) {
return i
}
}
}
return -1
}
fun getUrlIfLocalFile(entry: MappingEntry): Url? = canonicalizedUrls.getOrNull(entry.source)?.let { if (it.isInLocalFileSystem) it else null }
}
fun canonicalizePath(url: String, baseUrl: Url, baseUrlIsFile: Boolean): String {
var path = url
if (!FileUtil.isAbsolute(url) && !url.isEmpty() && url[0] != '/') {
val basePath = baseUrl.path
if (baseUrlIsFile) {
val lastSlashIndex = basePath.lastIndexOf('/')
val pathBuilder = StringBuilder()
if (lastSlashIndex == -1) {
pathBuilder.append('/')
}
else {
pathBuilder.append(basePath, 0, lastSlashIndex + 1)
}
path = pathBuilder.append(url).toString()
}
else {
path = "$basePath/$url"
}
}
return FileUtil.toCanonicalPath(path, '/')
}
// see canonicalizeUri kotlin impl and https://trac.webkit.org/browser/trunk/Source/WebCore/inspector/front-end/ParsedURL.js completeURL
fun canonicalizeUrl(url: String, baseUrl: Url?, trimFileScheme: Boolean, baseUrlIsFile: Boolean = true): Url {
if (url.startsWith(StandardFileSystems.FILE_PROTOCOL_PREFIX)) {
return ScriptDebuggerUrls.newLocalFileUrl(FileUtil.toCanonicalPath(VfsUtilCore.toIdeaUrl(url, true).substring(StandardFileSystems.FILE_PROTOCOL_PREFIX.length), '/'))
}
else if (baseUrl == null || url.contains(URLUtil.SCHEME_SEPARATOR) || url.startsWith("data:") || url.startsWith("blob:") ||
url.startsWith("javascript:") || url.startsWith("webpack:")) {
// consider checking :/ instead of :// because scheme may be followed by path, not by authority
// https://tools.ietf.org/html/rfc3986#section-1.1.2
// be careful with windows paths: C:/Users
return Urls.parseEncoded(url) ?: Urls.newUri(null, url)
}
else {
return doCanonicalize(url, baseUrl, baseUrlIsFile, true)
}
}
fun doCanonicalize(url: String, baseUrl: Url, baseUrlIsFile: Boolean, asLocalFileIfAbsoluteAndExists: Boolean): Url {
val path = canonicalizePath(url, baseUrl, baseUrlIsFile)
if (baseUrl.isInLocalFileSystem ||
asLocalFileIfAbsoluteAndExists && SourceResolver.isAbsolute(path) && File(path).exists()) {
// file:///home/user/foo.js.map, foo.ts -> file:///home/user/foo.ts (baseUrl is in local fs)
// http://localhost/home/user/foo.js.map, foo.ts -> file:///home/user/foo.ts (File(path) exists)
return ScriptDebuggerUrls.newLocalFileUrl(path)
}
else if (!path.startsWith("/")) {
// http://localhost/source.js.map, C:/foo.ts webpack-dsj3c45 -> C:/foo.ts webpack-dsj3c45
// (we can't append path suffixes unless they start with /
return ScriptDebuggerUrls.parse(path, true) ?: Urls.newUnparsable(path)
}
else {
// new url from path and baseUrl's scheme and authority
val split = path.split('?', limit = 2)
return Urls.newUrl(baseUrl.scheme, baseUrl.authority, split[0], if (split.size > 1) '?' + split[1] else null)
}
} | apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/casts/literalExpressionAsGenericArgument/unaryExpressionCast.kt | 5 | 159 | class Box<T>(val value: T)
fun box() : String {
val b = Box<Long>(-1)
val expected: Long? = -1L
return if (b.value == expected) "OK" else "fail"
} | apache-2.0 |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/traits/indirectlyInheritPropertyGetter.kt | 5 | 114 | interface A {
val str: String
get() = "OK"
}
interface B : A
class Impl : B
fun box() = Impl().str
| apache-2.0 |
samirma/MeteoriteLandings | app/src/main/java/com/antonio/samir/meteoritelandingsspots/data/Result.kt | 1 | 295 | package com.antonio.samir.meteoritelandingsspots.data
sealed class Result<out T : Any> {
data class Success<out T : Any>(val data: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
data class InProgress<out T : Any>(val data: T? = null) : Result<T>()
} | mit |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reflection/callBy/nonDefaultParameterOmitted.kt | 2 | 582 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
fun foo(x: Int, y: Int = 2) = x + y
fun box(): String {
try {
::foo.callBy(mapOf())
return "Fail: IllegalArgumentException must have been thrown"
}
catch (e: IllegalArgumentException) {
// OK
}
try {
::foo.callBy(mapOf(::foo.parameters.last() to 1))
return "Fail: IllegalArgumentException must have been thrown"
}
catch (e: IllegalArgumentException) {
// OK
}
return "OK"
}
| apache-2.0 |
aconsuegra/algorithms-playground | src/main/kotlin/me/consuegra/algorithms/KSearchInsertPosition.kt | 1 | 1452 | package me.consuegra.algorithms
/**
* Given a sorted array and a target value, return the index if the target is found. If not, return the index
* where it would be if it were inserted in order.
* <p>
* You may assume no duplicates in the array.
* <p>
* Here are few examples.
* [1,3,5,6], 5 → 2
* [1,3,5,6], 2 → 1
* [1,3,5,6], 7 → 4
* [1,3,5,6], 0 → 0
*/
class KSearchInsertPosition {
fun searchInsert(input: IntArray, target: Int): Int {
var low = 0
var high = input.size - 1
while (low <= high) {
val middle = (low + high) / 2
when {
input[middle] < target -> low = middle + 1
input[middle] > target -> high = middle - 1
else -> return middle
}
}
return low
}
fun searchInsertRec(input: IntArray, target: Int): Int {
if (input.isEmpty()) {
return 0
}
return searchInsertRec(input, 0, input.size - 1, target)
}
fun searchInsertRec(input: IntArray, start: Int, end: Int, target: Int): Int {
if (start > end) {
return start
}
val middle = (start + end) / 2
when {
input[middle] < target -> return searchInsertRec(input, middle + 1, end, target)
input[middle] > target -> return searchInsertRec(input, start, middle - 1, target)
else -> return middle
}
}
}
| mit |
nrkv/HypeAPI | src/main/kotlin/io/nrkv/HypeAPI/task/model/TaskRequest.kt | 1 | 360 | package io.nrkv.HypeAPI.task.model
import java.util.*
/**
* Created by Ivan Nyrkov on 08/06/17.
*/
interface TaskRequest {
var title: String
var description: String
var dueDate: Date
fun update(newValues: TaskRequest) {
title = newValues.title
description = newValues.description
dueDate = newValues.dueDate
}
} | mit |
faceofcat/Tesla-Core-Lib | src/main/kotlin/net/ndrei/teslacorelib/inventory/FluidTankType.kt | 1 | 185 | package net.ndrei.teslacorelib.inventory
enum class FluidTankType(val canDrain: Boolean, val canFill: Boolean) {
INPUT(false, true),
OUTPUT(true, false),
BOTH(true, true)
} | mit |
rizafu/CoachMark | app/src/main/java/com/rizafu/sample/SimpleFragment.kt | 1 | 5660 | package com.rizafu.sample
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.design.widget.BaseTransientBottomBar
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.rizafu.coachmark.CoachMark
import com.rizafu.sample.databinding.RecyclerLayoutBinding
/**
* Created by RizaFu on 2/27/17.
*/
class SimpleFragment : Fragment(){
private lateinit var binding: RecyclerLayoutBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.recycler_layout, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adapter = SimpleAdapter()
adapter.addItem("Simple Coach Mark 1", "no tooltip, click target for dismiss")
adapter.addItem("Simple Coach Mark 2", "no tooltip, dismissible")
adapter.addItem("Simple Coach Mark 3", "no tooltip, with target custom click listener")
adapter.addItem("Coach Mark 1", "simple tooltip message at alignment bottom")
adapter.addItem("Coach Mark 2", "simple tooltip message at alignment top")
adapter.addItem("Coach Mark 3", "simple tooltip pointer at alignment left")
adapter.addItem("Coach Mark 4", "simple tooltip pointer at alignment right")
adapter.addItem("Coach Mark 5", "simple tooltip no pointer")
adapter.addItem("Simple Coach Mark 1", "no tooltip, click target for dismiss")
adapter.addItem("Simple Coach Mark 2", "no tooltip, dismissible")
adapter.addItem("Simple Coach Mark 3", "no tooltip, with target custom click listener")
adapter.addItem("Coach Mark 1", "simple tooltip message at alignment bottom")
adapter.addItem("Coach Mark 2", "simple tooltip message at alignment top")
adapter.addItem("Coach Mark 3", "simple tooltip pointer at alignment left")
adapter.addItem("Coach Mark 4", "simple tooltip pointer at alignment right")
adapter.addItem("Coach Mark 5", "simple tooltip no pointer")
binding.recyclerView.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
binding.recyclerView.setHasFixedSize(true)
binding.recyclerView.adapter = adapter
adapter.setOnItemClick({v, p -> onClick(v,p)})
}
private fun onClick(view: View, position: Int) {
activity?.let {
when (position) {
0 -> CoachMark.Builder(it)
.setTarget(view)
.show()
1 -> CoachMark.Builder(it)
.setTarget(view)
.setDismissible()
.show()
2 -> CoachMark.Builder(it)
.setTarget(view)
.setOnClickTarget { coachMark ->
coachMark.dismiss()
Snackbar.make(view.rootView, "Action click on target mark", BaseTransientBottomBar.LENGTH_LONG).show()
}
.show()
3 -> CoachMark.Builder(it)
.setTarget(view)
.addTooltipChildText(it, "this is message tooltip", android.R.color.primary_text_dark)
.setTooltipAlignment(CoachMark.TARGET_BOTTOM)
.setTooltipBackgroundColor(R.color.colorPrimary)
.show()
4 -> CoachMark.Builder(it)
.setTarget(view)
.addTooltipChildText(it, "this is message tooltip", android.R.color.primary_text_light)
.setTooltipAlignment(CoachMark.TARGET_TOP)
.setTooltipBackgroundColor(R.color.colorAccent)
.show()
5 -> CoachMark.Builder(it)
.setTarget(view)
.addTooltipChildText(it, "this is message tooltip", android.R.color.primary_text_light)
.setTooltipAlignment(CoachMark.TARGET_TOP_LEFT)
.setTooltipPointer(CoachMark.POINTER_LEFT)
.setTooltipBackgroundColor(R.color.colorAccent)
.show()
6 -> CoachMark.Builder(it)
.setTarget(view)
.addTooltipChildText(it, "this is message tooltip", android.R.color.primary_text_light)
.setTooltipAlignment(CoachMark.TARGET_TOP_RIGHT)
.setTooltipPointer(CoachMark.POINTER_RIGHT)
.setTooltipBackgroundColor(R.color.colorAccent)
.show()
7 -> CoachMark.Builder(it)
.setTarget(view)
.addTooltipChildText(it, "this is message tooltip", android.R.color.primary_text_light)
.setTooltipAlignment(CoachMark.TARGET_TOP)
.setTooltipPointer(CoachMark.POINTER_GONE)
.show()
else -> { }
}
}
}
companion object {
fun newInstance(): SimpleFragment {
val args = Bundle()
val fragment = SimpleFragment()
fragment.arguments = args
return fragment
}
}
}
| apache-2.0 |
salRoid/Filmy | app/src/main/java/tech/salroid/filmy/ui/activities/MainActivity.kt | 1 | 10778 | package tech.salroid.filmy.ui.activities
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.speech.RecognizerIntent
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.preference.PreferenceManager
import androidx.viewpager.widget.ViewPager
import com.google.android.material.appbar.AppBarLayout
import com.miguelcatalan.materialsearchview.MaterialSearchView
import com.miguelcatalan.materialsearchview.MaterialSearchView.SearchViewListener
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import tech.salroid.filmy.R
import tech.salroid.filmy.data.network.NetworkUtil
import tech.salroid.filmy.databinding.ActivityMainBinding
import tech.salroid.filmy.ui.FilmyIntro
import tech.salroid.filmy.ui.activities.fragment.Trending
import tech.salroid.filmy.ui.activities.fragment.UpComing
import tech.salroid.filmy.ui.adapters.CollectionsPagerAdapter
import tech.salroid.filmy.ui.fragment.InTheaters
import tech.salroid.filmy.ui.fragment.SearchFragment
import tech.salroid.filmy.utility.getQueryTextChangeStateFlow
class MainActivity : AppCompatActivity() {
var fetchingFromNetwork = false
private var trendingFragment: Trending? = null
private lateinit var searchFragment: SearchFragment
private var cantProceed = false
private var nightMode = false
private lateinit var binding: ActivityMainBinding
private val mMessageReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val statusCode = intent.getIntExtra("message", 0)
cantProceed(statusCode)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
val sp = PreferenceManager.getDefaultSharedPreferences(this)
nightMode = sp.getBoolean("dark", false)
if (nightMode) setTheme(R.style.AppTheme_Base_Dark) else setTheme(R.style.AppTheme_Base)
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
supportActionBar?.title = " "
introLogic()
if (nightMode) allThemeLogic() else lightThemeLogic()
/* binding.mainErrorView.apply {
title = getString(R.string.error_title_damn)
titleColor = ContextCompat.getColor(context, R.color.dark)
setSubtitle(getString(R.string.error_details))
setRetryText(getString(R.string.error_retry))
}*/
/*binding.mainErrorView.setRetryListener {
if (NetworkUtil.isNetworkConnected(this@MainActivity)) {
fetchingFromNetwork = true
// fetchMoviesFromNetwork()
}
canProceed()
}*/
//binding.mainErrorView.visibility = View.GONE
setupSearch()
}
private fun setupSearch() {
binding.searchView.setVoiceSearch(false)
binding.searchView.setOnSearchViewListener(object : SearchViewListener {
override fun onSearchViewShown() {
binding.tabLayout.visibility = View.GONE
disableToolbarScrolling()
searchFragment = SearchFragment()
supportFragmentManager.beginTransaction()
.replace(R.id.search_container, searchFragment)
.commit()
}
override fun onSearchViewClosed() {
supportFragmentManager
.beginTransaction()
.remove(searchFragment)
.commit()
enableToolbarScrolling()
}
})
// Instant search using Flow
lifecycleScope.launch(Dispatchers.IO) {
binding.searchView.getQueryTextChangeStateFlow()
.debounce(300)
.filter { query ->
return@filter query.isNotEmpty()
}
.distinctUntilChanged()
.flatMapLatest { query ->
searchFragment.showProgress()
flow {
emit(NetworkUtil.searchMovies(query))
}.catch {
emitAll(flowOf(null))
}
}
.flowOn(Dispatchers.Main)
.collect { result ->
lifecycleScope.launch(Dispatchers.Main) {
result?.results?.let { searchFragment.showSearchResults(it) }
}
}
}
}
private fun allThemeLogic() {
binding.tabLayout.setTabTextColors(Color.parseColor("#bdbdbd"), Color.parseColor("#e0e0e0"))
binding.tabLayout.setBackgroundColor(
ContextCompat.getColor(
this,
R.color.colorDarkThemePrimary
)
)
binding.tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#bdbdbd"))
binding.logo.setTextColor(Color.parseColor("#E0E0E0"))
binding.searchView.setBackgroundColor(resources.getColor(R.color.colorDarkThemePrimary))
binding.searchView.setBackIcon(
ContextCompat.getDrawable(
this,
R.drawable.ic_action_navigation_arrow_back_inverted
)
)
binding.searchView.setCloseIcon(
ContextCompat.getDrawable(
this,
R.drawable.ic_action_navigation_close_inverted
)
)
binding.searchView.setTextColor(Color.parseColor("#ffffff"))
}
private fun lightThemeLogic() {
binding.logo.setTextColor(ContextCompat.getColor(this, R.color.dark))
}
private fun introLogic() {
val thread = Thread {
val getPrefs = PreferenceManager.getDefaultSharedPreferences(baseContext)
val isFirstStart = getPrefs.getBoolean("firstStart", true)
if (isFirstStart) {
val i = Intent(this@MainActivity, FilmyIntro::class.java)
startActivity(i)
val e = getPrefs.edit()
e.putBoolean("firstStart", false)
e.apply()
}
}
thread.start()
}
fun cantProceed(status: Int) {
Handler().postDelayed({
if (trendingFragment != null && !trendingFragment!!.isShowingFromDatabase) {
cantProceed = true
binding.tabLayout.visibility = View.GONE
//binding.viewpager.visibility = View.GONE
//binding.mainErrorView.visibility = View.VISIBLE
disableToolbarScrolling()
}
}, 1000)
}
private fun canProceed() {
cantProceed = false
binding.tabLayout.visibility = View.VISIBLE
//binding.viewpager.visibility = View.VISIBLE
//binding.mainErrorView.visibility = View.GONE
//trendingFragment?.retryLoading()
enableToolbarScrolling()
}
private fun disableToolbarScrolling() {
val params = binding.toolbarScroller.layoutParams as AppBarLayout.LayoutParams
params.scrollFlags = 0
}
private fun enableToolbarScrolling() {
val params = binding.toolbarScroller.layoutParams as AppBarLayout.LayoutParams
params.scrollFlags = (AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL
or AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS)
}
private fun setupViewPager(viewPager: ViewPager) {
trendingFragment = Trending()
val inTheatersFragment = InTheaters()
val upComingFragment = UpComing()
val adapter = CollectionsPagerAdapter(supportFragmentManager)
adapter.addFragment(trendingFragment!!, getString(R.string.trending))
// adapter.addFragment(inTheatersFragment, getString(R.string.theatres))
// adapter.addFragment(upComingFragment, getString(R.string.upcoming))
viewPager.adapter = adapter
}
private fun getSearchedResult(query: String) {
searchFragment.getSearchedResult(query)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main_menu, menu)
val itemSearch = menu.findItem(R.id.action_search)
val itemAccount = menu.findItem(R.id.ic_collections)
if (nightMode) {
itemSearch.setIcon(R.drawable.ic_action_action_search)
itemAccount.setIcon(R.drawable.ic_action_collections_bookmark2)
}
binding.searchView.setMenuItem(itemSearch)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_search -> startActivity(Intent(this, SearchFragment::class.java))
R.id.ic_setting -> startActivity(Intent(this, SettingsActivity::class.java))
R.id.ic_collections -> startActivity(Intent(this, CollectionsActivity::class.java))
}
return super.onOptionsItemSelected(item)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == MaterialSearchView.REQUEST_VOICE && resultCode == RESULT_OK) {
val matches = data!!.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
if (matches != null && matches.size > 0) {
val searchWrd = matches[0]
if (!TextUtils.isEmpty(searchWrd)) {
binding.searchView.setQuery(searchWrd, false)
}
}
return
}
super.onActivityResult(requestCode, resultCode, data)
}
override fun onBackPressed() {
if (binding.searchView.isSearchOpen) {
binding.searchView.closeSearch()
} else {
super.onBackPressed()
}
}
override fun onResume() {
super.onResume()
val sp = PreferenceManager.getDefaultSharedPreferences(this)
val nightModeNew = sp.getBoolean("dark", false)
if (nightMode != nightModeNew) recreate()
LocalBroadcastManager.getInstance(this)
.registerReceiver(mMessageReceiver, IntentFilter("fetch-failed"))
}
override fun onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver)
super.onPause()
}
} | apache-2.0 |
AndroidX/androidx | compose/ui/ui-test/src/commonMain/kotlin/androidx/compose/ui/test/ExperimentalTestApi.kt | 3 | 1012 | /*
* 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.test
@RequiresOptIn("This testing API is experimental and is likely to be changed or removed entirely")
@Retention(AnnotationRetention.BINARY)
annotation class ExperimentalTestApi
@RequiresOptIn(
"This is internal API for Compose modules that may change frequently and without warning."
)
@Retention(AnnotationRetention.BINARY)
annotation class InternalTestApi
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/unusedLambdaExpressionBody/inEnumEntry.kt | 13 | 108 | // PROBLEM: none
enum class Test(f: () -> Unit) {
A(<caret>getFunc())
}
fun getFunc(): () -> Unit = {} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/move/java/moveClass/moveInnerToTop/moveNestedClassToTopLevelInAnotherPackage/before/b/onDemandImport.kt | 13 | 63 | package b
import b.*
fun bar() {
val t: a.A.X = a.A.X()
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/refIndex/tests/testData/compilerIndex/functions/fromObject/staticFunction/ObjectUsage.kt | 45 | 46 | fun objectUsage() {
val o = KotlinObject
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/primitiveArray/mapJoinToString.kt | 9 | 129 | // WITH_STDLIB
fun test() {
val array: IntArray = intArrayOf(0, 1, 2, 3)
array.<caret>map { "$it-$it" }.joinToString()
} | apache-2.0 |
zielu/GitToolBox | src/main/kotlin/zielu/gittoolbox/ui/DatePresenterFacade.kt | 1 | 339 | package zielu.gittoolbox.ui
import com.intellij.util.text.SyncDateFormat
import zielu.gittoolbox.config.AppConfig
import java.time.Clock
internal class DatePresenterFacade {
fun getAbsoluteDateTimeFormat(): SyncDateFormat = AppConfig.getConfig()
.absoluteDateTimeStyle.format
fun getClock(): Clock = Clock.systemDefaultZone()
}
| apache-2.0 |
Flank/flank | flank-scripts/src/main/kotlin/flank/scripts/utils/MarkdownFormatter.kt | 1 | 223 | package flank.scripts.utils
fun String.markdownBold() = "**$this**"
fun markdownLink(description: String, url: String) = "[$description]($url)"
fun String.markdownH2() = "## $this"
fun String.markdownH3() = "### $this"
| apache-2.0 |
MyPureCloud/platform-client-sdk-common | resources/sdk/purecloudkotlin/extensions/connector/ApiClientConnectorProvider.kt | 1 | 160 | package com.mypurecloud.sdk.v2.connector
interface ApiClientConnectorProvider {
fun create(properties: ApiClientConnectorProperties): ApiClientConnector
}
| mit |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/controller/tasks/TaskNone.kt | 1 | 199 | package com.cout970.modeler.controller.tasks
import com.cout970.modeler.Program
/**
* Created by cout970 on 2017/07/17.
*/
object TaskNone : ITask {
override fun run(state: Program) = Unit
} | gpl-3.0 |
tensorflow/examples | lite/examples/object_detection/android/app/src/androidTest/java/org/tensorflow/lite/examples/objectdetection/TFObjectDetectionTest.kt | 1 | 5984 | /*
* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tensorflow.lite.examples.objectdetection
import android.content.res.AssetManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.RectF
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import java.io.InputStream
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.tensorflow.lite.support.label.Category
import org.tensorflow.lite.task.vision.detector.Detection
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class TFObjectDetectionTest {
val controlResults = listOf<Detection>(
Detection.create(RectF(69.0f, 58.0f, 227.0f, 171.0f),
listOf<Category>(Category.create("cat", "cat", 0.77734375f))),
Detection.create(RectF(13.0f, 6.0f, 283.0f, 215.0f),
listOf<Category>(Category.create("couch", "couch", 0.5859375f))),
Detection.create(RectF(45.0f, 27.0f, 257.0f, 184.0f),
listOf<Category>(Category.create("chair", "chair", 0.55078125f)))
)
@Test
@Throws(Exception::class)
fun detectionResultsShouldNotChange() {
val objectDetectorHelper =
ObjectDetectorHelper(
context = InstrumentationRegistry.getInstrumentation().context,
objectDetectorListener =
object : ObjectDetectorHelper.DetectorListener {
override fun onError(error: String) {
// no op
}
override fun onResults(
results: MutableList<Detection>?,
inferenceTime: Long,
imageHeight: Int,
imageWidth: Int
) {
assertEquals(controlResults.size, results!!.size)
// Loop through the detected and control data
for (i in controlResults.indices) {
// Verify that the bounding boxes are the same
assertEquals(results[i].boundingBox, controlResults[i].boundingBox)
// Verify that the detected data and control
// data have the same number of categories
assertEquals(
results[i].categories.size,
controlResults[i].categories.size
)
// Loop through the categories
for (j in 0 until controlResults[i].categories.size - 1) {
// Verify that the labels are consistent
assertEquals(
results[i].categories[j].label,
controlResults[i].categories[j].label
)
}
}
}
}
)
// Create Bitmap and convert to TensorImage
val bitmap = loadImage("cat1.png")
// Run the object detector on the sample image
objectDetectorHelper.detect(bitmap!!, 0)
}
@Test
@Throws(Exception::class)
fun detectedImageIsScaledWithinModelDimens() {
val objectDetectorHelper =
ObjectDetectorHelper(
context = InstrumentationRegistry.getInstrumentation().context,
objectDetectorListener =
object : ObjectDetectorHelper.DetectorListener {
override fun onError(error: String) {}
override fun onResults(
results: MutableList<Detection>?,
inferenceTime: Long,
imageHeight: Int,
imageWidth: Int
) {
assertNotNull(results)
for (result in results!!) {
assertTrue(result.boundingBox.top <= imageHeight)
assertTrue(result.boundingBox.bottom <= imageHeight)
assertTrue(result.boundingBox.left <= imageWidth)
assertTrue(result.boundingBox.right <= imageWidth)
}
}
}
)
// Create Bitmap and convert to TensorImage
val bitmap = loadImage("cat1.png")
// Run the object detector on the sample image
objectDetectorHelper.detect(bitmap!!, 0)
}
@Throws(Exception::class)
private fun loadImage(fileName: String): Bitmap? {
val assetManager: AssetManager =
InstrumentationRegistry.getInstrumentation().context.assets
val inputStream: InputStream = assetManager.open(fileName)
return BitmapFactory.decodeStream(inputStream)
}
}
| apache-2.0 |
kivensolo/UiUsingListView | library/network/src/main/java/com/zeke/reactivehttp/datasource/BaseRemoteDataSource.kt | 1 | 6931 | package com.zeke.reactivehttp.datasource
import android.util.LruCache
import com.zeke.reactivehttp.callback.BaseRequestCallback
import com.zeke.reactivehttp.coroutine.ICoroutineEvent
import com.zeke.reactivehttp.exception.BaseHttpException
import com.zeke.reactivehttp.exception.LocalBadException
import com.zeke.reactivehttp.viewmodel.IUIActionEvent
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.concurrent.TimeUnit
/**
* @Author: leavesC
* @Date: 2020/5/4 0:56
* @Desc: 远程数据源的基类,目前用于提供网络数据。
*
* BaseRemoteDataSource处于最下层的数据提供者,只用于向上层提供数据,
* 提供了多个同步请求和异步请求方法,和 BaseReactiveViewModel 之间依靠 IUIActionEvent 接口来联系
*/
@Suppress("MemberVisibilityCanBePrivate")
abstract class BaseRemoteDataSource<Api : Any>(
protected val iUiActionEvent: IUIActionEvent?,
protected val apiServiceClass: Class<Api>
) : ICoroutineEvent {
companion object {
/**
* ApiService 缓存
*/
private val apiServiceCache = LruCache<String, Any>(30)
/**
* Retrofit 缓存
*/
private val retrofitCache = LruCache<String, Retrofit>(3)
/**
* 默认的 OKHttpClient
*/
private val defaultOkHttpClient by lazy {
OkHttpClient.Builder()
.readTimeout(10000L, TimeUnit.MILLISECONDS)
.writeTimeout(10000L, TimeUnit.MILLISECONDS)
.connectTimeout(10000L, TimeUnit.MILLISECONDS)
.retryOnConnectionFailure(true).build()
}
/**
* 构建默认的 Retrofit
*/
private fun createDefaultRetrofit(baseUrl: String): Retrofit {
return Retrofit.Builder()
.client(defaultOkHttpClient)
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}
/**
* 和生命周期绑定的协程作用域
*/
override val lifecycleSupportedScope = iUiActionEvent?.lifecycleSupportedScope ?: GlobalScope
/**
* 由子类实现此字段以便获取 baseUrl
*/
protected abstract val baseUrl: String
/**
* 允许子类自己来实现创建 Retrofit 的逻辑
* 外部无需缓存 Retrofit 实例,ReactiveHttp 内部已做好缓存处理
* 但外部需要自己判断是否需要对 OKHttpClient 进行缓存
* @param baseUrl
*/
protected open fun createRetrofit(baseUrl: String): Retrofit {
return createDefaultRetrofit(baseUrl)
}
protected open fun generateBaseUrl(baseUrl: String): String {
if (baseUrl.isNotBlank()) {
return baseUrl
}
return this.baseUrl
}
/**
* 获取指定BaseUrl对应的API对象
* @param baseUrl 指定的baseUrl
* @return API 对应的APIServer对象
*/
fun getApiService(baseUrl: String = ""): Api {
return getApiService(generateBaseUrl(baseUrl), apiServiceClass)
}
private fun getApiService(baseUrl: String, apiServiceClazz: Class<Api>): Api {
val key = baseUrl + apiServiceClazz.canonicalName
@Suppress("UNCHECKED_CAST")
val apiCache = apiServiceCache.get(key)?.let {
it as? Api
}
if (apiCache != null) {
return apiCache
}
val retrofit = retrofitCache.get(baseUrl) ?: (createRetrofit(baseUrl).apply {
retrofitCache.put(baseUrl, this)
})
val apiService = retrofit.create(apiServiceClazz)
apiServiceCache.put(key, apiService)
return apiService
}
protected fun handleException(throwable: Throwable, callback: BaseRequestCallback?) {
if (callback == null) {
return
}
if (throwable is CancellationException) {
callback.onCancelled?.invoke()
return
}
val exception = generateBaseExceptionReal(throwable)
if (exceptionHandle(exception)) {
callback.onFailed?.invoke(exception)
if (callback.onFailToast()) {
val error = exceptionFormat(exception)
if (error.isNotBlank()) {
showToast(error)
}
}
}
}
internal fun generateBaseExceptionReal(throwable: Throwable): BaseHttpException {
return generateBaseException(throwable).apply {
exceptionRecord(this)
}
}
/**
* 如果外部想要对 Throwable 进行特殊处理,则可以重写此方法,用于改变 Exception 类型
* 例如,在 token 失效时接口一般是会返回特定一个 httpCode 用于表明移动端需要去更新 token 了
* 此时外部就可以实现一个 BaseException 的子类 TokenInvalidException 并在此处返回
* 从而做到接口异常原因强提醒的效果,而不用去纠结 httpCode 到底是多少
*/
protected open fun generateBaseException(throwable: Throwable): BaseHttpException {
return if (throwable is BaseHttpException) {
throwable
} else {
LocalBadException(throwable)
}
}
/**
* 用于由外部中转控制当抛出异常时是否走 onFail 回调,当返回 true 时则回调,否则不回调
* @param httpException
*/
protected open fun exceptionHandle(httpException: BaseHttpException): Boolean {
return true
}
/**
* 用于将网络请求过程中的异常反馈给外部,以便记录
* @param throwable
*/
protected open fun exceptionRecord(throwable: Throwable) {
}
/**
* 用于对 BaseException 进行格式化,以便在请求失败时 Toast 提示错误信息
* @param httpException
*/
protected open fun exceptionFormat(httpException: BaseHttpException): String {
return when (httpException.realException) {
null -> {
httpException.errorMessage
}
is ConnectException, is SocketTimeoutException, is UnknownHostException -> {
"连接超时,请检查您的网络设置"
}
else -> {
"请求过程抛出异常:" + httpException.errorMessage
}
}
}
protected fun showLoading(job: Job?) {
iUiActionEvent?.showLoading(job)
}
protected fun dismissLoading() {
iUiActionEvent?.dismissLoading()
}
protected open fun showToast(msg: String){
}
} | gpl-2.0 |
siosio/intellij-community | plugins/kotlin/jps/jps-plugin/tests/testData/incremental/cacheVersionChanged/moduleWithInlineModified/module2_B.kt | 5 | 55 | package b
import a.*
open class B {
val a = f()
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/sortedByLast.kt | 2 | 136 | // API_VERSION: 1.3
// WITH_RUNTIME
val x: Pair<String, Int> = listOf("a" to 1, "c" to 3, "b" to 2).<caret>sortedBy { it.second }.last() | apache-2.0 |
siosio/intellij-community | plugins/ide-features-trainer/src/training/learn/lesson/general/GotoActionLesson.kt | 1 | 5332 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.learn.lesson.general
import com.intellij.ide.IdeBundle
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereUI
import com.intellij.ide.util.gotoByName.GotoActionModel
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.editor.actions.ToggleShowLineNumbersGloballyAction
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.editor.impl.EditorComponentImpl
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.ui.UIUtil
import training.dsl.*
import training.learn.LearnBundle
import training.learn.LessonsBundle
import training.learn.course.KLesson
import java.awt.event.KeyEvent
import javax.swing.JDialog
class GotoActionLesson(private val sample: LessonSample, private val firstLesson: Boolean = false) :
KLesson("Actions", LessonsBundle.message("goto.action.lesson.name")) {
companion object {
private const val FIND_ACTION_WORKAROUND: String = "https://intellij-support.jetbrains.com/hc/en-us/articles/360005137400-Cmd-Shift-A-hotkey-opens-Terminal-with-apropos-search-instead-of-the-Find-Action-dialog"
}
override val lessonContent: LessonContext.() -> Unit
get() = {
prepareSample(sample)
task("GotoAction") {
text(LessonsBundle.message("goto.action.use.find.action.1",
LessonUtil.actionName(it), action(it)))
if (SystemInfo.isMacOSMojave) {
text(LessonsBundle.message("goto.action.mac.workaround", LessonUtil.actionName(it), FIND_ACTION_WORKAROUND))
}
text(LessonsBundle.message("goto.action.use.find.action.2",
LessonUtil.actionName("SearchEverywhere"), LessonUtil.rawKeyStroke(KeyEvent.VK_SHIFT)))
stateCheck { checkInsideSearchEverywhere() }
test { actions(it) }
}
task("About") {
showWarningIfSearchPopupClosed()
text(LessonsBundle.message("goto.action.invoke.about.action",
LessonUtil.actionName(it).toLowerCase(), LessonUtil.rawEnter()))
triggerByUiComponentAndHighlight(highlightBorder = false, highlightInside = false) { dialog: JDialog ->
dialog.title?.contains(IdeBundle.message("about.popup.about.app", ApplicationNamesInfo.getInstance().fullProductName)) ?: false
}
test { actions(it) }
}
task {
text(LessonsBundle.message("goto.action.to.return.to.the.editor", action("EditorEscape")))
stateCheck {
focusOwner is EditorComponentImpl
}
test(waitEditorToBeReady = false) {
invokeActionViaShortcut("ESCAPE")
}
}
task("GotoAction") {
text(LessonsBundle.message("goto.action.invoke.again",
action(it), LessonUtil.rawKeyStroke(KeyEvent.VK_SHIFT)))
stateCheck { checkInsideSearchEverywhere() }
test { actions(it) }
}
val showLineNumbersName = ActionsBundle.message("action.EditorGutterToggleGlobalLineNumbers.text")
task(LearnBundle.message("show.line.number.prefix.to.show.first")) {
text(LessonsBundle.message("goto.action.show.line.numbers.request", strong(it), strong(showLineNumbersName)))
triggerByListItemAndHighlight { item ->
val matchedValue = item as? GotoActionModel.MatchedValue
val actionWrapper = matchedValue?.value as? GotoActionModel.ActionWrapper
val action = actionWrapper?.action
action is ToggleShowLineNumbersGloballyAction
}
restoreState { !checkInsideSearchEverywhere() }
test {
waitComponent(SearchEverywhereUI::class.java)
type(it)
}
}
val lineNumbersShown = isLineNumbersShown()
task {
text(LessonsBundle.message("goto.action.first.lines.toggle", if (lineNumbersShown) 0 else 1))
stateCheck { isLineNumbersShown() == !lineNumbersShown }
showWarningIfSearchPopupClosed()
test {
ideFrame {
jList(showLineNumbersName).item(showLineNumbersName).click()
}
}
}
task {
text(LessonsBundle.message("goto.action.second.lines.toggle", if (lineNumbersShown) 0 else 1))
stateCheck { isLineNumbersShown() == lineNumbersShown }
showWarningIfSearchPopupClosed()
test {
ideFrame {
jList(showLineNumbersName).item(showLineNumbersName).click()
}
}
}
if (firstLesson) {
firstLessonCompletedMessage()
}
}
private fun TaskRuntimeContext.checkInsideSearchEverywhere(): Boolean {
return UIUtil.getParentOfType(SearchEverywhereUI::class.java, focusOwner) != null
}
private fun TaskContext.showWarningIfSearchPopupClosed() {
showWarning(LessonsBundle.message("goto.action.popup.closed.warning.message", action("GotoAction"),
LessonUtil.rawKeyStroke(KeyEvent.VK_SHIFT))) {
!checkInsideSearchEverywhere()
}
}
private fun isLineNumbersShown() = EditorSettingsExternalizable.getInstance().isLineNumbersShown
} | apache-2.0 |
JetBrains/kotlin-native | klib/src/test/testData/Objects.kt | 4 | 795 | /*
* Copyright 2010-2018 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.
*/
object A {
fun a() {}
}
class B {
companion object {
fun b() {}
}
object C {
fun c() {}
}
}
class D {
companion object E {
fun e() {}
}
}
| apache-2.0 |
jwren/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/vfilefinder/KotlinLibraryKindIndex.kt | 1 | 2349 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.vfilefinder
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.serviceOrNull
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileVisitor
import com.intellij.openapi.vfs.VirtualFileWithId
import org.jetbrains.kotlin.analysis.decompiler.stub.file.FileAttributeService
import org.jetbrains.kotlin.serialization.deserialization.MetadataPackageFragment
enum class KnownLibraryKindForIndex {
COMMON, JS, UNKNOWN
}
private val KOTLIN_LIBRARY_KIND_FILE_ATTRIBUTE: String = "kotlin-library-kind".apply {
serviceOrNull<FileAttributeService>()?.register(this, 1)
}
// TODO: Detect library kind for Jar file using IdePlatformKindResolution.
fun VirtualFile.getLibraryKindForJar(): KnownLibraryKindForIndex {
if (this !is VirtualFileWithId) return detectLibraryKindFromJarContentsForIndex(this)
val service =
serviceOrNull<FileAttributeService>()
?: return detectLibraryKindFromJarContentsForIndex(this)
service
.readEnumAttribute(KOTLIN_LIBRARY_KIND_FILE_ATTRIBUTE, this, KnownLibraryKindForIndex::class.java)
?.let { return it.value }
return detectLibraryKindFromJarContentsForIndex(this).also { newValue ->
service.writeEnumAttribute(KOTLIN_LIBRARY_KIND_FILE_ATTRIBUTE, this, newValue)
}
}
private fun detectLibraryKindFromJarContentsForIndex(jarRoot: VirtualFile): KnownLibraryKindForIndex {
var result: KnownLibraryKindForIndex? = null
VfsUtil.visitChildrenRecursively(jarRoot, object : VirtualFileVisitor<Unit>() {
override fun visitFile(file: VirtualFile): Boolean =
when (file.extension) {
"class" -> false
"kjsm" -> {
result = KnownLibraryKindForIndex.JS
false
}
MetadataPackageFragment.METADATA_FILE_EXTENSION -> {
result = KnownLibraryKindForIndex.COMMON
false
}
else -> true
}
})
return result ?: KnownLibraryKindForIndex.UNKNOWN
}
| apache-2.0 |
jwren/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/autoImports/minusOperator.after.kt | 5 | 550 | // "Import" "true"
// ERROR: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: <br>public fun String.minus(i: Integer): String defined in h in file minusOperator.before.Main.kt<br>public fun String.minus(str: String): String defined in h in file minusOperator.before.Main.kt
// COMPILER_ARGUMENTS: -XXLanguage:-NewInference
package h
import util.minus
interface H
fun f(h: H?) {
h <caret>- "other"
}
fun String.minus(str: String) = ""
fun String.minus(i: Integer) = ""
/* IGNORE_FIR */ | apache-2.0 |
jwren/intellij-community | java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/ModuleHighlightingTest.kt | 1 | 31467 | // 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.java.codeInsight.daemon
import com.intellij.codeInsight.daemon.impl.JavaHighlightInfoTypes
import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil
import com.intellij.codeInsight.intention.IntentionActionDelegate
import com.intellij.codeInspection.IllegalDependencyOnInternalPackageInspection
import com.intellij.codeInspection.deprecation.DeprecationInspection
import com.intellij.codeInspection.deprecation.MarkedForRemovalInspection
import com.intellij.java.testFramework.fixtures.LightJava9ModulesCodeInsightFixtureTestCase
import com.intellij.java.testFramework.fixtures.MultiModuleJava9ProjectDescriptor.ModuleDescriptor
import com.intellij.java.testFramework.fixtures.MultiModuleJava9ProjectDescriptor.ModuleDescriptor.*
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiManager
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.ProjectScope
import com.intellij.psi.util.PsiUtilCore
import org.assertj.core.api.Assertions.assertThat
import java.util.jar.JarFile
class ModuleHighlightingTest : LightJava9ModulesCodeInsightFixtureTestCase() {
override fun setUp() {
super.setUp()
addFile("module-info.java", "module M2 { }", M2)
addFile("module-info.java", "module M3 { }", M3)
}
fun testPackageStatement() {
highlight("package pkg;")
highlight("""
<error descr="A module file should not have 'package' statement">package pkg;</error>
module M { }""".trimIndent())
fixes("<caret>package pkg;\nmodule M { }", arrayOf("DeleteElementFix", "FixAllHighlightingProblems"))
}
fun testSoftKeywords() {
addFile("pkg/module/C.java", "package pkg.module;\npublic class C { }")
myFixture.configureByText("module-info.java", "module M { exports pkg.module; }")
val keywords = myFixture.doHighlighting().filter { it.type == JavaHighlightInfoTypes.JAVA_KEYWORD }
assertEquals(2, keywords.size)
assertEquals(TextRange(0, 6), TextRange(keywords[0].startOffset, keywords[0].endOffset))
assertEquals(TextRange(11, 18), TextRange(keywords[1].startOffset, keywords[1].endOffset))
}
fun testDependencyOnIllegalPackage() {
addFile("a/secret/Secret.java", "package a.secret;\npublic class Secret {}", M4)
addFile("module-info.java", "module M4 { exports pkg.module; }", M4)
myFixture.enableInspections(IllegalDependencyOnInternalPackageInspection())
myFixture.configureByText("C.java", "package pkg;\n" +
"import a.secret.*;\n" +
"public class C {<error descr=\"Illegal dependency: module 'M4' doesn't export package 'a.secret'\">Secret</error> s; }")
myFixture.checkHighlighting()
}
fun testWrongFileName() {
highlight("M.java", """/* ... */ <error descr="Module declaration should be in a file named 'module-info.java'">module M</error> { }""")
}
fun testFileDuplicate() {
addFile("pkg/module-info.java", """module M.bis { }""")
highlight("""<error descr="'module-info.java' already exists in the module">module M</error> { }""")
}
fun testFileDuplicateInTestRoot() {
addTestFile("module-info.java", """module M.test { }""")
highlight("""module M { }""")
}
fun testWrongFileLocation() {
highlight("pkg/module-info.java", """<error descr="Module declaration should be located in a module's source root">module M</error> { }""")
}
fun testIncompatibleModifiers() {
highlight("""
module M {
requires static transitive M2;
requires <error descr="Modifier 'private' not allowed here">private</error> <error descr="Modifier 'volatile' not allowed here">volatile</error> M3;
}""".trimIndent())
}
fun testAnnotations() {
highlight("""@Deprecated <error descr="'@Override' not applicable to module">@Override</error> module M { }""")
}
fun testDuplicateStatements() {
addFile("pkg/main/C.java", "package pkg.main;\npublic class C { }")
addFile("pkg/main/Impl.java", "package pkg.main;\npublic class Impl extends C { }")
highlight("""
import pkg.main.C;
module M {
requires M2;
<error descr="Duplicate 'requires': M2">requires M2;</error>
exports pkg.main;
<error descr="Duplicate 'exports': pkg.main">exports pkg. main;</error>
opens pkg.main;
<error descr="Duplicate 'opens': pkg.main">opens pkg. main;</error>
uses C;
<error descr="Duplicate 'uses': pkg.main.C">uses pkg. main . /*...*/ C;</error>
provides pkg .main .C with pkg.main.Impl;
<error descr="Duplicate 'provides': pkg.main.C">provides C with pkg. main. Impl;</error>
}""".trimIndent())
}
fun testUnusedServices() {
addFile("pkg/main/C1.java", "package pkg.main;\npublic class C1 { }")
addFile("pkg/main/C2.java", "package pkg.main;\npublic class C2 { }")
addFile("pkg/main/C3.java", "package pkg.main;\npublic class C3 { }")
addFile("pkg/main/Impl1.java", "package pkg.main;\npublic class Impl1 extends C1 { }")
addFile("pkg/main/Impl2.java", "package pkg.main;\npublic class Impl2 extends C2 { }")
addFile("pkg/main/Impl3.java", "package pkg.main;\npublic class Impl3 extends C3 { }")
highlight("""
import pkg.main.C2;
import pkg.main.C3;
module M {
uses C2;
uses pkg.main.C3;
provides pkg.main.<warning descr="Service interface provided but not exported or used">C1</warning> with pkg.main.Impl1;
provides pkg.main.C2 with pkg.main.Impl2;
provides C3 with pkg.main.Impl3;
}""".trimIndent())
}
fun testRequires() {
addFile("module-info.java", "module M2 { requires M1 }", M2)
addFile(JarFile.MANIFEST_NAME, "Manifest-Version: 1.0\nAutomatic-Module-Name: all.fours\n", M4)
highlight("""
module M1 {
requires <error descr="Module not found: M.missing">M.missing</error>;
requires <error descr="Cyclic dependence: M1">M1</error>;
requires <error descr="Cyclic dependence: M1, M2">M2</error>;
requires <error descr="Module is not in dependencies: M3">M3</error>;
requires <warning descr="Ambiguous module reference: lib.auto">lib.auto</warning>;
requires lib.multi.release;
requires <warning descr="Ambiguous module reference: lib.named">lib.named</warning>;
requires lib.claimed;
requires all.fours;
}""".trimIndent())
addFile(JarFile.MANIFEST_NAME, "Manifest-Version: 1.0\n", M4)
highlight("""module M1 { requires <error descr="Module not found: all.fours">all.fours</error>; }""")
addFile(JarFile.MANIFEST_NAME, "Manifest-Version: 1.0\nAutomatic-Module-Name: all.fours\n", M4)
highlight("""module M1 { requires all.fours; }""")
}
fun testExports() {
addFile("pkg/empty/package-info.java", "package pkg.empty;")
addFile("pkg/main/C.java", "package pkg.main;\nclass C { }")
highlight("""
module M {
exports <error descr="Package not found: pkg.missing.unknown">pkg.missing.unknown</error>;
exports <error descr="Package is empty: pkg.empty">pkg.empty</error>;
exports pkg.main to <warning descr="Module not found: M.missing">M.missing</warning>, M2, <error descr="Duplicate 'exports' target: M2">M2</error>;
}""".trimIndent())
addTestFile("pkg/tests/T.java", "package pkg.tests;\nclass T { }", M_TEST)
highlight("module-info.java", "module M { exports pkg.tests; }".trimIndent(), M_TEST, true)
}
fun testOpens() {
addFile("pkg/main/C.java", "package pkg.main;\nclass C { }")
addFile("pkg/resources/resource.txt", "...")
highlight("""
module M {
opens <warning descr="Package not found: pkg.missing.unknown">pkg.missing.unknown</warning>;
opens pkg.main to <warning descr="Module not found: M.missing">M.missing</warning>, M2, <error descr="Duplicate 'opens' target: M2">M2</error>;
opens pkg.resources;
}""".trimIndent())
addTestFile("pkg/tests/T.java", "package pkg.tests;\nclass T { }", M_TEST)
highlight("module-info.java", "module M { opens pkg.tests; }".trimIndent(), M_TEST, true)
}
fun testWeakModule() {
highlight("""open module M { <error descr="'opens' is not allowed in an open module">opens pkg.missing;</error> }""")
}
fun testUses() {
addFile("pkg/main/C.java", "package pkg.main;\nclass C { void m(); }")
addFile("pkg/main/O.java", "package pkg.main;\npublic class O {\n public class I { void m(); }\n}")
addFile("pkg/main/E.java", "package pkg.main;\npublic enum E { }")
highlight("""
module M {
uses pkg.<error descr="Cannot resolve symbol 'main'">main</error>;
uses pkg.main.<error descr="Cannot resolve symbol 'X'">X</error>;
uses pkg.main.<error descr="'pkg.main.C' is not public in 'pkg.main'. Cannot be accessed from outside package">C</error>;
uses pkg.main.<error descr="The service definition is an enum: E">E</error>;
uses pkg.main.O.I;
uses pkg.main.O.I.<error descr="Cannot resolve symbol 'm'">m</error>;
}""".trimIndent())
}
fun testProvides() {
addFile("pkg/main/C.java", "package pkg.main;\npublic interface C { }")
addFile("pkg/main/CT.java", "package pkg.main;\npublic interface CT<T> { }")
addFile("pkg/main/Impl1.java", "package pkg.main;\nclass Impl1 { }")
addFile("pkg/main/Impl2.java", "package pkg.main;\npublic class Impl2 { }")
addFile("pkg/main/Impl3.java", "package pkg.main;\npublic abstract class Impl3 implements C { }")
addFile("pkg/main/Impl4.java", "package pkg.main;\npublic class Impl4 implements C {\n public Impl4(String s) { }\n}")
addFile("pkg/main/Impl5.java", "package pkg.main;\npublic class Impl5 implements C {\n protected Impl5() { }\n}")
addFile("pkg/main/Impl6.java", "package pkg.main;\npublic class Impl6 implements C { }")
addFile("pkg/main/Impl7.java", "package pkg.main;\npublic class Impl7 {\n public static void provider();\n}")
addFile("pkg/main/Impl8.java", "package pkg.main;\npublic class Impl8 {\n public static C provider();\n}")
addFile("pkg/main/Impl9.java", "package pkg.main;\npublic class Impl9 {\n public class Inner implements C { }\n}")
addFile("pkg/main/Impl10.java", "package pkg.main;\npublic class Impl10<T> implements CT<T> {\n private Impl10() { }\n public static CT provider();\n}")
addFile("module-info.java", "module M2 {\n exports pkg.m2;\n}", M2)
addFile("pkg/m2/C.java", "package pkg.m2;\npublic class C { }", M2)
addFile("pkg/m2/Impl.java", "package pkg.m2;\npublic class Impl extends C { }", M2)
highlight("""
import pkg.main.Impl6;
module M {
requires M2;
provides pkg.main.C with pkg.main.<error descr="Cannot resolve symbol 'NoImpl'">NoImpl</error>;
provides pkg.main.C with pkg.main.<error descr="'pkg.main.Impl1' is not public in 'pkg.main'. Cannot be accessed from outside package">Impl1</error>;
provides pkg.main.C with pkg.main.<error descr="The service implementation type must be a subtype of the service interface type, or have a public static no-args 'provider' method">Impl2</error>;
provides pkg.main.C with pkg.main.<error descr="The service implementation is an abstract class: Impl3">Impl3</error>;
provides pkg.main.C with pkg.main.<error descr="The service implementation does not have a public default constructor: Impl4">Impl4</error>;
provides pkg.main.C with pkg.main.<error descr="The service implementation does not have a public default constructor: Impl5">Impl5</error>;
provides pkg.main.C with pkg.main.Impl6, <error descr="Duplicate implementation: pkg.main.Impl6">Impl6</error>;
provides pkg.main.C with pkg.main.<error descr="The 'provider' method return type must be a subtype of the service interface type: Impl7">Impl7</error>;
provides pkg.main.C with pkg.main.Impl8;
provides pkg.main.C with pkg.main.Impl9.<error descr="The service implementation is an inner class: Inner">Inner</error>;
provides pkg.main.CT with pkg.main.Impl10;
provides pkg.m2.C with pkg.m2.<error descr="The service implementation must be defined in the same module as the provides directive">Impl</error>;
}""".trimIndent())
}
fun testQuickFixes() {
addFile("pkg/main/impl/X.java", "package pkg.main.impl;\npublic class X { }")
addFile("module-info.java", "module M2 { exports pkg.m2; }", M2)
addFile("pkg/m2/C2.java", "package pkg.m2;\npublic class C2 { }", M2)
addFile("pkg/m3/C3.java", "package pkg.m3;\npublic class C3 { }", M3)
addFile("module-info.java", "module M6 { exports pkg.m6; }", M6)
addFile("pkg/m6/C6.java", "package pkg.m6;\nimport pkg.m8.*;\nimport java.util.function.*;\npublic class C6 { public void m(Consumer<C8> c) { } }", M6)
addFile("module-info.java", "module M8 { exports pkg.m8; }", M8)
addFile("pkg/m8/C8.java", "package pkg.m8;\npublic class C8 { }", M8)
fixes("module M { requires <caret>M.missing; }", arrayOf())
fixes("module M { requires <caret>M3; }", arrayOf("AddModuleDependencyFix"))
fixes("module M { exports pkg.main.impl to <caret>M3; }", arrayOf())
fixes("module M { exports <caret>pkg.missing; }", arrayOf("CreateClassInPackageInModuleFix"))
fixes("module M { exports <caret>pkg.m3; }", arrayOf())
fixes("module M { uses pkg.m3.<caret>C3; }", arrayOf("AddModuleDependencyFix"))
fixes("pkg/main/C.java", "package pkg.main;\nimport <caret>pkg.m2.C2;", arrayOf("AddRequiresDirectiveFix"))
addFile("module-info.java", "module M { requires M6; }")
addFile("pkg/main/Util.java", "package pkg.main;\nclass Util {\n static <T> void sink(T t) { }\n}")
fixes("pkg/main/C.java", "package pkg.main;\nimport pkg.m6.*;class C {{ new C6().m(<caret>Util::sink); }}", arrayOf("AddRequiresDirectiveFix"))
fixes("pkg/main/C.java", "package pkg.main;\nimport pkg.m6.*;class C {{ new C6().m(<caret>t -> Util.sink(t)); }}", arrayOf("AddRequiresDirectiveFix"))
addFile("module-info.java", "module M2 { }", M2)
fixes("module M { requires M2; uses <caret>pkg.m2.C2; }", arrayOf("AddExportsDirectiveFix"))
fixes("pkg/main/C.java", "package pkg.main;\nimport <caret>pkg.m2.C2;", arrayOf("AddExportsDirectiveFix"))
addFile("pkg/main/S.java", "package pkg.main;\npublic class S { }")
fixes("module M { provides pkg.main.<caret>S with pkg.main.S; }", arrayOf("AddExportsDirectiveFix", "AddUsesDirectiveFix"))
}
fun testPackageAccessibility() = doTestPackageAccessibility(moduleFileInTests = false, checkFileInTests = false)
fun testPackageAccessibilityInNonModularTest() = doTestPackageAccessibility(moduleFileInTests = true, checkFileInTests = false)
fun testPackageAccessibilityInModularTest() = doTestPackageAccessibility(moduleFileInTests = true, checkFileInTests = true)
private fun doTestPackageAccessibility(moduleFileInTests: Boolean = false, checkFileInTests: Boolean = false) {
val moduleFileText = "module M { requires M2; requires M6; requires lib.named; requires lib.auto; }"
if (moduleFileInTests) addTestFile("module-info.java", moduleFileText) else addFile("module-info.java", moduleFileText)
addFile("module-info.java", "module M2 { exports pkg.m2; exports pkg.m2.impl to close.friends.only; }", M2)
addFile("pkg/m2/C2.java", "package pkg.m2;\npublic class C2 { }", M2)
addFile("pkg/m2/impl/C2Impl.java", "package pkg.m2.impl;\nimport pkg.m2.C2;\npublic class C2Impl { public static int I; public static C2 make() {} }", M2)
addFile("pkg/sub/C2X.java", "package pkg.sub;\npublic class C2X { }", M2)
addFile("pkg/unreachable/C3.java", "package pkg.unreachable;\npublic class C3 { }", M3)
addFile("pkg/m4/C4.java", "package pkg.m4;\npublic class C4 { }", M4)
addFile("module-info.java", "module M5 { exports pkg.m5; }", M5)
addFile("pkg/m5/C5.java", "package pkg.m5;\npublic class C5 { }", M5)
addFile("module-info.java", "module M6 { requires transitive M7; exports pkg.m6.inner; }", M6)
addFile("pkg/sub/C6X.java", "package pkg.sub;\npublic class C6X { }", M6)
addFile("pkg/m6/C6_1.java", "package pkg.m6.inner;\npublic class C6_1 {}", M6)
//addFile("pkg/m6/C6_2.kt", "package pkg.m6.inner\n class C6_2", M6) TODO: uncomment to fail the test
addFile("module-info.java", "module M7 { exports pkg.m7; }", M7)
addFile("pkg/m7/C7.java", "package pkg.m7;\npublic class C7 { }", M7)
var checkFileText = """
import pkg.m2.C2;
import pkg.m2.*;
import <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl;
import <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.*;
import <error descr="Package 'pkg.m4' is declared in the unnamed module, but module 'M' does not read it">pkg.m4</error>.C4;
import <error descr="Package 'pkg.m5' is declared in module 'M5', but module 'M' does not read it">pkg.m5</error>.C5;
import pkg.m7.C7;
import <error descr="Package 'pkg.sub' is declared in module 'M2', which does not export it to module 'M'">pkg.sub</error>.*;
import <error descr="Package not found: pkg.unreachable">pkg.unreachable</error>.*;
import pkg.lib1.LC1;
import <error descr="Package 'pkg.lib1.impl' is declared in module 'lib.named', which does not export it to module 'M'">pkg.lib1.impl</error>.LC1Impl;
import <error descr="Package 'pkg.lib1.impl' is declared in module 'lib.named', which does not export it to module 'M'">pkg.lib1.impl</error>.*;
import pkg.lib2.LC2;
import pkg.lib2.impl.LC2Impl;
import static <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl.make;
import java.util.List;
import java.util.function.Supplier;
import <error descr="Package 'pkg.libInvalid' is declared in module with an invalid name ('lib.invalid.1.2')">pkg.libInvalid</error>.LCInv;
import pkg.m6.inner.C6_1;
//import pkg.m6.inner.C6_2;
/** See also {@link C2Impl#I} and {@link C2Impl#make} */
class C {{
<error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">C2Impl</error>.I = 0;
<error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">C2Impl</error>.make();
<error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl.I = 1;
<error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl.make();
List<<error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">C2Impl</error>> l1 = null;
List<<error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl> l2 = null;
Supplier<C2> s1 = <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">C2Impl</error>::make;
Supplier<C2> s2 = <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl::make;
}}
""".trimIndent()
if (moduleFileInTests != checkFileInTests) {
checkFileText = Regex("(<error [^>]+>)([^<]+)(</error>)").replace(checkFileText) {
if (it.value.contains("unreachable")) it.value else it.groups[2]!!.value
}
}
highlight("test.java", checkFileText, isTest = checkFileInTests)
}
fun testPackageAccessibilityOverTestScope() {
addFile("module-info.java", "module M2 { exports pkg.m2; exports pkg.m2.impl to close.friends.only; }", M2)
addFile("pkg/m2/C2.java", "package pkg.m2;\npublic class C2 { }", M2)
addFile("pkg/m2/impl/C2Impl.java", "package pkg.m2.impl;\nimport pkg.m2.C2;\npublic class C2Impl { public static int I; public static C2 make() {} }", M2)
highlight("module-info.java", "module M.test { requires M2; }", M_TEST, isTest = true)
val highlightText = """
import pkg.m2.C2;
import pkg.m2.*;
import <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M.test'">pkg.m2.impl</error>.C2Impl;
import <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M.test'">pkg.m2.impl</error>.*;
""".trimIndent()
highlight("test.java", highlightText, M_TEST, isTest = true)
}
fun testPrivateJdkPackage() {
addFile("module-info.java", "module M { }")
highlight("test.java", """
import <error descr="Package 'jdk.internal' is declared in module 'java.base', which does not export it to module 'M'">jdk.internal</error>.*;
""".trimIndent())
}
fun testPrivateJdkPackageFromUnnamed() {
highlight("test.java", """
import <error descr="Package 'jdk.internal' is declared in module 'java.base', which does not export it to the unnamed module">jdk.internal</error>.*;
""".trimIndent())
}
fun testNonRootJdkModule() {
highlight("test.java", """
import <error descr="Package 'java.non.root' is declared in module 'java.non.root', which is not in the module graph">java.non.root</error>.*;
""".trimIndent())
}
fun testUpgradeableModuleOnClasspath() {
highlight("test.java", """
import java.xml.bind.*;
import java.xml.bind.C;
""".trimIndent())
}
fun testUpgradeableModuleOnModulePath() {
myFixture.enableInspections(DeprecationInspection(), MarkedForRemovalInspection())
highlight("""
module M {
requires <error descr="'java.xml.bind' is deprecated and marked for removal">java.xml.bind</error>;
requires java.xml.ws;
}""".trimIndent())
}
fun testLinearModuleGraphBug() {
addFile("module-info.java", "module M6 { requires M7; }", M6)
addFile("module-info.java", "module M7 { }", M7)
highlight("module M { requires M6; }")
}
fun testCorrectedType() {
addFile("module-info.java", "module M { requires M6; requires lib.named; }")
addFile("module-info.java", "module M6 { requires lib.named; exports pkg;}", M6)
addFile("pkg/A.java", "package pkg; public class A {public static void foo(java.util.function.Supplier<pkg.lib1.LC1> f){}}", M6)
highlight("pkg/Usage.java","import pkg.lib1.LC1; class Usage { {pkg.A.foo(LC1::new);} }")
}
fun testDeprecations() {
myFixture.enableInspections(DeprecationInspection(), MarkedForRemovalInspection())
addFile("module-info.java", "@Deprecated module M2 { }", M2)
highlight("""module M { requires <warning descr="'M2' is deprecated">M2</warning>; }""")
}
fun testMarkedForRemoval() {
myFixture.enableInspections(DeprecationInspection(), MarkedForRemovalInspection())
addFile("module-info.java", "@Deprecated(forRemoval=true) module M2 { }", M2)
highlight("""module M { requires <error descr="'M2' is deprecated and marked for removal">M2</error>; }""")
}
fun testPackageConflicts() {
addFile("pkg/collision2/C2.java", "package pkg.collision2;\npublic class C2 { }", M2)
addFile("pkg/collision4/C4.java", "package pkg.collision4;\npublic class C4 { }", M4)
addFile("pkg/collision7/C7.java", "package pkg.collision7;\npublic class C7 { }", M7)
addFile("module-info.java", "module M2 { exports pkg.collision2; }", M2)
addFile("module-info.java", "module M4 { exports pkg.collision4 to M88; }", M4)
addFile("module-info.java", "module M6 { requires transitive M7; }", M6)
addFile("module-info.java", "module M7 { exports pkg.collision7 to M6; }", M7)
addFile("module-info.java", "module M { requires M2; requires M4; requires M6; requires lib.auto; }")
highlight("test1.java", """<error descr="Package 'pkg.collision2' exists in another module: M2">package pkg.collision2;</error>""")
highlight("test2.java", """package pkg.collision4;""")
highlight("test3.java", """package pkg.collision7;""")
highlight("test4.java", """<error descr="Package 'java.util' exists in another module: java.base">package java.util;</error>""")
highlight("test5.java", """<error descr="Package 'pkg.lib2' exists in another module: lib.auto">package pkg.lib2;</error>""")
}
fun testClashingReads1() {
addFile("pkg/collision/C2.java", "package pkg.collision;\npublic class C2 { }", M2)
addFile("pkg/collision/C7.java", "package pkg.collision;\npublic class C7 { }", M7)
addFile("module-info.java", "module M2 { exports pkg.collision; }", M2)
addFile("module-info.java", "module M6 { requires transitive M7; }", M6)
addFile("module-info.java", "module M7 { exports pkg.collision; }", M7)
highlight("""
<error descr="Module 'M' reads package 'pkg.collision' from both 'M2' and 'M7'">module M</error> {
requires M2;
requires M6;
}""".trimIndent())
}
fun testClashingReads2() {
addFile("pkg/collision/C2.java", "package pkg.collision;\npublic class C2 { }", M2)
addFile("pkg/collision/C4.java", "package pkg.collision;\npublic class C4 { }", M4)
addFile("module-info.java", "module M2 { exports pkg.collision; }", M2)
addFile("module-info.java", "module M4 { exports pkg.collision to somewhere; }", M4)
highlight("module M { requires M2; requires M4; }")
}
fun testClashingReads3() {
addFile("pkg/lib2/C2.java", "package pkg.lib2;\npublic class C2 { }", M2)
addFile("module-info.java", "module M2 { exports pkg.lib2; }", M2)
highlight("""
<error descr="Module 'M' reads package 'pkg.lib2' from both 'M2' and 'lib.auto'">module M</error> {
requires M2;
requires <warning descr="Ambiguous module reference: lib.auto">lib.auto</warning>;
}""".trimIndent())
}
fun testClashingReads4() {
addFile("module-info.java", "module M2 { requires transitive lib.auto; }", M2)
addFile("module-info.java", "module M4 { requires transitive lib.auto; }", M4)
highlight("module M { requires M2; requires M4; }")
}
fun testInaccessibleMemberType() {
addFile("module-info.java", "module C { exports pkg.c; }", M8)
addFile("module-info.java", "module B { requires C; exports pkg.b; }", M6)
addFile("module-info.java", "module A { requires B; }")
addFile("pkg/c/C.java", "package pkg.c;\npublic class C { }", M8)
addFile("pkg/b/B.java", """
package pkg.b;
import pkg.c.C;
public class B {
private static class I { }
public C f1;
public I f2;
public C m1(C p1, Class<? extends C> p2) { return new C(); }
public I m2(I p1, Class<? extends I> p2) { return new I(); }
}""".trimIndent(), M6)
highlight("pkg/a/A.java", """
package pkg.a;
import pkg.b.B;
public class A {
void test() {
B exposer = new B();
exposer.f1 = null;
exposer.f2 = null;
Object o1 = exposer.m1(null, null);
Object o2 = exposer.m2(null, null);
}
}""".trimIndent())
}
fun testAccessingDefaultPackage() {
addFile("X.java", "public class X {\n public static class XX extends X { }\n}")
highlight("""
module M {
uses <error descr="Class 'X' is in the default package">X</error>;
provides <error descr="Class 'X' is in the default package">X</error> with <error descr="Class 'X' is in the default package">X</error>.XX;
}""".trimIndent())
}
fun testAutomaticModuleFromIdeaModule() {
highlight("module-info.java", """
module M {
requires ${M6.moduleName.replace('_', '.')}; // `light.idea.test.m6`
requires <error descr="Module not found: m42">m42</error>;
}""".trimIndent())
addFile("p/B.java", "package p; public class B {}", module = M6)
addFile("p/C.java", "package p; public class C {}", module = M4)
highlight("A.java", """
public class A extends p.B {
private <error descr="Package 'p' is declared in the unnamed module, but module 'M' does not read it">p</error>.C c;
}
""".trimIndent())
}
fun testAutomaticModuleFromManifest() {
addResourceFile(JarFile.MANIFEST_NAME, "Automatic-Module-Name: m6.bar\n", module = M6)
highlight("module-info.java", "module M { requires m6.bar; }")
addFile("p/B.java", "package p; public class B {}", module = M6)
addFile("p/C.java", "package p; public class C {}", module = M4)
highlight("A.java", """
public class A extends p.B {
private <error descr="Package 'p' is declared in the unnamed module, but module 'M' does not read it">p</error>.C c;
}
""".trimIndent())
}
fun testAutomaticModuleFromManifestHighlighting() {
addResourceFile(JarFile.MANIFEST_NAME, "Automatic-Module-Name: m6.bar\n", module = M6)
addFile("p/B.java", "package p; public class B {}", M7)
addFile("module-info.java", "module M4 { exports p; }", M7)
highlight("A.java", """
public class A extends p.B {}
""".trimIndent(), M6, false)
}
fun testLightModuleDescriptorCaching() {
val libClass = myFixture.javaFacade.findClass("pkg.lib2.LC2", ProjectScope.getLibrariesScope(project))!!
val libModule = JavaModuleGraphUtil.findDescriptorByElement(libClass)!!
PsiManager.getInstance(project).dropPsiCaches()
assertSame(libModule, JavaModuleGraphUtil.findDescriptorByElement(libClass)!!)
ProjectRootManager.getInstance(project).incModificationCount()
assertNotSame(libModule, JavaModuleGraphUtil.findDescriptorByElement(libClass)!!)
}
fun testModuleInSources() {
val classInLibrary = myFixture.javaFacade.findClass("lib.named.C", GlobalSearchScope.allScope(project))!!
val elementInSources = classInLibrary.navigationElement
assertThat(JavaModuleGraphUtil.findDescriptorByFile(PsiUtilCore.getVirtualFile(elementInSources), project)).isNotNull
}
//<editor-fold desc="Helpers.">
private fun highlight(text: String) = highlight("module-info.java", text)
private fun highlight(path: String, text: String, module: ModuleDescriptor = MAIN, isTest: Boolean = false) {
myFixture.configureFromExistingVirtualFile(if (isTest) addTestFile(path, text, module) else addFile(path, text, module))
myFixture.checkHighlighting()
}
private fun fixes(text: String, fixes: Array<String>) = fixes("module-info.java", text, fixes)
private fun fixes(path: String, text: String, fixes: Array<String>) {
myFixture.configureFromExistingVirtualFile(addFile(path, text))
val available = myFixture.availableIntentions
.map { IntentionActionDelegate.unwrap(it)::class.java }
.filter { it.name.startsWith("com.intellij.codeInsight.") }
.map { it.simpleName }
assertThat(available).containsExactlyInAnyOrder(*fixes)
}
//</editor-fold>
}
| apache-2.0 |
sureshg/kotlin-starter | buildSrc/src/main/kotlin/tasks/MyExecTask.kt | 1 | 664 | package tasks
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.*
/**
* A custom exec task.
*/
open class MyExecTask : DefaultTask() {
init {
group = "misc"
description = "Custom Exec Task for ${project.name}"
}
@Input var command = listOf("ls")
@TaskAction fun run() {
println("Executing $command for ${this.project.name}.")
project.exec {
workingDir = project.buildDir
commandLine = command
}
}
}
fun Project.myExecTask() = task<MyExecTask>("myExecTask") | apache-2.0 |
JetBrains/intellij-community | plugins/kotlin/completion/impl-shared/src/org/jetbrains/kotlin/idea/completion/implCommon/handlers/NamedArgumentInsertHandler.kt | 1 | 3074 | /*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.completion.implCommon.handlers
import com.intellij.codeInsight.completion.InsertHandler
import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.KtValueArgumentList
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
class NamedArgumentInsertHandler(private val parameterName: Name) : InsertHandler<LookupElement> {
override fun handleInsert(context: InsertionContext, item: LookupElement) {
val editor = context.editor
val (textAfterCompletionArea, doNeedTrailingSpace) = context.file.findElementAt(context.tailOffset).let { psi ->
psi?.siblings()?.firstOrNull { it !is PsiWhiteSpace }?.text to (psi !is PsiWhiteSpace)
}
var text: String
var caretOffset: Int
if (textAfterCompletionArea == "=") {
// User tries to manually rename existing named argument. We shouldn't add trailing `=` in such case
text = parameterName.render()
caretOffset = text.length
} else {
// For complicated cases let's try to normalize the document firstly in order to avoid parsing errors due to incomplete code
editor.document.replaceString(context.startOffset, context.tailOffset, "")
PsiDocumentManager.getInstance(context.project).commitDocument(editor.document)
val nextArgument = context.file.findElementAt(context.startOffset)?.siblings()
?.firstOrNull { it !is PsiWhiteSpace }?.parentsWithSelf?.takeWhile { it !is KtValueArgumentList }
?.firstIsInstanceOrNull<KtValueArgument>()
if (nextArgument?.isNamed() == true) {
if (doNeedTrailingSpace) {
text = "${parameterName.render()} = , "
caretOffset = text.length - 2
} else {
text = "${parameterName.render()} = ,"
caretOffset = text.length - 1
}
} else {
text = "${parameterName.render()} = "
caretOffset = text.length
}
}
if (context.file.findElementAt(context.startOffset - 1)?.let { it !is PsiWhiteSpace && it.text != "(" } == true) {
text = " $text"
caretOffset++
}
editor.document.replaceString(context.startOffset, context.tailOffset, text)
editor.caretModel.moveToOffset(context.startOffset + caretOffset)
}
}
| apache-2.0 |
djkovrik/YapTalker | app/src/main/java/com/sedsoftware/yaptalker/presentation/custom/glide/UiOnProgressListener.kt | 1 | 195 | package com.sedsoftware.yaptalker.presentation.custom.glide
interface UiOnProgressListener {
fun onProgress(bytesRead: Long, expectedLength: Long)
fun getGranualityPercentage(): Float
}
| apache-2.0 |
androidx/androidx | room/room-runtime/src/test/java/androidx/room/RoomSQLiteQueryTest.kt | 3 | 4399 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room
import androidx.room.RoomSQLiteQuery.Companion.acquire
import androidx.sqlite.db.SupportSQLiteProgram
import com.google.common.truth.Truth.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
@RunWith(JUnit4::class)
class RoomSQLiteQueryTest {
@Before
fun clear() {
RoomSQLiteQuery.queryPool.clear()
}
@Test
fun acquireBasic() {
val query = acquire("abc", 3)
assertThat(query.sql).isEqualTo("abc")
assertThat(query.argCount).isEqualTo(3)
assertThat(query.blobBindings.size).isEqualTo(4)
assertThat(query.longBindings.size).isEqualTo(4)
assertThat(query.stringBindings.size).isEqualTo(4)
assertThat(query.doubleBindings.size).isEqualTo(4)
}
@Test
fun acquireSameSizeAgain() {
val query = acquire("abc", 3)
query.release()
assertThat(acquire("blah", 3)).isSameInstanceAs(query)
}
@Test
fun acquireSameSizeWithoutRelease() {
val query = acquire("abc", 3)
assertThat(
acquire("fda", 3)
).isNotSameInstanceAs(query)
}
@Test
fun bindings() {
val query = acquire("abc", 6)
val myBlob = ByteArray(3)
val myLong = 3L
val myDouble = 7.0
val myString = "ss"
query.bindBlob(1, myBlob)
query.bindLong(2, myLong)
query.bindNull(3)
query.bindDouble(4, myDouble)
query.bindString(5, myString)
query.bindNull(6)
val program: SupportSQLiteProgram = mock()
query.bindTo(program)
verify(program).bindBlob(1, myBlob)
verify(program).bindLong(2, myLong)
verify(program).bindNull(3)
verify(program).bindDouble(4, myDouble)
verify(program).bindString(5, myString)
verify(program).bindNull(6)
}
@Test
fun dontKeepSameSizeTwice() {
val query1 = acquire("abc", 3)
val query2 = acquire("zx", 3)
val query3 = acquire("qw", 0)
query1.release()
query2.release()
assertThat(RoomSQLiteQuery.queryPool.size).isEqualTo(1)
query3.release()
assertThat(RoomSQLiteQuery.queryPool.size).isEqualTo(2)
}
@Test
fun returnExistingForSmallerSize() {
val query = acquire("abc", 3)
query.release()
assertThat(acquire("dsa", 2)).isSameInstanceAs(query)
}
@Test
fun returnNewForBigger() {
val query = acquire("abc", 3)
query.release()
assertThat(
acquire("dsa", 4)
).isNotSameInstanceAs(query)
}
@Test
fun pruneCache() {
for (i in 0 until RoomSQLiteQuery.POOL_LIMIT) {
acquire("dsdsa", i).release()
}
pruneCacheTest()
}
@Test
fun pruneCacheReverseInsertion() {
val queries: MutableList<RoomSQLiteQuery> = ArrayList()
for (i in RoomSQLiteQuery.POOL_LIMIT - 1 downTo 0) {
queries.add(acquire("dsdsa", i))
}
for (query in queries) {
query.release()
}
pruneCacheTest()
}
private fun pruneCacheTest() {
assertThat(
RoomSQLiteQuery.queryPool.size
).isEqualTo(RoomSQLiteQuery.POOL_LIMIT)
acquire("dsadsa", RoomSQLiteQuery.POOL_LIMIT + 1).release()
assertThat(
RoomSQLiteQuery.queryPool.size
).isEqualTo(RoomSQLiteQuery.DESIRED_POOL_SIZE)
val itr: Iterator<RoomSQLiteQuery> = RoomSQLiteQuery.queryPool.values.iterator()
for (i in 0 until RoomSQLiteQuery.DESIRED_POOL_SIZE) {
assertThat(itr.next().capacity).isEqualTo(i)
}
}
} | apache-2.0 |
djkovrik/YapTalker | app/src/main/java/com/sedsoftware/yaptalker/presentation/mapper/UserProfileModelMapper.kt | 1 | 1590 | package com.sedsoftware.yaptalker.presentation.mapper
import com.sedsoftware.yaptalker.domain.entity.base.UserProfile
import com.sedsoftware.yaptalker.presentation.mapper.util.TextTransformer
import com.sedsoftware.yaptalker.presentation.model.base.UserProfileModel
import io.reactivex.functions.Function
import javax.inject.Inject
class UserProfileModelMapper @Inject constructor(
private val textTransformer: TextTransformer
) : Function<UserProfile, UserProfileModel> {
override fun apply(profile: UserProfile): UserProfileModel =
UserProfileModel(
nickname = profile.nickname,
avatar = profile.avatar,
photo = profile.photo,
group = profile.group,
status = profile.status,
uq = textTransformer.transformRankToFormattedText(profile.uq),
signature = textTransformer.transformHtmlToSpanned(profile.signature),
rewards = textTransformer.transformHtmlToSpanned(profile.rewards),
registerDate = profile.registerDate,
timeZone = profile.timeZone,
website = textTransformer.transformWebsiteToSpanned(profile.website),
birthDate = profile.birthDate,
location = profile.location,
interests = profile.interests,
sex = profile.sex,
messagesCount = profile.messagesCount,
messsagesPerDay = profile.messsagesPerDay,
bayans = profile.bayans,
todayTopics = profile.todayTopics,
email = profile.email,
icq = profile.icq
)
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/structuralsearch/search/KotlinSSConstantExpressionTest.kt | 4 | 633 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.structuralsearch.search
import org.jetbrains.kotlin.idea.structuralsearch.KotlinStructuralSearchTest
class KotlinSSConstantExpressionTest : KotlinStructuralSearchTest() {
override fun getBasePath(): String = "constantExpression"
fun testNull() { doTest("null") }
fun testBoolean() { doTest("true") }
fun testInteger() { doTest("1") }
fun testFloat() { doTest("1.0f") }
fun testCharacter() { doTest("'a'") }
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/code-insight/postfix-templates/testData/expansion/for/nestedList.after.kt | 3 | 81 | fun test(list: List<List<String>>) {
for (strings in list) {
}
} | apache-2.0 |
GunoH/intellij-community | platform/tips-of-the-day/src/com/intellij/ide/util/TipsFeedback.kt | 2 | 2707 | // 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.ide.util
import com.intellij.feedback.common.FeedbackRequestType
import com.intellij.feedback.common.submitGeneralFeedback
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.components.*
import com.intellij.openapi.util.registry.Registry
import com.intellij.util.xmlb.annotations.XMap
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
@Service
@State(name = "TipsFeedback", storages = [Storage(value = "tips-feedback.xml", roamingType = RoamingType.DISABLED)])
class TipsFeedback : SimplePersistentStateComponent<TipsFeedback.State>(State()) {
fun getLikenessState(tipId: String): Boolean? {
return state.tipToLikeness[tipId]
}
fun setLikenessState(tipId: String, likenessState: Boolean?) {
if (likenessState != null) {
state.tipToLikeness[tipId] = likenessState
state.intIncrementModificationCount()
}
else state.tipToLikeness.remove(tipId)?.also {
state.intIncrementModificationCount()
}
}
class State : BaseState() {
@get:XMap
val tipToLikeness by linkedMap<String, Boolean>()
}
fun scheduleFeedbackSending(tipId: String, likenessState: Boolean) {
val shortDescription = """
tipId: $tipId
like: $likenessState
""".trimIndent()
val dataJsonObject = buildJsonObject {
put("format_version", FEEDBACK_FORMAT_VERSION)
put("tip_id", tipId)
put("like", likenessState)
put("ide_name", ApplicationNamesInfo.getInstance().fullProductName)
put("ide_build", ApplicationInfo.getInstance().build.asStringWithoutProductCode())
}
submitGeneralFeedback(
project = null,
title = FEEDBACK_TITLE,
description = shortDescription,
feedbackType = FEEDBACK_TITLE,
collectedData = Json.encodeToString(dataJsonObject),
feedbackRequestType = getFeedbackRequestType(),
showNotification = false)
}
private fun getFeedbackRequestType(): FeedbackRequestType {
return when (Registry.stringValue("tips.of.the.day.feedback")) {
"production" -> FeedbackRequestType.PRODUCTION_REQUEST
"staging" -> FeedbackRequestType.TEST_REQUEST
else -> FeedbackRequestType.NO_REQUEST
}
}
companion object {
private const val FEEDBACK_TITLE = "Tips of the Day Feedback"
private const val FEEDBACK_FORMAT_VERSION = 1
@JvmStatic
fun getInstance(): TipsFeedback = service()
}
} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/preference/SettingsMutators.kt | 3 | 4613 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.test.preference
import com.intellij.debugger.settings.DebuggerSettings
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.compiler.configuration.Kotlin2JvmCompilerArgumentsHolder
import org.jetbrains.kotlin.idea.debugger.core.DebuggerUtils
import org.jetbrains.kotlin.idea.debugger.KotlinDebuggerSettings
import org.jetbrains.kotlin.idea.debugger.core.ToggleKotlinVariablesState
import org.jetbrains.kotlin.idea.debugger.evaluate.compilation.ReflectionCallClassPatcher
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.DISABLE_KOTLIN_INTERNAL_CLASSES
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.RENDER_DELEGATED_PROPERTIES
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.SKIP_CLASSLOADERS
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.SKIP_CONSTRUCTORS
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.SKIP_GETTERS
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.SKIP_SYNTHETIC_METHODS
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys.TRACING_FILTERS_ENABLED
import kotlin.reflect.KMutableProperty1
internal val SettingsMutators: List<SettingsMutator<*>> = listOf(
DebuggerSettingsMutator(SKIP_SYNTHETIC_METHODS, DebuggerSettings::SKIP_SYNTHETIC_METHODS),
DebuggerSettingsMutator(SKIP_CONSTRUCTORS, DebuggerSettings::SKIP_CONSTRUCTORS),
DebuggerSettingsMutator(SKIP_CLASSLOADERS, DebuggerSettings::SKIP_CLASSLOADERS),
DebuggerSettingsMutator(TRACING_FILTERS_ENABLED, DebuggerSettings::TRACING_FILTERS_ENABLED),
DebuggerSettingsMutator(SKIP_GETTERS, DebuggerSettings::SKIP_GETTERS),
KotlinSettingsMutator(DISABLE_KOTLIN_INTERNAL_CLASSES, KotlinDebuggerSettings::disableKotlinInternalClasses),
KotlinSettingsMutator(RENDER_DELEGATED_PROPERTIES, KotlinDebuggerSettings::renderDelegatedProperties),
KotlinVariablesModeSettingsMutator,
JvmTargetSettingsMutator,
ForceRankingSettingsMutator,
ReflectionPatchingMutator
)
private class DebuggerSettingsMutator<T : Any>(
key: DebuggerPreferenceKey<T>,
private val prop: KMutableProperty1<DebuggerSettings, T>
) : SettingsMutator<T>(key) {
override fun setValue(value: T, project: Project): T {
val debuggerSettings = DebuggerSettings.getInstance()
val oldValue = prop.get(debuggerSettings)
prop.set(debuggerSettings, value)
return oldValue
}
}
private class KotlinSettingsMutator<T : Any>(
key: DebuggerPreferenceKey<T>,
private val prop: KMutableProperty1<KotlinDebuggerSettings, T>
) : SettingsMutator<T>(key) {
override fun setValue(value: T, project: Project): T {
val debuggerSettings = KotlinDebuggerSettings.getInstance()
val oldValue = prop.get(debuggerSettings)
prop.set(debuggerSettings, value)
return oldValue
}
}
private object KotlinVariablesModeSettingsMutator : SettingsMutator<Boolean>(DebuggerPreferenceKeys.SHOW_KOTLIN_VARIABLES) {
override fun setValue(value: Boolean, project: Project): Boolean {
val service = ToggleKotlinVariablesState.getService()
val oldValue = service.kotlinVariableView
service.kotlinVariableView = value
return oldValue
}
}
private object JvmTargetSettingsMutator : SettingsMutator<String>(DebuggerPreferenceKeys.JVM_TARGET) {
override fun setValue(value: String, project: Project): String {
var oldValue: String? = null
Kotlin2JvmCompilerArgumentsHolder.getInstance(project).update {
oldValue = jvmTarget
jvmTarget = value.takeIf { it.isNotEmpty() }
}
return oldValue ?: ""
}
}
private object ForceRankingSettingsMutator : SettingsMutator<Boolean>(DebuggerPreferenceKeys.FORCE_RANKING) {
override fun setValue(value: Boolean, project: Project): Boolean {
val oldValue = DebuggerUtils.forceRanking
DebuggerUtils.forceRanking = value
return oldValue
}
}
private object ReflectionPatchingMutator : SettingsMutator<Boolean>(DebuggerPreferenceKeys.REFLECTION_PATCHING) {
override fun setValue(value: Boolean, project: Project): Boolean {
val oldValue = ReflectionCallClassPatcher.isEnabled
ReflectionCallClassPatcher.isEnabled = value
return oldValue
}
} | apache-2.0 |
siosio/intellij-community | platform/platform-api/src/com/intellij/openapi/ui/DialogPanel.kt | 1 | 3013 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.ui
import com.intellij.openapi.Disposable
import com.intellij.ui.components.JBPanel
import java.awt.LayoutManager
import java.util.function.Supplier
import javax.swing.JComponent
import javax.swing.text.JTextComponent
class DialogPanel : JBPanel<DialogPanel> {
var preferredFocusedComponent: JComponent? = null
var validateCallbacks: List<() -> ValidationInfo?> = emptyList()
var componentValidateCallbacks: Map<JComponent, () -> ValidationInfo?> = emptyMap()
var customValidationRequestors: Map<JComponent, List<(() -> Unit) -> Unit>> = emptyMap()
var applyCallbacks: Map<JComponent?, List<() -> Unit>> = emptyMap()
var resetCallbacks: Map<JComponent?, List<() -> Unit>> = emptyMap()
var isModifiedCallbacks: Map<JComponent?, List<() -> Boolean>> = emptyMap()
private val componentValidationStatus = hashMapOf<JComponent, ValidationInfo>()
constructor() : super()
constructor(layout: LayoutManager?) : super(layout)
fun registerValidators(parentDisposable: Disposable, componentValidityChangedCallback: ((Map<JComponent, ValidationInfo>) -> Unit)? = null) {
for ((component, callback) in componentValidateCallbacks) {
val validator = ComponentValidator(parentDisposable).withValidator(Supplier {
val infoForComponent = callback()
if (componentValidationStatus[component] != infoForComponent) {
if (infoForComponent != null) {
componentValidationStatus[component] = infoForComponent
}
else {
componentValidationStatus.remove(component)
}
componentValidityChangedCallback?.invoke(componentValidationStatus)
}
infoForComponent
})
if (component is JTextComponent) {
validator.andRegisterOnDocumentListener(component)
}
registerCustomValidationRequestors(component, validator)
validator.installOn(component)
}
}
fun apply() {
for ((component, callbacks) in applyCallbacks.entries) {
if (component == null) continue
val modifiedCallbacks = isModifiedCallbacks.get(component)
if (modifiedCallbacks.isNullOrEmpty() || modifiedCallbacks.any { it() }) {
callbacks.forEach { it() }
}
}
applyCallbacks.get(null)?.forEach { it() }
}
fun reset() {
for ((component, callbacks) in resetCallbacks.entries) {
if (component == null) continue
callbacks.forEach { it() }
}
resetCallbacks.get(null)?.forEach { it() }
}
fun isModified(): Boolean {
return isModifiedCallbacks.values.any { list -> list.any { it() } }
}
private fun registerCustomValidationRequestors(component: JComponent, validator: ComponentValidator) {
for (onCustomValidationRequest in customValidationRequestors.get(component) ?: return) {
onCustomValidationRequest { validator.revalidate() }
}
}
}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantWith/notApplicable_inValueArgument.kt | 4 | 128 | // PROBLEM: none
// WITH_RUNTIME
fun foo(i: Int) {}
fun test() {
foo(<caret>with("") {
println()
1
})
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/intentions/importMember/ObjectMethod.kt | 4 | 224 | // INTENTION_TEXT: "Add import for 'kotlin.properties.Delegates.notNull'"
// WITH_RUNTIME
import kotlin.properties.Delegates
class A {
val v1: Int by Delegates.notNull()
val v2: Char by Delegates.notNull<caret>()
} | apache-2.0 |
loxal/FreeEthereum | free-ethereum-core/src/test/java/org/ethereum/jsontestsuite/suite/builder/BlockHeaderBuilder.kt | 1 | 2560 | /*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* 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 org.ethereum.jsontestsuite.suite.builder
import org.ethereum.core.BlockHeader
import org.ethereum.jsontestsuite.suite.Utils
import org.ethereum.jsontestsuite.suite.model.BlockHeaderTck
import java.math.BigInteger
internal object BlockHeaderBuilder {
fun build(headerTck: BlockHeaderTck): BlockHeader {
val header = BlockHeader(
Utils.parseData(headerTck.parentHash),
Utils.parseData(headerTck.uncleHash),
Utils.parseData(headerTck.coinbase),
Utils.parseData(headerTck.bloom),
Utils.parseNumericData(headerTck.difficulty),
BigInteger(1, Utils.parseData(headerTck.number)).toLong(),
Utils.parseData(headerTck.gasLimit),
BigInteger(1, Utils.parseData(headerTck.gasUsed)).toLong(),
BigInteger(1, Utils.parseData(headerTck.timestamp)).toLong(),
Utils.parseData(headerTck.extraData),
Utils.parseData(headerTck.mixHash),
Utils.parseData(headerTck.nonce)
)
header.receiptsRoot = Utils.parseData(headerTck.receiptTrie)
header.setTransactionsRoot(Utils.parseData(headerTck.transactionsTrie))
header.stateRoot = Utils.parseData(headerTck.stateRoot)
return header
}
}
| mit |
vovagrechka/fucking-everything | attic/alraune/alraune-back-very-old/gen/generated--alraune-entities.kt | 1 | 11602 | /*
* (C) Copyright 2017 Vladimir Grechka
*
* YOU DON'T MESS AROUND WITH THIS SHIT, IT WAS GENERATED BY A TOOL SMARTER THAN YOU
*/
//
// Generated on Fri May 19 13:31:49 EEST 2017
// Model: e:/fegh/alraune/alraune-back/src/alraune-entities.kt
//
package alraune.back
import kotlin.reflect.KClass
import vgrechka.*
import vgrechka.spew.*
import kotlin.properties.Delegates.notNull
import kotlin.reflect.KMutableProperty1
// ------------------------------------------------------------------
// AlUser
// ------------------------------------------------------------------
// Generated at e-68337cd-2d2d-4aa0-bfcc-e6423096599d
fun newAlUser(
firstName: String,
email: String,
lastName: String,
passwordHash: String,
sessionID: String,
profilePhone: String,
adminNotes: String,
aboutMe: String,
profileRejectionReason: String?,
banReason: String?,
subscribedToAllCategories: Boolean
): AlUser {
return Generated_AlUser().also {
it.firstName = firstName
it.email = email
it.lastName = lastName
it.passwordHash = passwordHash
it.sessionID = sessionID
it.profilePhone = profilePhone
it.adminNotes = adminNotes
it.aboutMe = aboutMe
it.profileRejectionReason = profileRejectionReason
it.banReason = banReason
it.subscribedToAllCategories = subscribedToAllCategories
}
}
val alUserRepo: AlUserRepository by lazy {
object : AlUserRepository {
override fun select(prop: KMutableProperty1<AlUser, String>, op: DBPile.Operator, arg: Any?): List<AlUser> {
println("findBy(prop = ${prop.name}; op = ${op.toString()}; arg = $arg)")
val params = mutableListOf<Any?>()
val sql = buildString {
ln("select")
ln(" alUser_id,")
ln(" unix_timestamp(alUser_createdAt),")
ln(" unix_timestamp(alUser_updatedAt),")
ln(" alUser_deleted,")
ln(" alUser_firstName,")
ln(" alUser_email,")
ln(" alUser_lastName,")
ln(" alUser_passwordHash,")
ln(" alUser_sessionID,")
ln(" alUser_profilePhone,")
ln(" alUser_adminNotes,")
ln(" alUser_aboutMe,")
ln(" alUser_profileRejectionReason,")
ln(" alUser_banReason,")
ln(" alUser_subscribedToAllCategories")
ln("from `alraune_users`")
ln("where")
ln("${propertyToColumnName(prop)} ${op.sql} ?")
params.add(arg)
}
val rows = DBPile.query(sql, params, uuid = "7a25556d-0083-49a0-bd41-bdd4b42764ca")
println("findBy: Found ${rows.size} rows")
val items = mutableListOf<AlUser>()
for (row in rows) {
// run {
// val value = row[13]
// println("--- type = ${PHPPile.getType(value)}; value = $value")
// }
items += Generated_AlUser().also {
it.id = row[0] as String
it.createdAt = DBPile.mysqlValueToPHPTimestamp(row[1])
it.updatedAt = DBPile.mysqlValueToPHPTimestamp(row[2])
it.deleted = DBPile.mysqlValueToBoolean(row[3])
it.firstName = row[4] as String
it.email = row[5] as String
it.lastName = row[6] as String
it.passwordHash = row[7] as String
it.sessionID = row[8] as String
it.profilePhone = row[9] as String
it.adminNotes = row[10] as String
it.aboutMe = row[11] as String
it.profileRejectionReason = row[12] as String?
it.banReason = row[13] as String?
it.subscribedToAllCategories = DBPile.mysqlValueToBoolean(row[14])
}
}
return items
}
override fun insert(x: AlUser): AlUser {
DBPile.execute(
sql = buildString {
ln("insert into `alraune_users`(")
ln(" `alUser_createdAt`,")
ln(" `alUser_updatedAt`,")
ln(" `alUser_deleted`,")
ln(" `alUser_firstName`,")
ln(" `alUser_email`,")
ln(" `alUser_lastName`,")
ln(" `alUser_passwordHash`,")
ln(" `alUser_sessionID`,")
ln(" `alUser_profilePhone`,")
ln(" `alUser_adminNotes`,")
ln(" `alUser_aboutMe`,")
ln(" `alUser_profileRejectionReason`,")
ln(" `alUser_banReason`,")
ln(" `alUser_subscribedToAllCategories`")
ln(") values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
},
params = listOf(
phiEval("return gmdate('Y-m-d H:i:s', ${x.createdAt.time});") as String,
phiEval("return gmdate('Y-m-d H:i:s', ${x.updatedAt.time});") as String,
x.deleted,
x.firstName,
x.email,
x.lastName,
x.passwordHash,
x.sessionID,
x.profilePhone,
x.adminNotes,
x.aboutMe,
x.profileRejectionReason,
x.banReason,
x.subscribedToAllCategories
),
uuid = "5b5be5e7-5eb9-44e7-8618-c513fb577b0c"
)
val res = DBPile.query(
sql = "select cast(last_insert_id() as char)",
uuid = "1c969a58-f1d4-4410-923b-bea78697c069"
)
x.id = res.first().first() as String
return x
}
}
}
fun AlUserRepository.propertyToColumnName(prop: KMutableProperty1<AlUser, String>): String {
if (prop.name == AlUser::id.name) return "alUser_id"
if (prop.name == AlUser::createdAt.name) return "alUser_createdAt"
if (prop.name == AlUser::updatedAt.name) return "alUser_updatedAt"
if (prop.name == AlUser::deleted.name) return "alUser_deleted"
if (prop.name == AlUser::firstName.name) return "alUser_firstName"
if (prop.name == AlUser::email.name) return "alUser_email"
if (prop.name == AlUser::lastName.name) return "alUser_lastName"
if (prop.name == AlUser::passwordHash.name) return "alUser_passwordHash"
if (prop.name == AlUser::sessionID.name) return "alUser_sessionID"
if (prop.name == AlUser::profilePhone.name) return "alUser_profilePhone"
if (prop.name == AlUser::adminNotes.name) return "alUser_adminNotes"
if (prop.name == AlUser::aboutMe.name) return "alUser_aboutMe"
if (prop.name == AlUser::profileRejectionReason.name) return "alUser_profileRejectionReason"
if (prop.name == AlUser::banReason.name) return "alUser_banReason"
if (prop.name == AlUser::subscribedToAllCategories.name) return "alUser_subscribedToAllCategories"
throw Exception("03f6ab91-79cf-4633-a7d0-06dd05ab9dd2")
}
val AlUserRepository.dropTableDDL get() = buildString {
ln("drop table if exists `alraune_users`")
}
val AlUserRepository.createTableDDL get() = buildString {
ln("create table `alraune_users` (")
ln(" alUser_id bigint not null auto_increment primary key,")
ln(" alUser_createdAt datetime not null,")
ln(" alUser_updatedAt datetime not null,")
ln(" alUser_deleted boolean not null,")
ln(" alUser_firstName longtext not null,")
ln(" alUser_email longtext not null,")
ln(" alUser_lastName longtext not null,")
ln(" alUser_passwordHash longtext not null,")
ln(" alUser_sessionID longtext not null,")
ln(" alUser_profilePhone longtext not null,")
ln(" alUser_adminNotes longtext not null,")
ln(" alUser_aboutMe longtext not null,")
ln(" alUser_profileRejectionReason longtext,")
ln(" alUser_banReason longtext,")
ln(" alUser_subscribedToAllCategories boolean not null")
ln(") engine=InnoDB;")
}
class Generated_AlUser : AlUser {
override var id by notNull<String>()
override var createdAt: PHPTimestamp = DBPile.currentTimestampForEntity()
override var updatedAt= createdAt
override var deleted= false
override var firstName by notNull<String>()
override var email by notNull<String>()
override var lastName by notNull<String>()
override var passwordHash by notNull<String>()
override var sessionID by notNull<String>()
override var profilePhone by notNull<String>()
override var adminNotes by notNull<String>()
override var aboutMe by notNull<String>()
override var profileRejectionReason: String? = null
override var banReason: String? = null
override var subscribedToAllCategories by notNull<Boolean>()
override fun toString(): String {
return buildString {
append("AlUser(")
append("id=$id, ")
append("createdAt=${phiEval("return gmdate('Y-m-d H:i:s', ${createdAt.time});") as String}, ")
append("updatedAt=${phiEval("return gmdate('Y-m-d H:i:s', ${createdAt.time});") as String}, ")
append("deleted=$deleted, ")
append("firstName=$firstName, ")
append("email=$email, ")
append("lastName=$lastName, ")
append("sessionID=$sessionID, ")
append("profilePhone=$profilePhone, ")
append("adminNotes=$adminNotes, ")
append("aboutMe=$aboutMe, ")
append("profileRejectionReason=$profileRejectionReason, ")
append("banReason=$banReason, ")
append("subscribedToAllCategories=$subscribedToAllCategories")
append(")")
}
}
}
object AlGeneratedDBPile {
object ddl {
val dropCreateAllScript = """
drop table if exists `alraune_users`;
create table `alraune_users` (
alUser_id bigint not null auto_increment primary key,
alUser_createdAt datetime not null,
alUser_updatedAt datetime not null,
alUser_deleted boolean not null,
alUser_firstName longtext not null,
alUser_email longtext not null,
alUser_lastName longtext not null,
alUser_passwordHash longtext not null,
alUser_sessionID longtext not null,
alUser_profilePhone longtext not null,
alUser_adminNotes longtext not null,
alUser_aboutMe longtext not null,
alUser_profileRejectionReason longtext,
alUser_banReason longtext,
alUser_subscribedToAllCategories boolean not null
) engine=InnoDB;
"""
}
}
/*
DDL
===
drop table if exists `alraune_users`;
create table `alraune_users` (
alUser_id bigint not null auto_increment primary key,
alUser_createdAt datetime not null,
alUser_updatedAt datetime not null,
alUser_deleted boolean not null,
alUser_firstName longtext not null,
alUser_email longtext not null,
alUser_lastName longtext not null,
alUser_passwordHash longtext not null,
alUser_sessionID longtext not null,
alUser_profilePhone longtext not null,
alUser_adminNotes longtext not null,
alUser_aboutMe longtext not null,
alUser_profileRejectionReason longtext,
alUser_banReason longtext,
alUser_subscribedToAllCategories boolean not null
) engine=InnoDB;
*/ | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveNameFromFunctionExpressionFix.kt | 3 | 2274 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.CleanupFix
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.util.createIntentionForFirstParentOfType
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.resolve.BindingContext
class RemoveNameFromFunctionExpressionFix(element: KtNamedFunction) : KotlinQuickFixAction<KtNamedFunction>(element), CleanupFix {
override fun getText(): String = KotlinBundle.message("remove.identifier.from.anonymous.function")
override fun getFamilyName(): String = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
removeNameFromFunction(element ?: return)
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic) =
diagnostic.createIntentionForFirstParentOfType(::RemoveNameFromFunctionExpressionFix)
private fun removeNameFromFunction(function: KtNamedFunction) {
var wereAutoLabelUsages = false
val name = function.nameAsName ?: return
function.forEachDescendantOfType<KtReturnExpression> {
if (!wereAutoLabelUsages && it.getLabelNameAsName() == name) {
wereAutoLabelUsages = it.analyze().get(BindingContext.LABEL_TARGET, it.getTargetLabel()) == function
}
}
function.nameIdentifier?.delete()
if (wereAutoLabelUsages) {
val psiFactory = KtPsiFactory(function)
val newFunction = psiFactory.createExpressionByPattern("$0@ $1", name, function)
function.replace(newFunction)
}
}
}
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/frame/remapThis.kt | 13 | 262 | package remapThis
fun main() {
Bar().bar()
}
class Bar {
fun bar() {
"a".foo()
}
fun String.foo() {
//Breakpoint!
val a = this
}
}
// PRINT_FRAME
// SHOW_KOTLIN_VARIABLES
// DESCRIPTOR_VIEW_OPTIONS: NAME_EXPRESSION | apache-2.0 |
GunoH/intellij-community | plugins/evaluation-plugin/src/com/intellij/cce/evaluation/step/HeadlessFinishEvaluationStep.kt | 7 | 543 | package com.intellij.cce.evaluation.step
import com.intellij.cce.workspace.EvaluationWorkspace
import kotlin.system.exitProcess
class HeadlessFinishEvaluationStep : FinishEvaluationStep() {
override fun start(workspace: EvaluationWorkspace): EvaluationWorkspace? {
print("Evaluation completed. ")
if (workspace.getReports().isEmpty()) {
println(" Workspace: ${workspace.path()}")
} else {
println("Reports:")
workspace.getReports().forEach { println("${it.key}: ${it.value}") }
}
exitProcess(0)
}
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/base/fir/analysis-api-providers/testData/annotationsResolver/same_package_short_name.kt | 8 | 173 | package foo.bar.baz
annotation class Ann1
annotation class Ann2
annotation class Ann3
@Ann1
@Ann2
fun test<caret>() {}
// ANNOTATION: foo/bar/baz/Ann1, foo/bar/baz/Ann2 | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/structuralsearch/search/KotlinSSIsExpressionTest.kt | 5 | 516 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.structuralsearch.search
import org.jetbrains.kotlin.idea.structuralsearch.KotlinSSResourceInspectionTest
class KotlinSSIsExpressionTest : KotlinSSResourceInspectionTest() {
override fun getBasePath(): String = "isExpression"
fun testIs() { doTest("'_ is '_") }
fun testNegatedIs() { doTest("'_ !is '_") }
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceToStringWithStringTemplateInspection.kt | 3 | 1724 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.canDropBraces
import org.jetbrains.kotlin.idea.core.dropBraces
import org.jetbrains.kotlin.idea.intentions.isToString
import org.jetbrains.kotlin.psi.*
class ReplaceToStringWithStringTemplateInspection : AbstractApplicabilityBasedInspection<KtDotQualifiedExpression>(
KtDotQualifiedExpression::class.java
) {
override fun isApplicable(element: KtDotQualifiedExpression): Boolean {
if (element.receiverExpression !is KtReferenceExpression) return false
if (element.parent is KtBlockStringTemplateEntry) return false
return element.isToString()
}
override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) {
val variable = element.receiverExpression.text
val replaced = element.replace(KtPsiFactory(element).createExpression("\"\${$variable}\""))
val blockStringTemplateEntry = (replaced as? KtStringTemplateExpression)?.entries?.firstOrNull() as? KtBlockStringTemplateEntry
if (blockStringTemplateEntry?.canDropBraces() == true) blockStringTemplateEntry.dropBraces()
}
override fun inspectionText(element: KtDotQualifiedExpression) =
KotlinBundle.message("inspection.replace.to.string.with.string.template.display.name")
override val defaultFixText get() = KotlinBundle.message("replace.tostring.with.string.template")
} | apache-2.0 |
smmribeiro/intellij-community | plugins/eclipse/src/org/jetbrains/idea/eclipse/config/EmlFileLoader.kt | 3 | 9682 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.eclipse.config
import com.intellij.openapi.components.ExpandMacroToPathMap
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.workspaceModel.ide.toPath
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder
import com.intellij.workspaceModel.storage.bridgeEntities.*
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jdom.Element
import org.jetbrains.idea.eclipse.IdeaXml
import org.jetbrains.idea.eclipse.conversion.EPathUtil
import org.jetbrains.idea.eclipse.conversion.IdeaSpecificSettings
import org.jetbrains.jps.model.serialization.java.JpsJavaModelSerializerExtension
import org.jetbrains.jps.model.serialization.module.JpsModuleRootModelSerializer
import org.jetbrains.jps.util.JpsPathUtil
/**
* Loads additional module configuration from *.eml file to [ModuleEntity]
*/
internal class EmlFileLoader(
private val module: ModuleEntity, private val builder: WorkspaceEntityStorageBuilder,
private val expandMacroToPathMap: ExpandMacroToPathMap,
private val virtualFileManager: VirtualFileUrlManager
) {
fun loadEml(emlTag: Element, contentRoot: ContentRootEntity) {
loadCustomJavaSettings(emlTag)
loadContentEntries(emlTag, contentRoot)
loadJdkSettings(emlTag)
loadDependencies(emlTag)
}
private fun loadDependencies(emlTag: Element) {
val moduleLibraries = module.dependencies.asSequence().filterIsInstance<ModuleDependencyItem.Exportable.LibraryDependency>()
.mapNotNull { it.library.resolve(builder) }
.filter { it.tableId is LibraryTableId.ModuleLibraryTableId }
.associateBy { it.name }
val libraryScopes = HashMap<String, ModuleDependencyItem.DependencyScope>()
emlTag.getChildren("lib").forEach { libTag ->
val name = libTag.getAttributeValue("name")!!
libraryScopes[name] = libTag.getScope()
val moduleLibrary = moduleLibraries[name]
if (moduleLibrary != null) {
loadModuleLibrary(libTag, moduleLibrary)
}
}
val moduleScopes = emlTag.getChildren("module").associateBy(
{ it.getAttributeValue("name") },
{ it.getScope() }
)
builder.modifyEntity(ModifiableModuleEntity::class.java, module) {
dependencies = dependencies.map { dep ->
when (dep) {
is ModuleDependencyItem.Exportable.LibraryDependency ->
libraryScopes[dep.library.name]?.let { dep.copy(scope = it) } ?: dep
is ModuleDependencyItem.Exportable.ModuleDependency ->
moduleScopes[dep.module.name]?.let { dep.copy(scope = it) } ?: dep
else -> dep
}
}
}
}
private fun Element.getScope(): ModuleDependencyItem.DependencyScope {
return getAttributeValue("scope")?.let {
try {
ModuleDependencyItem.DependencyScope.valueOf(it)
}
catch (e: IllegalArgumentException) {
null
}
} ?: ModuleDependencyItem.DependencyScope.COMPILE
}
private fun loadModuleLibrary(libTag: Element, library: LibraryEntity) {
val eclipseSrcRoot = library.roots.firstOrNull { it.type.name == OrderRootType.SOURCES.name() }
val rootsToRemove = HashSet<LibraryRoot>()
val rootsToAdd = ArrayList<LibraryRoot>()
libTag.getChildren(IdeaSpecificSettings.SRCROOT_ATTR).forEach { rootTag ->
val url = rootTag.getAttributeValue("url")
val bindAttribute = rootTag.getAttributeValue(IdeaSpecificSettings.SRCROOT_BIND_ATTR)
if (bindAttribute != null && !bindAttribute.toBoolean()) {
rootsToAdd.add(LibraryRoot(virtualFileManager.fromUrl(url!!), LibraryRootTypeId.SOURCES))
}
else if (eclipseSrcRoot != null && url != eclipseSrcRoot.url.url && EPathUtil.areUrlsPointTheSame(url, eclipseSrcRoot.url.url)) {
rootsToAdd.add(LibraryRoot(virtualFileManager.fromUrl(url!!), LibraryRootTypeId.SOURCES))
rootsToRemove.add(eclipseSrcRoot)
}
}
libTag.getChildren(IdeaSpecificSettings.JAVADOCROOT_ATTR).mapTo(rootsToAdd) {
LibraryRoot(virtualFileManager.fromUrl(it.getAttributeValue("url")!!), EclipseModuleRootsSerializer.JAVADOC_TYPE)
}
fun updateRoots(tagName: String, rootType: String) {
libTag.getChildren(tagName).forEach { rootTag ->
val root = expandMacroToPathMap.substitute(rootTag.getAttributeValue(IdeaSpecificSettings.PROJECT_RELATED)!!, SystemInfo.isFileSystemCaseSensitive)
library.roots.forEach { libRoot ->
if (libRoot !in rootsToRemove && libRoot.type.name == rootType && EPathUtil.areUrlsPointTheSame(root, libRoot.url.url)) {
rootsToRemove.add(libRoot)
rootsToAdd.add(LibraryRoot(virtualFileManager.fromUrl(root), LibraryRootTypeId(rootType)))
}
}
}
}
updateRoots(IdeaSpecificSettings.RELATIVE_MODULE_SRC, OrderRootType.SOURCES.name())
updateRoots(IdeaSpecificSettings.RELATIVE_MODULE_CLS, OrderRootType.CLASSES.name())
updateRoots(IdeaSpecificSettings.RELATIVE_MODULE_JAVADOC, "JAVADOC")
if (rootsToAdd.isNotEmpty() || rootsToRemove.isNotEmpty()) {
builder.modifyEntity(ModifiableLibraryEntity::class.java, library) {
roots = roots - rootsToRemove + rootsToAdd
}
}
}
private fun loadJdkSettings(emlTag: Element) {
val sdkItem = if (emlTag.getAttributeValue(IdeaSpecificSettings.INHERIT_JDK).toBoolean()) {
ModuleDependencyItem.InheritedSdkDependency
}
else {
emlTag.getAttributeValue("jdk")
?.let { ModuleDependencyItem.SdkDependency(it, "JavaSDK") }
}
if (sdkItem != null) {
builder.modifyEntity(ModifiableModuleEntity::class.java, module) {
val newDependencies = dependencies.map {
when (it) {
is ModuleDependencyItem.SdkDependency -> sdkItem
ModuleDependencyItem.InheritedSdkDependency -> sdkItem
else -> it
}
}
dependencies = if (newDependencies.size < dependencies.size) listOf(ModuleDependencyItem.InheritedSdkDependency) + newDependencies
else newDependencies
}
}
}
private fun loadCustomJavaSettings(emlTag: Element) {
val javaSettings = module.javaSettings ?: builder.addJavaModuleSettingsEntity(true, true, null, null, null, module, module.entitySource)
builder.modifyEntity(ModifiableJavaModuleSettingsEntity::class.java, javaSettings) {
val testOutputElement = emlTag.getChild(IdeaXml.OUTPUT_TEST_TAG)
if (testOutputElement != null) {
compilerOutputForTests = testOutputElement.getAttributeValue(IdeaXml.URL_ATTR)?.let { virtualFileManager.fromUrl(it) }
}
val inheritedOutput = emlTag.getAttributeValue(JpsJavaModelSerializerExtension.INHERIT_COMPILER_OUTPUT_ATTRIBUTE)
if (inheritedOutput.toBoolean()) {
inheritedCompilerOutput = true
}
excludeOutput = emlTag.getChild(IdeaXml.EXCLUDE_OUTPUT_TAG) != null
languageLevelId = emlTag.getAttributeValue("LANGUAGE_LEVEL")
}
}
private fun loadContentEntries(emlTag: Element, contentRoot: ContentRootEntity) {
val entriesElements = emlTag.getChildren(IdeaXml.CONTENT_ENTRY_TAG)
if (entriesElements.isNotEmpty()) {
entriesElements.forEach {
val url = virtualFileManager.fromUrl(it.getAttributeValue(IdeaXml.URL_ATTR)!!)
val contentRootEntity = contentRoot.module.contentRoots.firstOrNull { it.url == url }
?: builder.addContentRootEntity(url, emptyList(), emptyList(), module)
loadContentEntry(it, contentRootEntity)
}
}
else {
loadContentEntry(emlTag, contentRoot)
}
}
private fun loadContentEntry(contentEntryTag: Element, entity: ContentRootEntity) {
val testSourceFolders = contentEntryTag.getChildren(IdeaXml.TEST_FOLDER_TAG).mapTo(HashSet()) {
it.getAttributeValue(IdeaXml.URL_ATTR)
}
val packagePrefixes = contentEntryTag.getChildren(IdeaXml.PACKAGE_PREFIX_TAG).associateBy(
{ it.getAttributeValue(IdeaXml.URL_ATTR)!! },
{ it.getAttributeValue(IdeaXml.PACKAGE_PREFIX_VALUE_ATTR)!! }
)
for (sourceRoot in entity.sourceRoots) {
val url = sourceRoot.url.url
val isForTests = url in testSourceFolders
val rootType = if (isForTests) JpsModuleRootModelSerializer.JAVA_TEST_ROOT_TYPE_ID else JpsModuleRootModelSerializer.JAVA_SOURCE_ROOT_TYPE_ID
if (rootType != sourceRoot.rootType) {
builder.modifyEntity(ModifiableSourceRootEntity::class.java, sourceRoot) {
this.rootType = rootType
}
}
val packagePrefix = packagePrefixes[url]
if (packagePrefix != null) {
val javaRootProperties = sourceRoot.asJavaSourceRoot()
if (javaRootProperties != null) {
builder.modifyEntity(ModifiableJavaSourceRootEntity::class.java, javaRootProperties) {
this.packagePrefix = packagePrefix
}
}
else {
builder.addJavaSourceRootEntity(sourceRoot, false, packagePrefix)
}
}
}
val excludedUrls = contentEntryTag.getChildren(IdeaXml.EXCLUDE_FOLDER_TAG)
.mapNotNull { it.getAttributeValue(IdeaXml.URL_ATTR) }
.filter { FileUtil.isAncestor(entity.url.toPath().toFile(), JpsPathUtil.urlToFile(it), false) }
.map { virtualFileManager.fromUrl(it) }
if (excludedUrls.isNotEmpty()) {
builder.modifyEntity(ModifiableContentRootEntity::class.java, entity) {
this.excludedUrls = this.excludedUrls + excludedUrls
}
}
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/DebuggerFieldCompletionInformationProvider.kt | 6 | 609 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.evaluate
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.completion.CompletionInformationProvider
class DebuggerFieldCompletionInformationProvider : CompletionInformationProvider {
override fun getContainerAndReceiverInformation(descriptor: DeclarationDescriptor) =
(descriptor as? DebuggerFieldPropertyDescriptor)?.description?.let { " $it" }
} | apache-2.0 |
smmribeiro/intellij-community | plugins/eclipse/testSources/org/jetbrains/idea/eclipse/EclipseEml2ModulesTest.kt | 4 | 1405 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.eclipse
import com.intellij.testFramework.ApplicationExtension
import com.intellij.testFramework.rules.TempDirectoryExtension
import com.intellij.testFramework.rules.TestNameExtension
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.RegisterExtension
class EclipseEml2ModulesTest {
@JvmField
@RegisterExtension
val tempDirectory = TempDirectoryExtension()
@JvmField
@RegisterExtension
val testName = TestNameExtension()
@Test
fun testSourceRootPaths() {
doTest("ws-internals")
}
@Test
fun testAnotherSourceRootPaths() {
doTest("anotherPath")
}
private fun doTest(secondRootName: String) {
val testName = testName.methodName.removePrefix("test").decapitalize()
val testRoot = eclipseTestDataRoot.resolve("eml").resolve(testName)
val commonRoot = eclipseTestDataRoot.resolve("common").resolve("twoModulesWithClasspathStorage")
checkEmlFileGeneration(listOf(testRoot, commonRoot), tempDirectory, listOf(
"test" to "srcPath/sourceRootPaths/sourceRootPaths",
"ws-internals" to "srcPath/$secondRootName/ws-internals"
))
}
companion object {
@JvmField
@RegisterExtension
val appRule = ApplicationExtension()
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/intentions/convertToScope/convertToWith/parameterExpression.kt | 9 | 209 | // AFTER-WARNING: Variable 'result' is never used
// WITH_STDLIB
class X {
fun one() {}
fun two() = ""
}
fun test(x : X) {
x.one()
val result = process(<caret>x.two())
}
fun process(x: Any) = x | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/intentions/toRawStringLiteral/simple.kt | 26 | 39 | val v = <caret>"\"\\Hello,\nworld!\\\"" | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/completion/tests/testData/smart/inElvisOperator/6.kt | 13 | 419 | interface A
interface B : A
interface C
fun foo(a: A){}
fun foo(c: C){}
fun B?.bar(a: A, b: B, c: C, a1: A?, b1: B?, c1: C?) {
foo(this ?: <caret>
}
// EXIST: { itemText:"a" }
// EXIST: { itemText:"b" }
// ABSENT: { itemText:"c" }
// ABSENT: { itemText:"a1" }
// ABSENT: { itemText:"b1" }
// ABSENT: { itemText:"c1" }
// EXIST: { itemText:"!! a1" }
// EXIST: { itemText:"!! b1" }
// ABSENT: { itemText:"!! c1" }
| apache-2.0 |
trubitsyn/VisibleForTesting | src/test/resources/AnnotateKtClassOrObjectMethodsIntention/android/before.template.kt | 1 | 236 | import android.support.annotation.VisibleForTesting
class F<caret>oo {
@VisibleForTesting
private fun annotatedFoo() {}
fun publicFoo() {}
protected fun foo() {}
internal fun bar() {}
private fun baz() {}
} | apache-2.0 |
DuckDeck/AndroidDemo | app/src/main/java/stan/androiddemo/project/petal/Module/Main/PetalActivity.kt | 1 | 10365 | package stan.androiddemo.project.petal.Module.Main
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Color
import android.os.Bundle
import android.support.v4.app.FragmentManager
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.TextView
import com.facebook.drawee.view.SimpleDraweeView
import com.jakewharton.rxbinding.view.RxView
import kotlinx.android.synthetic.main.activity_petal.*
import stan.androiddemo.R
import stan.androiddemo.project.petal.Base.BasePetalActivity
import stan.androiddemo.project.petal.Config.Config
import stan.androiddemo.project.petal.Event.OnPinsFragmentInteractionListener
import stan.androiddemo.project.petal.Model.PinsMainInfo
import stan.androiddemo.project.petal.Module.Follow.PetalFollowActivity
import stan.androiddemo.project.petal.Module.ImageDetail.PetalImageDetailActivity
import stan.androiddemo.project.petal.Module.Login.PetalLoginActivity
import stan.androiddemo.project.petal.Module.PetalList.PetalListFragment
import stan.androiddemo.project.petal.Module.Search.SearchPetalActivity
import stan.androiddemo.project.petal.Module.Setting.PetalSettingActivity
import stan.androiddemo.project.petal.Module.UserInfo.PetalUserInfoActivity
import stan.androiddemo.tool.CompatUtils
import stan.androiddemo.tool.ImageLoad.ImageLoadBuilder
import stan.androiddemo.tool.Logger
import stan.androiddemo.tool.SPUtils
import java.util.concurrent.TimeUnit
class PetalActivity : BasePetalActivity(),OnPinsFragmentInteractionListener, SharedPreferences.OnSharedPreferenceChangeListener {
lateinit var fragmentManage: FragmentManager
lateinit var types:Array<String>
lateinit var titles:Array<String>
private var mUserName = ""
private var mUserId = ""
lateinit var fragment:PetalListFragment
lateinit var imgNavHead:SimpleDraweeView
lateinit var txtNavUsername:TextView
lateinit var txtNavUserEmail:TextView
override fun getTag(): String {return this.toString()}
override fun getLayoutId(): Int {
return R.layout.activity_petal
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setSupportActionBar(toolbar)
fragmentManage = supportFragmentManager
getData()
getSharedPreferences("share_data", Context.MODE_PRIVATE).registerOnSharedPreferenceChangeListener(this)
initDrawer(toolbar)
initNavHeadView()
initNavMenuView()
selectFragment(0)
}
override fun onResume() {
super.onResume()
setNavUserInfo()
}
//取出各种需要用的全局变量
fun getData(){
types = resources.getStringArray(R.array.type_array)
titles = resources.getStringArray(R.array.title_array)
isLogin = SPUtils.get(mContext,Config.ISLOGIN,false) as Boolean
if (isLogin){
mUserName = SPUtils.get(mContext,Config.USERNAME,mUserName) as String
mUserId = SPUtils.get(mContext,Config.USERID,mUserId) as String
}
}
//初始化DrawLayout
fun initDrawer(tb: android.support.v7.widget.Toolbar){
val toggle = ActionBarDrawerToggle(this,drawer_layout_petal,tb,
R.string.navigation_drawer_open,R.string.navigation_drawer_close)
drawer_layout_petal.addDrawerListener(toggle)
toggle.syncState()
navigation_view_petal.setNavigationItemSelectedListener {
if (it.groupId == R.id.menu_group_type){
fragment.mKey = types[it.itemId]
fragment.setRefresh()
title = titles[it.itemId]
}
else{
when(it.itemId){
R.id.nav_petal_setting->{
PetalSettingActivity.launch(this@PetalActivity)
}
R.id.nav_petal_quit->{
SPUtils.clear(mContext)
finish()
}
}
}
drawer_layout_petal.closeDrawer(GravityCompat.START)
return@setNavigationItemSelectedListener true
}
}
//初始化HeadNav
fun initNavHeadView(){
val headView = navigation_view_petal.inflateHeaderView(R.layout.petal_nav_header)
imgNavHead = headView.findViewById(R.id.img_petal_my_header)
imgNavHead.setOnClickListener {
if (isLogin){
PetalUserInfoActivity.launch(this@PetalActivity,mUserId,mUserName)
}
else{
PetalLoginActivity.launch(this@PetalActivity)
}
}
txtNavUsername = headView.findViewById(R.id.txt_nav_username)
txtNavUsername.setOnClickListener {
Logger.e("click txtNavUsername")
}
txtNavUserEmail = headView.findViewById(R.id.txt_nav_email)
val btnAttention = headView.findViewById<Button>(R.id.btn_nav_attention)
btnAttention.setCompoundDrawablesRelativeWithIntrinsicBounds(null,
CompatUtils.getTintDrawable(mContext,R.drawable.ic_loyalty_black_24dp
,resources.getColor(R.color.tint_list_pink)),null,null)
btnAttention.setOnClickListener {
if (!isLogin){
PetalLoginActivity.launch(this@PetalActivity)
}
else{
PetalFollowActivity.launch(this@PetalActivity)
}
}
val btnGather = headView.findViewById<Button>(R.id.btn_nav_gather)
btnGather.setCompoundDrawablesRelativeWithIntrinsicBounds(null,
CompatUtils.getTintDrawable(mContext,R.drawable.ic_camera_black_24dp
,resources.getColor(R.color.tint_list_pink)),null,null)
val btnMessage = headView.findViewById<Button>(R.id.btn_nav_message)
btnMessage.setCompoundDrawablesRelativeWithIntrinsicBounds(null,
CompatUtils.getTintDrawable(mContext,R.drawable.ic_message_black_24dp
,resources.getColor(R.color.tint_list_pink)),null,null)
val btnFriend = headView.findViewById<Button>(R.id.btn_nav_friends)
btnFriend.setCompoundDrawablesRelativeWithIntrinsicBounds(null,
CompatUtils.getTintDrawable(mContext,R.drawable.ic_people_black_24dp
,resources.getColor(R.color.tint_list_pink)),null,null)
}
fun setNavUserInfo(){
val drawable = CompatUtils.getTintDrawable(mContext,R.drawable.ic_account_circle_gray_48dp,Color.GRAY)
if (isLogin){
var key = SPUtils.get(mContext,Config.USERHEADKEY,"") as String
if (!key.isNullOrEmpty()){
key = resources.getString(R.string.urlImageRoot) + key
ImageLoadBuilder.Start(mContext,imgNavHead,key).setPlaceHolderImage(drawable).setIsCircle(true,true).build()
}
else{
Logger.d("User Head Key is empty")
}
if (!mUserName.isNullOrEmpty()){
txtNavUsername.text = mUserName
}
val email = SPUtils.get(mContext,Config.USEREMAIL,"") as String
if (!email.isNullOrEmpty()){
txtNavUserEmail.text = email
}
}
else{
ImageLoadBuilder.Start(mContext,imgNavHead,"").setPlaceHolderImage(drawable).setIsCircle(true,true).build()
}
}
//初始化NavMenu
fun initNavMenuView(){
val menu = navigation_view_petal.menu
val titleList = resources.getStringArray(R.array.title_array)
val icons = arrayListOf(R.drawable.ic_toys_black_24dp,R.drawable.ic_camera_black_24dp,R.drawable.ic_camera_alt_black_24dp,R.drawable.ic_local_dining_black_24dp,R.drawable.ic_loyalty_black_24dp)
for(i in 0 until titleList.size){
menu.add(R.id.menu_group_type,i, Menu.NONE,titleList[i]).setIcon(icons[i]).setCheckable(true)
}
menu.getItem(0).isChecked = true
}
fun selectFragment(position:Int){
val transaction = fragmentManage.beginTransaction()
val type = types[position]
val tt = titles[position]
fragment = PetalListFragment.createListFragment(type,tt)
transaction.replace(R.id.frame_layout_petal_with_refresh,fragment)
transaction.commit()
title = tt
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.petal_search_result,menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
//do something
return super.onOptionsItemSelected(item)
}
override fun initResAndListener() {
float_button_search.setImageResource(R.drawable.ic_search_black_24dp)
RxView.clicks(float_button_search).throttleFirst(Config.throttDuration.toLong(),TimeUnit.MILLISECONDS)
.subscribe({
SearchPetalActivity.launch(this@PetalActivity)
})
}
override fun onBackPressed() {
if (drawer_layout_petal.isDrawerOpen(GravityCompat.START)){
drawer_layout_petal.closeDrawers()
}
else{
super.onBackPressed()
}
}
override fun onSharedPreferenceChanged(p0: SharedPreferences, p1: String) {
if (Config.ISLOGIN == p1){
isLogin = p0.getBoolean(Config.ISLOGIN, false)
}
}
override fun onClickPinsItemImage(bean: PinsMainInfo, view: View) {
PetalImageDetailActivity.launch(this@PetalActivity,PetalImageDetailActivity.ACTION_MAIN)
}
override fun onClickPinsItemText(bean: PinsMainInfo, view: View) {
PetalImageDetailActivity.launch(this@PetalActivity,PetalImageDetailActivity.ACTION_MAIN)
}
companion object {
fun launch(activity:Activity){
val intent = Intent(activity,PetalActivity::class.java)
activity.startActivity(intent)
}
fun launch(activity:Activity,flag:Int){
val intent = Intent(activity,PetalActivity::class.java)
intent.flags = flag
activity.startActivity(intent)
}
}
}
| mit |
DuckDeck/AndroidDemo | app/src/main/java/stan/androiddemo/project/Game2048/InputListener.kt | 1 | 7557 | package stan.androiddemo.project.Game2048
import android.annotation.SuppressLint
import android.view.MotionEvent
import android.view.View
import java.util.*
/**
* Created by hugfo on 2017/8/19.
*/
class InputListener(view: MainView) : View.OnTouchListener{
private val SWIPE_MIN_DISTANCE = 0
private val SWIPE_THRESHOLD_VELOCITY = 25
private val MOVE_THRESHOLD = 250
private val RESET_STARTING = 10
private var timer: Timer? = null
private var x: Float = 0F
private var y: Float = 0F
private var lastdx: Float = 0F
private var lastdy: Float = 0F
private var previousX: Float = 0F
private var previousY: Float = 0F
private var startingX: Float = 0F
private var startingY: Float = 0F
private var previousDirection = 1
private var veryLastDirection = 1
private var hasMoved = false
private var isAutoRun = false
internal var mView: MainView = view
@SuppressLint("ClickableViewAccessibility")
override fun onTouch(v: View, event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
x = event.x
y = event.y
startingX = x
startingY = y
previousX = x
previousY = y
lastdx = 0f
lastdy = 0f
hasMoved = false
return true
}
MotionEvent.ACTION_MOVE -> {
x = event.x
y = event.y
if (isAutoRun){
//TODO("auto run")
return true
}
if (mView.game.isActive()) {
val dx = x - previousX
if (Math.abs(lastdx + dx) < Math.abs(lastdx) + Math.abs(dx)
&& Math.abs(dx) > RESET_STARTING
&& Math.abs(x - startingX) > SWIPE_MIN_DISTANCE) {
startingX = x
startingY = y
lastdx = dx
previousDirection = veryLastDirection
}
if (lastdx == 0f) {
lastdx = dx
}
val dy = y - previousY
if (Math.abs(lastdy + dy) < Math.abs(lastdy) + Math.abs(dy)
&& Math.abs(dy) > RESET_STARTING
&& Math.abs(y - startingY) > SWIPE_MIN_DISTANCE) {
startingX = x
startingY = y
lastdy = dy
previousDirection = veryLastDirection
}
if (lastdy == 0f) {
lastdy = dy
}
if (pathMoved() > SWIPE_MIN_DISTANCE * SWIPE_MIN_DISTANCE) {
var moved = false
if ((dy >= SWIPE_THRESHOLD_VELOCITY && previousDirection == 1 || y - startingY >= MOVE_THRESHOLD) && previousDirection % 2 != 0) {
moved = true
previousDirection *= 2
veryLastDirection = 2
mView.game.move(2)
} else if ((dy <= -SWIPE_THRESHOLD_VELOCITY && previousDirection == 1 || y - startingY <= -MOVE_THRESHOLD) && previousDirection % 3 != 0) {
moved = true
previousDirection *= 3
veryLastDirection = 3
mView.game.move(0)
} else if ((dx >= SWIPE_THRESHOLD_VELOCITY && previousDirection == 1 || x - startingX >= MOVE_THRESHOLD) && previousDirection % 5 != 0) {
moved = true
previousDirection *= 5
veryLastDirection = 5
mView.game.move(1)
} else if ((dx <= -SWIPE_THRESHOLD_VELOCITY && previousDirection == 1 || x - startingX <= -MOVE_THRESHOLD) && previousDirection % 7 != 0) {
moved = true
previousDirection *= 7
veryLastDirection = 7
mView.game.move(3)
}
if (moved) {
hasMoved = true
startingX = x
startingY = y
}
}
}
previousX = x
previousY = y
return true
}
MotionEvent.ACTION_UP -> {
x = event.x
y = event.y
previousDirection = 1
veryLastDirection = 1
// "Menu" inputs
if (!hasMoved) {
if (iconPressed(mView.sXNewGame, mView.sYIcons)) {
mView.game.newGame()
} else if (iconPressed(mView.sXUndo, mView.sYIcons)) {
mView.game.revertUndoState()
} else if (iconPressed(mView.sXCheat, mView.sYIcons)) {
mView.game.cheat()
} else if (iconPressed(mView.sXAuto, mView.sYIcons)) {
if (!mView.game.isActive()){
return true
}
isAutoRun = !isAutoRun
if (isAutoRun&&mView.game.isActive()){
if (timer == null){
timer = Timer()
setTimeTask()
}
}
else{
timer?.cancel()
timer = null
}
}
else if (isTap(2)
&& inRange(mView.startingX.toFloat(), x, mView.endingX.toFloat())
&& inRange(mView.startingY.toFloat(), x, mView.endingY.toFloat())
&& mView.continueButtonEnabled) {
mView.game.setEndlessMode()
}
}
}
}
return true
}
private fun setTimeTask(){
timer?.schedule(object:TimerTask(){
override fun run() {
if (!mView.game.isActive()){
timer?.cancel()
timer = null
isAutoRun = false
}
//TODO("start ai action")
val best = mView.game.ai?.getBest()
if (best != null){
mView.post {
mView.game.move(best!!.move!!)
}
}
}
},300,MOVE_THRESHOLD.toLong())
}
private fun pathMoved(): Float {
return (x - startingX) * (x - startingX) + (y - startingY) * (y - startingY)
}
private fun iconPressed(sx: Int, sy: Int): Boolean {
return isTap(1) && inRange(sx.toFloat(), x, sx + mView.iconSize.toFloat())
&& inRange(sy.toFloat(), y, sy + mView.iconSize.toFloat())
}
private fun inRange(starting: Float, check: Float, ending: Float): Boolean {
return check in starting..ending
}
private fun isTap(factor: Int): Boolean {
return pathMoved() <= mView.iconSize * factor
}
} | mit |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/data/domains/variables/VariableId.kt | 1 | 92 | package ch.rmy.android.http_shortcuts.data.domains.variables
typealias VariableId = String
| mit |
DuckDeck/AndroidDemo | app/src/main/java/stan/androiddemo/tool/Extension.kt | 1 | 2071 | package stan.androiddemo.tool
import android.graphics.Bitmap
import android.media.Image
import android.os.Environment
import android.widget.ImageView
import okhttp3.internal.Util
//import org.opencv.android.Utils
//import org.opencv.core.Mat
//import org.opencv.imgproc.Imgproc
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
/**
* Created by hugfo on 2017/8/5.
*/
fun Int.ToFixedInt(num:Int):String{
if (this.toString().length > num){
return this.toString()
}
else {
var str = this.toString()
while (str.length < num){
str = "0$str"
}
return str
}
}
fun String.ConvertUrl():String{
return this.replace(".","_").replace(":","=").replace("/","-")
}
fun Image.Save(name:String){
val buffer = this.planes[0].buffer
val data = ByteArray(buffer.remaining())
buffer.get(data)
val filePath = Environment.getExternalStorageDirectory().path + "/DCIM/Camera"
val photoPath = "$name.jpeg"
val file = File(filePath,photoPath)
try {
//存到本地相册
val fileOutputStream = FileOutputStream(file)
fileOutputStream.write(data)
fileOutputStream.close()
}
catch (e: FileNotFoundException){
e.printStackTrace()
}
catch (e: IOException){
e.printStackTrace()
}
finally {
this.close()
}
}
//fun ImageView.setMat(mat:Mat){
// val bitmat = Bitmap.createBitmap(mat.width(),mat.height(),Bitmap.Config.ARGB_8888)
// val matResult = Mat()
//// Imgproc.cvtColor(mat,matResult,Imgproc.COLOR_BGR2RGBA)
// Utils.matToBitmap(mat,bitmat)
// setImageBitmap(bitmat)
// matResult.release()
//}
fun ImageView.getBitmap():Bitmap{
this.isDrawingCacheEnabled = true
val bitmap = Bitmap.createBitmap(this.drawingCache)
this.isDrawingCacheEnabled = false
return bitmap
}
//fun ImageView.getMat():Mat{
// val bitmap = getBitmap()
// val mat = Mat()
// Utils.bitmapToMat(bitmap,mat)
// return mat
//}
| mit |
NilsRenaud/kotlin-presentation | examples/src/org/nilsr/kotlin/examples/6OperatorOverloading.kt | 1 | 1593 | package org.nilsr.kotlin.examples
/**
* Shows :
* - Operator Overloading
*/
fun main(args : Array<String>) {
val one = MyInt(1)
val two = MyInt(2)
println(one + two)
one()
two()
}
class MyInt(private val value : Int = 0){
operator fun plus(b : MyInt) = this.value + b.value
operator fun invoke() = println("What am I supposed to do ??")
// +a a.unaryPlus()
// -a a.unaryMinus()
// !a a.not()
// a++ a.inc()
// a-- a.dec()
// a + b a.plus(b)
// a - b a.minus(b)
// a * b a.times(b)
// a / b a.div(b)
// a % b a.rem(b), a.mod(b) (deprecated)
// a..b a.rangeTo(b)
// a in b b.contains(a)
// a !in b !b.contains(a)
// a[i] a.get(i)
// a[i, j] a.get(i, j)
// a[i_1, ..., i_n] a.get(i_1, ..., i_n)
// a[i] = b a.set(i, b)
// a[i, j] = b a.set(i, j, b)
// a[i_1, ..., i_n] = b a.set(i_1, ..., i_n, b)
// a() a.invoke()
// a(i) a.invoke(i)
// a(i, j) a.invoke(i, j)
// a(i_1, ..., i_n) a.invoke(i_1, ..., i_n)
// a += b a.plusAssign(b)
// a -= b a.minusAssign(b)
// a *= b a.timesAssign(b)
// a /= b a.divAssign(b)
// a %= b a.remAssign(b), a.modAssign(b) (deprecated)
// a == b a?.equals(b) ?: (b === null)
// a != b !(a?.equals(b) ?: (b === null))
// a > b a.compareTo(b) > 0
// a < b a.compareTo(b) < 0
// a >= b a.compareTo(b) >= 0
// a <= b a.compareTo(b) <= 0
} | mit |
sksamuel/ktest | kotest-assertions/kotest-assertions-shared/src/jvmMain/kotlin/io/kotest/assertions/async/timeout.kt | 1 | 951 | package io.kotest.assertions.async
import io.kotest.assertions.failure
import kotlinx.coroutines.TimeoutCancellationException
import kotlinx.coroutines.withTimeout
import java.util.concurrent.TimeUnit
import kotlin.time.Duration
suspend fun <A> shouldTimeout(duration: Duration, thunk: suspend () -> A) =
shouldTimeout(duration.inWholeMilliseconds, TimeUnit.MILLISECONDS, thunk)
suspend fun <A> shouldTimeout(duration: java.time.Duration, thunk: suspend () -> A) =
shouldTimeout(duration.toMillis(), TimeUnit.MILLISECONDS, thunk)
/**
* Verify that an asynchronous call should timeout
*/
suspend fun <A> shouldTimeout(timeout: Long, unit: TimeUnit, thunk: suspend () -> A) {
val timedOut = try {
withTimeout(unit.toMillis(timeout)) {
thunk()
false
}
} catch (t: TimeoutCancellationException) {
true
}
if (!timedOut) {
throw failure("Expected test to timeout for $timeout/$unit")
}
}
| mit |
ZoranPandovski/al-go-rithms | sort/insertion_sort/kotlin/insertionSort.kt | 2 | 501 | import java.util.Arrays
fun insertionSort(arr: Array<Long>) {
for (j in 1..arr.size - 1){
var i = j - 1;
val processedValue = arr[j];
while ( (i >= 0) && (arr[i] > processedValue) ){
arr[i + 1] = arr[i];
i--;
}
arr[i + 1] = processedValue;
}
}
fun main(args: Array<String>) {
val arr = arrayOf(1, 3, 5, 4, 2, 6, 8, 9, 7, 10, 13, 15, 17, 16, 14, 12, 19, 18, 11)
insertionSort(arr)
println(Arrays.toString(arr))
}
| cc0-1.0 |
softappeal/yass | kotlin/yass/main/ch/softappeal/yass/transport/MessageSerializer.kt | 1 | 1474 | package ch.softappeal.yass.transport
import ch.softappeal.yass.remote.*
import ch.softappeal.yass.serialize.*
internal const val Request = 0.toByte()
internal const val ValueReply = 1.toByte()
internal const val ExceptionReply = 2.toByte()
fun messageSerializer(contractSerializer: Serializer) = object : Serializer {
override fun read(reader: Reader): Message = when (val type = reader.readByte()) {
Request -> Request(
reader.readZigZagInt(),
reader.readZigZagInt(),
contractSerializer.read(reader) as List<Any?>
)
ValueReply -> ValueReply(
contractSerializer.read(reader)
)
ExceptionReply -> ExceptionReply(
contractSerializer.read(reader) as Exception
)
else -> error("unexpected type $type")
}
override fun write(writer: Writer, value: Any?) = when (value) {
is Request -> {
writer.writeByte(Request)
writer.writeZigZagInt(value.serviceId)
writer.writeZigZagInt(value.methodId)
contractSerializer.write(writer, value.arguments)
}
is ValueReply -> {
writer.writeByte(ValueReply)
contractSerializer.write(writer, value.value)
}
is ExceptionReply -> {
writer.writeByte(ExceptionReply)
contractSerializer.write(writer, value.exception)
}
else -> error("unexpected value '$value'")
}
}
| bsd-3-clause |
atlarge-research/opendc-simulator | opendc-model-odc/core/src/main/kotlin/com/atlarge/opendc/model/odc/topology/machine/ProcessingUnit.kt | 1 | 1756 | /*
* MIT License
*
* Copyright (c) 2017 atlarge-research
*
* 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.atlarge.opendc.model.odc.topology.machine
import com.atlarge.opendc.simulator.Entity
/**
* An interface representing a generic processing unit which is placed into a [Machine].
*
* @author Fabian Mastenbroek ([email protected])
*/
interface ProcessingUnit : Entity<Unit> {
/**
* The speed of this [ProcessingUnit] per core in MHz.
*/
val clockRate: Int
/**
* The amount of cores within this [ProcessingUnit].
*/
val cores: Int
/**
* The energy consumption of this [ProcessingUnit] in Watt.
*/
val energyConsumption: Double
}
| mit |
batagliao/onebible.android | app/src/main/java/com/claraboia/bibleandroid/activities/DispatchActivity.kt | 1 | 4423 | package com.claraboia.bibleandroid.activities
import android.app.Activity
import android.app.Dialog
import android.content.DialogInterface
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.util.Log
import android.widget.Toast
import com.claraboia.bibleandroid.R
import com.claraboia.bibleandroid.bibleApplication
import com.claraboia.bibleandroid.helpers.*
import com.claraboia.bibleandroid.models.Bible
import com.claraboia.bibleandroid.viewmodels.BookForSort
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.google.firebase.auth.FirebaseAuth
import kotlin.concurrent.thread
class DispatchActivity : AppCompatActivity() {
private lateinit var firebaseauth: FirebaseAuth
private val REQUEST_GOOGLE_PLAY_SERVICES = 90909
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//TODO: get this code back
//verifyGooglePlay()
firebaseauth = FirebaseAuth.getInstance()
if (firebaseauth.currentUser == null) {
firebaseauth.signInAnonymously().addOnCompleteListener {
Log.d("DispatchActivity", "signInAnonymously:onComplete:" + it.isSuccessful)
bibleApplication.currentUser = firebaseauth.currentUser
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!it.isSuccessful) {
Log.w("DispatchActivity", "signInAnonymously", it.exception)
Toast.makeText(this, "Authentication failed.", Toast.LENGTH_SHORT).show()
}
performStartupPath()
}
}else{
bibleApplication.currentUser = firebaseauth.currentUser
performStartupPath()
}
}
// private fun verifyGooglePlay(){
// val playServicesStatus = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(this)
// if(playServicesStatus != ConnectionResult.SUCCESS){
// //If google play services in not available show an error dialog and return
// GoogleApiAvailability.getInstance().showErrorDialogFragment(this, playServicesStatus, 0)
// //val errorDialog = GoogleApiAvailability.getInstance().getErrorDialog(this, playServicesStatus, 0, null)
// //errorDialog.show()
// return
// }
// }
private fun performStartupPath(){
bibleApplication.localBibles.addAll(getAvailableBiblesLocal())
if(bibleApplication.localBibles.size == 0 || bibleApplication.preferences.selectedTranslation.isEmpty()) {
val builder = AlertDialog.Builder(this)
builder.setMessage(R.string.translationNeededToStart)
builder.setPositiveButton(R.string.ok) { dialog, button ->
val intent = Intent(this, SelectTranslationActivity::class.java)
intent.putExtra(SHOULD_OPEN_CLOUD_TAB_KEY, true)
startActivity(intent)
finish()
}
val dialog = builder.create()
dialog.show()
}else{
loadCurrentBible()
val intent = Intent(this, ReadActivity::class.java)
startActivity(intent)
finish()
}
}
private fun loadCurrentBible() {
bibleApplication.currentBible = loadBible(bibleApplication.preferences.selectedTranslation)
//load last accessed address as current position
val lastAddress = bibleApplication.preferences.lastAccessedAddress
bibleApplication.currentBook = lastAddress.bookOrder
bibleApplication.currentChapter = lastAddress.chapterOrder
//create a bookCollection to be able to sort, change without affect orignal list
bibleApplication.currentBible.books.forEach { b ->
val newbook = BookForSort(
b.bookOrder,
b.chapters.size,
b.getBookName(),
b.getBookAbbrev(),
b.getBookType()
)
bibleApplication.booksForSelection.add(newbook)
}
}
}
| apache-2.0 |
jorgefranconunes/jeedemos | build-systems/kotlin-gradle-Multiproject/cli/src/main/kotlin/com/varmateo/Main.kt | 1 | 261 | package com.varmateo
import com.varmateo.say
import com.varmateo.yawg.api.YawgInfo
fun main(args: Array<String>) {
val yawgDetails = "${YawgInfo.PRODUCT_NAME} ${YawgInfo.VERSION}"
val message = "Hello, we are using $yawgDetails"
say(message)
}
| gpl-3.0 |
fossasia/rp15 | app/src/main/java/org/fossasia/openevent/general/ticket/TicketDao.kt | 2 | 924 | package org.fossasia.openevent.general.ticket
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import io.reactivex.Flowable
import io.reactivex.Single
@Dao
interface TicketDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertTickets(tickets: List<Ticket>)
@Query("DELETE FROM Ticket")
fun deleteAll()
@Query("SELECT * from Ticket WHERE event = :eventId")
fun getTicketsForEvent(eventId: Long): Flowable<List<Ticket>>
@Query("SELECT * from Ticket WHERE id = :id")
fun getTicketDetails(id: Long): Single<Ticket>
@Query("SELECT * from Ticket WHERE id in (:ids)")
fun getTicketsWithIds(ids: List<Int>): Single<List<Ticket>>
@Query("SELECT MAX(price) as maxValue, MIN(price) as minValue from Ticket WHERE event = :eventId")
fun getTicketPriceRange(eventId: Long): Single<TicketPriceRange>
}
| apache-2.0 |
Authman2/Orbs-2 | Orbs2/src/main/java/tiles/Tiles.kt | 1 | 5379 | package tiles
import je.visual.Vector2D
import main_package.Assets
import states.WorldState
/**
EMPTY TILE
*/
class EmptyTile(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.EMPTY, ws) {
init {
setSolid(false)
}
}
/**
COBBLESTONE TILE
*/
class CobbleStoneTile(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.COBBLESTONE, ws) {
init {
setSolid(false)
}
}
/**
GRASS TILE
*/
class GrassTile(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.GRASS_1, ws) {
init {
setSolid(false)
}
}
/**
WOOD TILE
*/
class WoodFloor(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.WOOD_FLOOR, ws) {
init {
setSolid(false)
}
}
/**
Well
*/
class Well(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.WELL, ws) {
init {
setSolid(true)
}
}
/**
TREE TOP TILE
*/
class TreeTop(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.TREE_TOP, ws) {
init {
setSolid(true)
}
}
/**
TREE BOTTOM TILE
*/
class TreeBottom(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.TREE_BOTTOM, ws) {
init {
setSolid(true)
}
}
/**
BLUE RUG TOP LEFT TILE
*/
class BlueRug_TL(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.BLUE_RUG_TL, ws) {
init {
setSolid(false)
}
}
/**
BLUE RUG BOTTOM LEFT TILE
*/
class BlueRug_BL(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.BLUE_RUG_BL, ws) {
init {
setSolid(false)
}
}
/**
BLUE RUG TOP RIGHT TILE
*/
class BlueRug_TR(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.BLUE_RUG_TR, ws) {
init {
setSolid(false)
}
}
/**
BLUE RUG BOTTOM RIGHT TILE
*/
class BlueRug_BR(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.BLUE_RUG_BR, ws) {
init {
setSolid(false)
}
}
/**
RED RUG TOP LEFT TILE
*/
class RedRug_TL(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.RED_RUG_TL, ws) {
init {
setSolid(false)
}
}
/**
RED RUG BOTTOM LEFT TILE
*/
class RedRug_BL(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.RED_RUG_BL, ws) {
init {
setSolid(false)
}
}
/**
RED RUG TOP RIGHT TILE
*/
class RedRug_TR(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.RED_RUG_TR, ws) {
init {
setSolid(false)
}
}
/**
RED RUG BOTTOM RIGHT TILE
*/
class RedRug_BR(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.RED_RUG_BR, ws) {
init {
setSolid(false)
}
}
/**
HOUSE 1 TOP LEFT TILE
*/
class HouseOne_TL(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.HOUSE_1_TL, ws) {
init {
setSolid(true)
}
}
/**
HOUSE 1 LEFT TILE
*/
class HouseOne_L(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.HOUSE_1_L, ws) {
init {
setSolid(true)
defineCollisionArea(position.X*size, position.Y*size, size - 18, size)
}
}
/**
HOUSE 1 BOTTOM LEFT TILE
*/
class HouseOne_BL(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.HOUSE_1_BL, ws) {
init {
setSolid(true)
defineCollisionArea(position.X*size, position.Y*size + 8, size - 18, size - 8)
}
}
/**
HOUSE 1 BASE LEFT TILE
*/
class HouseOne_BaseL(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.HOUSE_1_BASE_L, ws) {
init {
setSolid(true)
}
}
/**
HOUSE 1 TOP RIGHT TILE
*/
class HouseOne_TR(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.HOUSE_1_TR, ws) {
init {
setSolid(true)
}
}
/**
HOUSE 1 RIGHT TILE
*/
class HouseOne_R(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.HOUSE_1_R, ws) {
init {
setSolid(true)
defineCollisionArea(position.X*size + 18, position.Y*size, size - 18, size)
}
}
/**
HOUSE 1 BOTTOM RIGHT TILE
*/
class HouseOne_BR(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.HOUSE_1_BR, ws) {
init {
setSolid(true)
defineCollisionArea(position.X*size + 18, position.Y*size + 8, size - 18, size - 8)
}
}
/**
HOUSE 1 BASE RIGHT TILE
*/
class HouseOne_BaseR(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.HOUSE_1_BASE_R, ws) {
init {
setSolid(true)
}
}
/**
HOUSE 1 TOP TILE
*/
class HouseOne_Top(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.HOUSE_1_T, ws) {
init {
setSolid(true)
}
}
/**
HOUSE 1 INNER TILE
*/
class HouseOne_Inner(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.HOUSE_1_INNER, ws) {
init {
setSolid(true)
defineCollisionArea(position.X*size, position.Y*size + 24, size, size - 24)
}
}
/**
HOUSE 1 WINDOW TILE
*/
class HouseOne_Window(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.HOUSE_1_WINDOW, ws) {
init {
setSolid(true)
}
}
/**
HOUSE 1 WALL TILE
*/
class HouseOne_Wall(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.HOUSE_1_WALL, ws) {
init {
setSolid(true)
}
}
/**
HOUSE 1 DOOR LEFT TILE
*/
class HouseOne_DoorL(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.HOUSE_1_DOOR_L, ws) {
init {
setSolid(true)
}
}
/**
HOUSE 1 DOOR RIGHT TILE
*/
class HouseOne_DoorR(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.HOUSE_1_DOOR_R, ws) {
init {
setSolid(true)
}
}
/**
HOUSE 1 DOOR TOP LEFT TILE
*/
class HouseOne_DoorTL(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.HOUSE_1_DOOR_TL, ws) {
init {
setSolid(true)
defineCollisionArea(position.X*size, position.Y*size + 24, size, size - 24)
}
}
/**
HOUSE 1 DOOR TOP RIGHT TILE
*/
class HouseOne_DoorTR(pos: Vector2D?, ws: WorldState?) : Tile(pos, Assets.HOUSE_1_DOOR_TR, ws) {
init {
setSolid(true)
defineCollisionArea(position.X*size, position.Y*size + 24, size, size - 24)
}
} | gpl-3.0 |
seventhroot/elysium | bukkit/rpk-stat-builds-bukkit/src/main/kotlin/com/rpkit/statbuilds/bukkit/statbuild/RPKCharacterStatPoints.kt | 1 | 984 | /*
* Copyright 2020 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.statbuilds.bukkit.statbuild
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.core.database.Entity
import com.rpkit.statbuilds.bukkit.statattribute.RPKStatAttribute
class RPKCharacterStatPoints(
override var id: Int = 0,
val character: RPKCharacter,
val statAttribute: RPKStatAttribute,
var points: Int
): Entity | apache-2.0 |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/database/RowColumnValues.kt | 1 | 147 | package org.evomaster.core.database
class RowColumnValues {
operator fun get(tableName: String, columnName: String) {
return
}
} | lgpl-3.0 |
liu-yun/BJUTWiFi | app/src/main/kotlin/me/liuyun/bjutlgn/db/FlowDao.kt | 2 | 446 | package me.liuyun.bjutlgn.db
import androidx.room.*
import me.liuyun.bjutlgn.entity.Flow
/**
* Created by Yun on 2017.7.6.
*/
@Dao
interface FlowDao {
@Query("SELECT * FROM flow")
fun all(): MutableList<Flow>
@Insert
fun insert(flow: Flow)
@Insert
fun insertAll(vararg flows: Flow)
@Update
fun update(flow: Flow)
@Delete
fun delete(flow: Flow)
@Query("DELETE FROM flow")
fun deleteAll()
} | mit |
EMResearch/EvoMaster | e2e-tests/spring-rest-mysql/src/main/kotlin/com/foo/spring/rest/mysql/SwaggerConfiguration.kt | 2 | 1014 | package com.foo.spring.rest.mysql
import org.springframework.context.annotation.Bean
import org.springframework.security.core.Authentication
import org.springframework.web.context.request.WebRequest
import springfox.documentation.builders.ApiInfoBuilder
import springfox.documentation.builders.PathSelectors
import springfox.documentation.service.ApiInfo
import springfox.documentation.spi.DocumentationType
import springfox.documentation.spring.web.plugins.Docket
open class SwaggerConfiguration {
@Bean
open fun docketApi(): Docket {
return Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.paths(PathSelectors.regex("/api/.*"))
.build()
.ignoredParameterTypes(WebRequest::class.java, Authentication::class.java)
}
private fun apiInfo(): ApiInfo {
return ApiInfoBuilder()
.title("API")
.description("Some description")
.version("1.0")
.build()
}
} | lgpl-3.0 |
EMResearch/EvoMaster | core/src/test/kotlin/org/evomaster/core/search/service/RandomnessTest.kt | 1 | 3687 | package org.evomaster.core.search.service
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
class RandomnessTest{
private lateinit var rand : Randomness
private val seed = 42L
@BeforeEach
fun init(){
rand = Randomness()
rand.updateSeed(seed)
}
@Test
fun testMaxMinInt(){
val min = -42
val max = 1234
rand.updateSeed(seed)
var a = ""
for(i in 0 until 100){
val k = rand.nextInt(min, max)
assertTrue(k >= min)
assertTrue(k <= max)
a += k
}
rand.updateSeed(seed)
var b = ""
for(i in 0 until 100){
val k = rand.nextInt(min, max)
assertTrue(k >= min)
assertTrue(k <= max)
b += k
}
assertEquals(a, b)
}
@Test
fun testChooseByProbability(){
val m = mutableMapOf<String, Double>()
m["a"] = 1.0
m["b"] = 2.0
m["c"] = 1.0
m["d"] = 1.0
m["e"] = 2.0
rand.updateSeed(seed)
var a = ""
for(i in 0 until 100){
val k = rand.chooseByProbability(m)
a += k
}
rand.updateSeed(seed)
var b = ""
for(i in 0 until 100){
val k = rand.chooseByProbability(m)
b += k
}
assertEquals(a, b)
}
@Test
fun testChooseListUpToN(){
val list = listOf(0,1,2,3,4,5,6,7,8,9,10)
rand.updateSeed(seed)
var a = ""
for(i in 0 until 100){
val k = rand.choose(list, 5)
assertTrue(k.size >= 0, "Size is ${k.size}")
assertTrue(k.size <= 5, "Size is ${k.size}")
a += k.joinToString("")
}
rand.updateSeed(seed)
var b = ""
for(i in 0 until 100){
val k = rand.choose(list, 5)
assertTrue(k.size >= 0, "Size is ${k.size}")
assertTrue(k.size <= 5, "Size is ${k.size}")
b += k.joinToString("")
}
assertEquals(a, b)
}
@Test
fun testChooseSetUpToN(){
val list = setOf(0,1,2,3,4,5,6,7,8,9,10)
rand.updateSeed(seed)
var a = ""
for(i in 0 until 100){
val k = rand.choose(list, 5)
assertTrue(k.size >= 0, "Size is ${k.size}")
assertTrue(k.size <= 5, "Size is ${k.size}")
a += k.joinToString("")
}
rand.updateSeed(seed)
var b = ""
for(i in 0 until 100){
val k = rand.choose(list, 5)
assertTrue(k.size >= 0, "Size is ${k.size}")
assertTrue(k.size <= 5, "Size is ${k.size}")
b += k.joinToString("")
}
assertEquals(a, b)
}
@Test
fun testChooseFromMap(){
val m = mutableMapOf<String, String>()
m["a"] = "0"
m["b"] = "1"
m["c"] = "2"
m["d"] = "3"
m["e"] = "4"
rand.updateSeed(seed)
var a = ""
for(i in 0 until 100){
val k = rand.choose(m)
a += k
}
rand.updateSeed(seed)
var b = ""
for(i in 0 until 100){
val k = rand.choose(m)
b += k
}
assertEquals(a, b)
}
@Test
fun chooseIntRange(){
val a = listOf(3,4,5,6)
val seen = a.map { false }.toMutableList()
for(i in 0 until 100){
val k = rand.choose(a.indices)
assertTrue(k in 0..3, "Wrong value: $k")
seen[k] = true
}
assertTrue(seen.all { it })
}
} | lgpl-3.0 |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/problem/external/service/httpws/param/HttpWsResponseParam.kt | 1 | 2216 | package org.evomaster.core.problem.external.service.httpws.param
import org.evomaster.core.problem.api.service.param.Param
import org.evomaster.core.problem.external.service.param.ResponseParam
import org.evomaster.core.search.gene.collection.EnumGene
import org.evomaster.core.search.gene.optional.OptionalGene
import org.evomaster.core.search.gene.string.StringGene
class HttpWsResponseParam (
/**
* Contains the values for HTTP status codes.
* Avoid having 404 as status, since WireMock will return 404 if there is
* no stub for the specific request.
*/
val status: EnumGene<Int> = getDefaultStatusEnumGene(),
/**
* Response content type, for now supports only JSON
*
* TODO might want to support XML and other formats here in the future
*/
responseType: EnumGene<String> = EnumGene("responseType", listOf("JSON")),
/**
* The body payload of the response, if any.
* Notice that the gene is a String, although the body might NOT be a string, but rather an Object or Array.
* This still works because we handle it in the phenotype representation, ie using raw values of specializations,
* which will not be quoted ""
*
* TODO: might want to extend StringGene to avoid cases in which taint is lost due to mutation
*/
responseBody: OptionalGene = OptionalGene(RESPONSE_GENE_NAME, StringGene(RESPONSE_GENE_NAME)),
val connectionHeader : String? = DEFAULT_HEADER_CONNECTION
): ResponseParam("response", responseType, responseBody, listOf(status)) {
companion object{
const val RESPONSE_GENE_NAME = "WireMockResponseGene"
const val DEFAULT_HEADER_CONNECTION : String = "close"
fun getDefaultStatusEnumGene() = EnumGene("status", listOf(200, 201, 204, 400, 401, 403, 500))
}
override fun copyContent(): Param {
return HttpWsResponseParam(status.copy() as EnumGene<Int>, responseType.copy() as EnumGene<String>, responseBody.copy() as OptionalGene, connectionHeader)
}
fun setStatus(statusCode : Int) : Boolean{
val index = status.values.indexOf(statusCode)
if (index == -1) return false
status.index = index
return true
}
} | lgpl-3.0 |
badoualy/kotlogram | mtproto/src/main/kotlin/com/github/badoualy/telegram/mtproto/tl/MTRpcError.kt | 1 | 1381 | package com.github.badoualy.telegram.mtproto.tl
import com.github.badoualy.telegram.tl.StreamUtils.*
import com.github.badoualy.telegram.tl.TLContext
import com.github.badoualy.telegram.tl.core.TLObject
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.regex.Pattern
class MTRpcError @JvmOverloads constructor(var errorCode: Int = 0, var message: String = "") : TLObject() {
val errorTag: String
get() {
if (message.isEmpty())
return "DEFAULT"
val matcher = REGEXP_PATTERN.matcher(message)
if (matcher.find())
return matcher.group()
return "DEFAULT"
}
override fun getConstructorId(): Int {
return CONSTRUCTOR_ID
}
@Throws(IOException::class)
override fun serializeBody(stream: OutputStream) {
writeInt(errorCode, stream)
writeString(message, stream)
}
@Throws(IOException::class)
override fun deserializeBody(stream: InputStream, context: TLContext) {
errorCode = readInt(stream)
message = readTLString(stream)
}
override fun toString(): String {
return "rpc_error#2144ca19"
}
companion object {
private val REGEXP_PATTERN = Pattern.compile("[A-Z_0-9]+")
@JvmField
val CONSTRUCTOR_ID = 558156313
}
}
| mit |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/client/LogsActivity.kt | 1 | 7280 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Adrien Beraud <[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 cx.ring.client
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.google.android.material.snackbar.Snackbar
import cx.ring.R
import cx.ring.application.JamiApplication
import cx.ring.databinding.ActivityLogsBinding
import cx.ring.utils.AndroidFileUtils
import cx.ring.utils.ContentUriHandler
import dagger.hilt.android.AndroidEntryPoint
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Maybe
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import net.jami.services.HardwareService
import net.jami.utils.StringUtils
import java.io.File
import java.io.FileOutputStream
import javax.inject.Inject
import javax.inject.Singleton
@AndroidEntryPoint
class LogsActivity : AppCompatActivity() {
private lateinit var binding: ActivityLogsBinding
private val compositeDisposable = CompositeDisposable()
private var disposable: Disposable? = null
private lateinit var fileSaver: ActivityResultLauncher<String>
private var mCurrentFile: File? = null
@Inject
@Singleton
lateinit var mHardwareService: HardwareService
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
JamiApplication.instance?.startDaemon()
binding = ActivityLogsBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
fileSaver = registerForActivityResult(ActivityResultContracts.CreateDocument()) { result: Uri? ->
if (result != null)
compositeDisposable.add(AndroidFileUtils.copyFileToUri(contentResolver, mCurrentFile, result)
.observeOn(AndroidSchedulers.mainThread()).subscribe({
if (!mCurrentFile!!.delete())
Log.w(TAG, "Can't delete temp file")
mCurrentFile = null
Snackbar.make(binding.root, R.string.file_saved_successfully, Snackbar.LENGTH_SHORT).show()
}) { Snackbar.make(binding.root, R.string.generic_error, Snackbar.LENGTH_SHORT).show()
})
}
binding.fab.setOnClickListener { if (disposable == null) startLogging() else stopLogging() }
if (mHardwareService.isLogging) startLogging()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.logs_menu, menu)
return super.onCreateOptionsMenu(menu)
}
private val log: Maybe<String>
get() {
if (mHardwareService.isLogging)
return mHardwareService.startLogs().firstElement()
val log = binding.logView.text
return if (StringUtils.isEmpty(log)) Maybe.empty()
else Maybe.just(log.toString())
}
private val logFile: Maybe<File>
get() = log
.observeOn(Schedulers.io())
.map { log: String ->
val file = AndroidFileUtils.createLogFile(this)
FileOutputStream(file).use { os -> os.write(log.toByteArray()) }
file
}
private val logUri: Maybe<Uri>
get() = logFile.map { file: File ->
ContentUriHandler.getUriForFile(this, ContentUriHandler.AUTHORITY_FILES, file)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
return true
}
R.id.menu_log_share -> {
compositeDisposable.add(logUri.observeOn(AndroidSchedulers.mainThread())
.subscribe({ uri: Uri ->
Log.w(TAG, "saved logs to $uri")
val sendIntent = Intent(Intent.ACTION_SEND).apply {
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
setDataAndType(uri, contentResolver.getType(uri))
putExtra(Intent.EXTRA_STREAM, uri)
}
startActivity(Intent.createChooser(sendIntent, null))
}) { e: Throwable ->
Snackbar.make(binding.root, "Error sharing logs: " + e.localizedMessage, Snackbar.LENGTH_SHORT).show()
})
return true
}
R.id.menu_log_save -> {
compositeDisposable.add(logFile.subscribe { file: File ->
mCurrentFile = file
fileSaver.launch(file.name)
})
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
private fun startLogging() {
binding.logView.text = ""
disposable = mHardwareService.startLogs()
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ message: String ->
binding.logView.text = message
binding.scroll.post { binding.scroll.fullScroll(View.FOCUS_DOWN) }
}) { e -> Log.w(TAG, "Error in logger", e) }
compositeDisposable.add(disposable)
setButtonState(true)
}
private fun stopLogging() {
disposable?.let {
it.dispose()
disposable = null
}
mHardwareService.stopLogs()
setButtonState(false)
}
private fun setButtonState(logging: Boolean) {
binding.fab.setText(if (logging) R.string.pref_logs_stop else R.string.pref_logs_start)
binding.fab.setBackgroundColor(ContextCompat.getColor(this, if (logging) R.color.red_400 else R.color.colorSecondary))
}
override fun onDestroy() {
disposable?.let {
it.dispose()
disposable = null
}
compositeDisposable.clear()
super.onDestroy()
}
companion object {
private val TAG = LogsActivity::class.simpleName!!
}
} | gpl-3.0 |
VoIPGRID/vialer-android | app/src/main/java/com/voipgrid/vialer/notifications/EncryptionDisabledNotification.kt | 1 | 2034 | package com.voipgrid.vialer.notifications
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.app.TaskStackBuilder
import com.voipgrid.vialer.MainActivity
import com.voipgrid.vialer.R
import com.voipgrid.vialer.SettingsActivity
class EncryptionDisabledNotification : AbstractNotification() {
override val notificationId: Int = 3
@RequiresApi(Build.VERSION_CODES.O)
override fun buildChannel(context : Context): NotificationChannel {
return NotificationChannel(
CHANNEL_ID,
context.getString(R.string.notification_channel_encryption_disabled),
NotificationManager.IMPORTANCE_LOW
)
}
override fun buildNotification(context: Context): android.app.Notification {
val builder = NotificationCompat.Builder(context, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_lock_open)
.setAutoCancel(false)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setContentTitle(context.getString(R.string.encrypted_calling_notification_title))
.setContentText(context.getString(R.string.encrypted_calling_notification_description))
.setOngoing(true)
.setVibrate(null)
val stackBuilder = TaskStackBuilder.create(context)
stackBuilder.addParentStack(MainActivity::class.java)
stackBuilder.addNextIntent(Intent(context, SettingsActivity::class.java))
builder.setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT))
return builder.build()
}
override fun provideChannelsToDelete() = listOf("vialer_encryption_disabled")
companion object {
const val CHANNEL_ID: String = "vialer_encryption_disabled_notifications"
}
} | gpl-3.0 |
Petrulak/kotlin-mvp-clean-architecture | app/src/main/java/com/petrulak/cleankotlin/platform/bus/event/events/BaseEvent.kt | 1 | 358 | package com.petrulak.cleankotlin.platform.bus.event.events
open class BaseEvent<T> {
val eventType: String
val payload: T?
constructor(eventType: String, payload: T) {
this.eventType = eventType
this.payload = payload
}
constructor(eventType: String) {
this.eventType = eventType
payload = null
}
} | mit |
Jire/Acelta | src/main/kotlin/com/acelta/world/mob/Direction.kt | 1 | 1001 | package com.acelta.world.mob
import com.acelta.world.Position
enum class Direction(val value: Int) {
NONE(-1), NORTH_WEST(0), NORTH(1), NORTH_EAST(2), WEST(3), EAST(4), SOUTH_WEST(5), SOUTH(6), SOUTH_EAST(7);
companion object {
fun between(currentX: Int, currentY: Int, nextX: Int, nextY: Int): Direction {
val deltaX = nextX - currentX
val deltaY = nextY - currentY
if (deltaY == 1) {
if (deltaX == 1) return NORTH_EAST
else if (deltaX == 0) return NORTH
else if (deltaX == -1) return NORTH_WEST
} else if (deltaY == -1) {
if (deltaX == 1) return SOUTH_EAST
else if (deltaX == 0) return SOUTH
else if (deltaX == -1) return SOUTH_WEST
} else if (deltaY == 0) {
if (deltaX == 1) return EAST
else if (deltaX == 0) return NONE
else if (deltaX == -1) return WEST
}
return NONE
}
fun between(currentPosition: Position, nextPosition: Position)
= between(currentPosition.x, currentPosition.y, nextPosition.x, nextPosition.y)
}
} | gpl-3.0 |
NephyProject/Penicillin | src/main/kotlin/jp/nephy/penicillin/endpoints/statuses/Delete.kt | 1 | 2685 | /*
* The MIT License (MIT)
*
* Copyright (c) 2017-2019 Nephy Project Team
*
* 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.
*/
@file:Suppress("UNUSED", "PublicApiImplicitType")
package jp.nephy.penicillin.endpoints.statuses
import jp.nephy.penicillin.core.request.action.JsonObjectApiAction
import jp.nephy.penicillin.core.request.formBody
import jp.nephy.penicillin.core.session.post
import jp.nephy.penicillin.endpoints.Option
import jp.nephy.penicillin.endpoints.Statuses
import jp.nephy.penicillin.endpoints.common.TweetMode
import jp.nephy.penicillin.models.Status
/**
* Destroys the status specified by the required ID parameter. The authenticating user must be the author of the specified status. Returns the destroyed status if successful.
*
* [Twitter API reference](https://developer.twitter.com/en/docs/tweets/post-and-engage/api-reference/post-statuses-destroy-id)
*
* @param id The numerical ID of the desired status.
* @param trimUser When set to either true , t or 1 , each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object.
* @param options Optional. Custom parameters of this request.
* @receiver [Statuses] endpoint instance.
* @return [JsonObjectApiAction] for [Status] model.
*/
fun Statuses.delete(
id: Long,
trimUser: Boolean? = null,
tweetMode: TweetMode = TweetMode.Default,
vararg options: Option
) = client.session.post("/1.1/statuses/destroy/$id.json") {
formBody(
"trim_user" to trimUser,
"tweet_mode" to tweetMode,
*options
)
}.jsonObject<Status>()
| mit |
google/private-compute-libraries | javatests/com/google/android/libraries/pcc/chronicle/analysis/DefaultChronicleContextTest.kt | 1 | 9281 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.analysis
import com.google.android.libraries.pcc.chronicle.api.Connection
import com.google.android.libraries.pcc.chronicle.api.ConnectionProvider
import com.google.android.libraries.pcc.chronicle.api.ConnectionRequest
import com.google.android.libraries.pcc.chronicle.api.DataType
import com.google.android.libraries.pcc.chronicle.api.ManagedDataType
import com.google.android.libraries.pcc.chronicle.api.ManagementStrategy
import com.google.android.libraries.pcc.chronicle.api.ProcessorNode
import com.google.android.libraries.pcc.chronicle.api.ReadConnection
import com.google.android.libraries.pcc.chronicle.api.WriteConnection
import com.google.android.libraries.pcc.chronicle.api.dataTypeDescriptor
import com.google.android.libraries.pcc.chronicle.api.error.ConnectionTypeAmbiguity
import com.google.android.libraries.pcc.chronicle.util.Key
import com.google.android.libraries.pcc.chronicle.util.MutableTypedMap
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.mock
import kotlin.test.assertFailsWith
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class DefaultChronicleContextTest {
@Test
fun moreThanOneConnectibleByConnectionType_throws() {
val node1 =
object : ConnectionProvider {
override val dataType: DataType =
ManagedDataType(
descriptor = dataTypeDescriptor("Foo", Unit::class),
managementStrategy = ManagementStrategy.PassThru,
connectionTypes = setOf(FooReader::class.java)
)
override fun getConnection(
connectionRequest: ConnectionRequest<out Connection>
): Connection = FooReader()
}
// Same connection type should cause the error to be thrown. The dataType being different is
// not relevant to the check.
val node2 =
object : ConnectionProvider {
override val dataType: DataType =
ManagedDataType(
descriptor = dataTypeDescriptor("Bar", Unit::class),
managementStrategy = ManagementStrategy.PassThru,
connectionTypes = setOf(FooReader::class.java)
)
override fun getConnection(
connectionRequest: ConnectionRequest<out Connection>
): Connection = FooReader()
}
assertFailsWith<ConnectionTypeAmbiguity> {
DefaultChronicleContext(setOf(node1, node2), emptySet(), DefaultPolicySet(emptySet()), mock())
}
}
@Test
fun findConnectionProvider() {
val readerConnectionProvider = FooReaderConnectionProvider()
val writerConnectionProvider = FooWriterConnectionProvider()
val context =
DefaultChronicleContext(
setOf(readerConnectionProvider, writerConnectionProvider),
emptySet(),
DefaultPolicySet(emptySet()),
mock()
)
assertThat(context.findConnectionProvider(FooReader::class.java))
.isSameInstanceAs(readerConnectionProvider)
assertThat(context.findConnectionProvider(FooWriter::class.java))
.isSameInstanceAs(writerConnectionProvider)
}
@Test
fun findDataType() {
val fooReaderConnectionProvider = FooReaderConnectionProvider()
val fooWriterConnectionProvider = FooWriterConnectionProvider()
val barReaderWriterConnectionProvider = BarReaderWriterConnectionProvider()
val context =
DefaultChronicleContext(
setOf(
fooReaderConnectionProvider,
fooWriterConnectionProvider,
barReaderWriterConnectionProvider
),
emptySet(),
DefaultPolicySet(emptySet()),
mock()
)
assertThat(context.findDataType(FooReader::class.java))
.isEqualTo(dataTypeDescriptor("Foo", Unit::class))
assertThat(context.findDataType(FooWriter::class.java))
.isEqualTo(dataTypeDescriptor("Foo", Unit::class))
assertThat(context.findDataType(BarReader::class.java))
.isEqualTo(dataTypeDescriptor("Bar", Unit::class))
assertThat(context.findDataType(BarWriter::class.java))
.isEqualTo(dataTypeDescriptor("Bar", Unit::class))
}
@Test
fun withNode_processor_leavesExistingUnchanged() {
val context =
DefaultChronicleContext(
setOf(FooReaderConnectionProvider()),
emptySet(),
DefaultPolicySet(emptySet()),
mock()
)
val updated = context.withNode(FooBarProcessor())
assertThat(context)
.isEqualTo(
DefaultChronicleContext(
setOf(FooReaderConnectionProvider()),
emptySet(),
DefaultPolicySet(emptySet()),
mock()
)
)
assertThat(updated).isNotEqualTo(context)
assertThat(updated)
.isEqualTo(
DefaultChronicleContext(
setOf(FooReaderConnectionProvider()),
setOf(FooBarProcessor()),
DefaultPolicySet(emptySet()),
mock()
)
)
}
@Test
fun withConnectionContext_processor_leavesExistingUnchanged() {
val mutableTypedMap = MutableTypedMap()
val connectionContext = mutableTypedMap.toTypedMap()
val context =
DefaultChronicleContext(
setOf(FooReaderConnectionProvider()),
emptySet(),
DefaultPolicySet(emptySet()),
mock(),
connectionContext
)
// Update the `connectionContext`
mutableTypedMap[Name] = "test"
val otherConnectionContext = mutableTypedMap.toTypedMap()
val updated = context.withConnectionContext(otherConnectionContext)
// Initial context should not have the Name key
assertThat(context.connectionContext[Name]).isNull()
assertThat(context)
.isEqualTo(
DefaultChronicleContext(
setOf(FooReaderConnectionProvider()),
emptySet(),
DefaultPolicySet(emptySet()),
mock(),
connectionContext
)
)
// Updated context has the Name key
assertThat(updated.connectionContext[Name]).isEqualTo("test")
assertThat(updated).isNotEqualTo(context)
assertThat(updated)
.isEqualTo(
DefaultChronicleContext(
setOf(FooReaderConnectionProvider()),
emptySet(),
DefaultPolicySet(emptySet()),
mock(),
otherConnectionContext
)
)
}
// Test key for `connectionContext`
private object Name : Key<String>
class FooReader : ReadConnection
class FooWriter : WriteConnection
class BarReader : ReadConnection
class BarWriter : WriteConnection
class FooReaderConnectionProvider : ConnectionProvider {
override val dataType: DataType =
ManagedDataType(
descriptor = dataTypeDescriptor("Foo", Unit::class),
managementStrategy = ManagementStrategy.PassThru,
connectionTypes = setOf(FooReader::class.java)
)
override fun getConnection(connectionRequest: ConnectionRequest<out Connection>): Connection =
FooReader()
override fun equals(other: Any?): Boolean = other is FooReaderConnectionProvider
override fun hashCode(): Int {
return javaClass.hashCode()
}
}
class FooWriterConnectionProvider : ConnectionProvider {
override val dataType: DataType =
ManagedDataType(
descriptor = dataTypeDescriptor("Foo", Unit::class),
managementStrategy = ManagementStrategy.PassThru,
connectionTypes = setOf(FooWriter::class.java)
)
override fun getConnection(connectionRequest: ConnectionRequest<out Connection>): Connection =
FooWriter()
override fun equals(other: Any?): Boolean = other is FooWriterConnectionProvider
override fun hashCode(): Int {
return javaClass.hashCode()
}
}
class BarReaderWriterConnectionProvider : ConnectionProvider {
override val dataType: DataType =
ManagedDataType(
descriptor = dataTypeDescriptor("Bar", Unit::class),
managementStrategy = ManagementStrategy.PassThru,
connectionTypes = setOf(BarReader::class.java, BarWriter::class.java)
)
override fun getConnection(connectionRequest: ConnectionRequest<out Connection>): Connection =
BarWriter()
override fun equals(other: Any?): Boolean = other is BarReaderWriterConnectionProvider
override fun hashCode(): Int {
return javaClass.hashCode()
}
}
class FooBarProcessor : ProcessorNode {
override val requiredConnectionTypes =
setOf(
FooReader::class.java,
FooWriter::class.java,
BarReader::class.java,
BarWriter::class.java
)
override fun equals(other: Any?): Boolean = other is FooBarProcessor
override fun hashCode(): Int {
return javaClass.hashCode()
}
}
}
| apache-2.0 |
tikivn/android-template | app/src/main/java/vn/tiki/sample/redux/ReduxDemoActivity.kt | 1 | 1884 | package vn.tiki.sample.redux
import android.os.Bundle
import android.os.SystemClock
import android.support.v7.app.AppCompatActivity
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_redux_demo.tvValue
import vn.tiki.architecture.redux.Epic
import vn.tiki.architecture.redux.Store
import vn.tiki.architecture.redux.createStore
import vn.tiki.sample.R
import vn.tiki.sample.redux.ReduxDemoActivity.Action.AddAction
import vn.tiki.sample.redux.ReduxDemoActivity.Action.MultiplyAction
class ReduxDemoActivity : AppCompatActivity() {
sealed class Action {
data class AddAction(val value: Int) : Action()
data class MultiplyAction(val value: Int) : Action()
}
private lateinit var store: Store<Int>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_redux_demo)
val addEpic = Epic<Int> { actions, getState ->
actions.ofType(AddAction::class.java)
.switchMap { action ->
Observable.fromCallable {
SystemClock.sleep(1000)
getState() + action.value
}.subscribeOn(Schedulers.io())
}
}
val multiplyEpic = Epic<Int> { actions, getState ->
actions.ofType(MultiplyAction::class.java)
.switchMap { action ->
Observable.fromCallable {
SystemClock.sleep(2000)
getState() * action.value
}.subscribeOn(Schedulers.io())
}
}
store = createStore(5, listOf(addEpic, multiplyEpic), true)
store.getState()
.observeOn(AndroidSchedulers.mainThread())
.map { "$it" }
.subscribe { tvValue.text = it }
store.dispatch(MultiplyAction(2))
store.dispatch(AddAction(3))
}
}
| apache-2.0 |
tonyofrancis/Fetch | fetch2/src/main/java/com/tonyodev/fetch2/helper/PriorityListProcessorImpl.kt | 1 | 8867 | package com.tonyodev.fetch2.helper
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import com.tonyodev.fetch2.*
import com.tonyodev.fetch2.downloader.DownloadManager
import com.tonyodev.fetch2core.HandlerWrapper
import com.tonyodev.fetch2.provider.DownloadProvider
import com.tonyodev.fetch2.provider.NetworkInfoProvider
import com.tonyodev.fetch2.util.DEFAULT_PRIORITY_QUEUE_INTERVAL_IN_MILLISECONDS
import com.tonyodev.fetch2.NetworkType
import com.tonyodev.fetch2.fetch.ListenerCoordinator
import com.tonyodev.fetch2core.Logger
import com.tonyodev.fetch2core.isFetchFileServerUrl
import java.util.concurrent.TimeUnit
class PriorityListProcessorImpl constructor(private val handlerWrapper: HandlerWrapper,
private val downloadProvider: DownloadProvider,
private val downloadManager: DownloadManager,
private val networkInfoProvider: NetworkInfoProvider,
private val logger: Logger,
private val listenerCoordinator: ListenerCoordinator,
@Volatile
override var downloadConcurrentLimit: Int,
private val context: Context,
private val namespace: String,
private val prioritySort: PrioritySort)
: PriorityListProcessor<Download> {
private val lock = Any()
@Volatile
override var globalNetworkType = NetworkType.GLOBAL_OFF
@Volatile
private var paused = false
override val isPaused: Boolean
get() = paused
@Volatile
private var stopped = true
override val isStopped: Boolean
get() = stopped
@Volatile
private var backOffTime = DEFAULT_PRIORITY_QUEUE_INTERVAL_IN_MILLISECONDS
private val networkChangeListener: NetworkInfoProvider.NetworkChangeListener = object : NetworkInfoProvider.NetworkChangeListener {
override fun onNetworkChanged() {
handlerWrapper.post {
if (!stopped && !paused && networkInfoProvider.isNetworkAvailable
&& backOffTime > DEFAULT_PRIORITY_QUEUE_INTERVAL_IN_MILLISECONDS) {
resetBackOffTime()
}
}
}
}
private val priorityBackoffResetReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (context != null && intent != null) {
when (intent.action) {
ACTION_QUEUE_BACKOFF_RESET -> {
if (!stopped && !paused && namespace == intent.getStringExtra(EXTRA_NAMESPACE)) {
resetBackOffTime()
}
}
}
}
}
}
init {
networkInfoProvider.registerNetworkChangeListener(networkChangeListener)
context.registerReceiver(priorityBackoffResetReceiver, IntentFilter(ACTION_QUEUE_BACKOFF_RESET))
}
private val priorityIteratorRunnable = Runnable {
if (canContinueToProcess()) {
if (downloadManager.canAccommodateNewDownload() && canContinueToProcess()) {
val priorityList = getPriorityList()
var shouldBackOff = false
if (priorityList.isEmpty() || !networkInfoProvider.isNetworkAvailable) {
shouldBackOff = true
}
if (!shouldBackOff) {
shouldBackOff = true
for (index in 0..priorityList.lastIndex) {
if (downloadManager.canAccommodateNewDownload() && canContinueToProcess()) {
val download = priorityList[index]
val isFetchServerRequest = isFetchFileServerUrl(download.url)
if ((isFetchServerRequest || networkInfoProvider.isNetworkAvailable) && canContinueToProcess()) {
val networkType = when {
globalNetworkType != NetworkType.GLOBAL_OFF -> globalNetworkType
download.networkType == NetworkType.GLOBAL_OFF -> NetworkType.ALL
else -> download.networkType
}
val properNetworkConditions = networkInfoProvider.isOnAllowedNetwork(networkType)
if (!properNetworkConditions) {
listenerCoordinator.mainListener.onWaitingNetwork(download)
}
if ((isFetchServerRequest || properNetworkConditions)) {
shouldBackOff = false
if (!downloadManager.contains(download.id) && canContinueToProcess()) {
downloadManager.start(download)
}
}
} else {
break
}
} else {
break
}
}
}
if (shouldBackOff) {
increaseBackOffTime()
}
}
if (canContinueToProcess()) {
registerPriorityIterator()
}
}
}
override fun start() {
synchronized(lock) {
resetBackOffTime()
stopped = false
paused = false
registerPriorityIterator()
logger.d("PriorityIterator started")
}
}
override fun stop() {
synchronized(lock) {
unregisterPriorityIterator()
paused = false
stopped = true
downloadManager.cancelAll()
logger.d("PriorityIterator stop")
}
}
override fun pause() {
synchronized(lock) {
unregisterPriorityIterator()
paused = true
stopped = false
downloadManager.cancelAll()
logger.d("PriorityIterator paused")
}
}
override fun resume() {
synchronized(lock) {
resetBackOffTime()
paused = false
stopped = false
registerPriorityIterator()
logger.d("PriorityIterator resumed")
}
}
override fun getPriorityList(): List<Download> {
synchronized(lock) {
return try {
downloadProvider.getPendingDownloadsSorted(prioritySort)
} catch (e: Exception) {
logger.d("PriorityIterator failed access database", e)
listOf()
}
}
}
private fun registerPriorityIterator() {
if (downloadConcurrentLimit > 0) {
handlerWrapper.postDelayed(priorityIteratorRunnable, backOffTime)
}
}
private fun unregisterPriorityIterator() {
if (downloadConcurrentLimit > 0) {
handlerWrapper.removeCallbacks(priorityIteratorRunnable)
}
}
private fun canContinueToProcess(): Boolean {
return !stopped && !paused
}
override fun resetBackOffTime() {
synchronized(lock) {
backOffTime = DEFAULT_PRIORITY_QUEUE_INTERVAL_IN_MILLISECONDS
unregisterPriorityIterator()
registerPriorityIterator()
logger.d("PriorityIterator backoffTime reset to $backOffTime milliseconds")
}
}
override fun sendBackOffResetSignal() {
synchronized(lock) {
val intent = Intent(ACTION_QUEUE_BACKOFF_RESET)
intent.putExtra(EXTRA_NAMESPACE, namespace)
context.sendBroadcast(intent)
}
}
override fun close() {
synchronized(lock) {
networkInfoProvider.unregisterNetworkChangeListener(networkChangeListener)
context.unregisterReceiver(priorityBackoffResetReceiver)
}
}
private fun increaseBackOffTime() {
backOffTime = if (backOffTime == DEFAULT_PRIORITY_QUEUE_INTERVAL_IN_MILLISECONDS) {
ONE_MINUTE_IN_MILLISECONDS
} else {
backOffTime * 2L
}
val minutes = TimeUnit.MILLISECONDS.toMinutes(backOffTime)
logger.d("PriorityIterator backoffTime increased to $minutes minute(s)")
}
private companion object {
private const val ONE_MINUTE_IN_MILLISECONDS = 60000L
}
} | apache-2.0 |
davinkevin/Podcast-Server | backend/src/main/kotlin/com/github/davinkevin/podcastserver/playlist/Playlist.kt | 1 | 785 | package com.github.davinkevin.podcastserver.playlist
import java.net.URI
import java.nio.file.Path
import java.time.OffsetDateTime
import java.util.*
/**
* Created by kevin on 2019-07-01
*/
data class Playlist(val id: UUID, val name: String)
data class PlaylistWithItems(val id: UUID, val name: String, val items: Collection<Item>) {
data class Item(
val id: UUID,
val title: String,
val fileName: Path?,
val description: String?,
val mimeType: String,
val length: Long?,
val pubDate: OffsetDateTime?,
val podcast: Podcast,
val cover: Cover) {
data class Podcast(val id: UUID, val title: String)
data class Cover (val id: UUID, val width: Int, val height: Int, val url: URI)
}
}
| apache-2.0 |
AlmasB/FXGL | fxgl-core/src/main/kotlin/com/almasb/fxgl/input/view/MouseButtonView.kt | 1 | 4673 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.input.view
import javafx.beans.property.ObjectProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.scene.input.MouseButton
import javafx.scene.layout.Pane
import javafx.scene.paint.*
import javafx.scene.shape.Line
import javafx.scene.shape.Rectangle
/**
* View for a mouse button.
*
* @author Almas Baimagambetov ([email protected])
*/
class MouseButtonView
@JvmOverloads constructor(button: MouseButton,
color: Color = Color.ORANGE,
size: Double = 24.0) : Pane() {
private val border = Rectangle(size, size * 1.5)
fun colorProperty(): ObjectProperty<Paint> = border.strokeProperty()
var color: Paint
get() = border.stroke
set(value) { border.stroke = value }
private val bgColorProp = SimpleObjectProperty(Color.BLACK)
//fun backgroundColorProperty(): ObjectProperty<Color> = bgColorProp
var backgroundColor: Color
get() = bgColorProp.value
set(value) { bgColorProp.value = value }
init {
border.fillProperty().bind(bgColorProp)
border.stroke = color
border.strokeWidth = size / 7
border.arcWidth = size / 1.5
border.arcHeight = size / 1.5
val borderTop = Rectangle(size, size * 1.5)
borderTop.fill = null
borderTop.strokeProperty().bind(border.strokeProperty())
borderTop.strokeWidth = size / 7
borderTop.arcWidth = size / 1.5
borderTop.arcHeight = size / 1.5
val line1 = Line(size / 2, 0.0, size / 2, size / 5)
line1.strokeProperty().bind(border.strokeProperty())
line1.strokeWidth = size / 7
val ellipse = Rectangle(size / 6, size / 6 * 1.5)
ellipse.fill = null
ellipse.strokeProperty().bind(border.strokeProperty())
ellipse.strokeWidth = size / 10
ellipse.arcWidth = size / 1.5
ellipse.arcHeight = size / 1.5
ellipse.translateX = size / 2 - size / 6 / 2
ellipse.translateY = size / 5
val line2 = Line(size / 2, size / 5 * 2.75, size / 2, size / 5 * 5)
line2.stroke = LinearGradient(0.5, 0.0, 0.5, 1.0, true, CycleMethod.NO_CYCLE, Stop(0.0, color), Stop(0.75, backgroundColor))
line2.strokeWidth = size / 7
border.strokeProperty().addListener { _, _, paint ->
if (paint is Color)
line2.stroke = LinearGradient(0.5, 0.0, 0.5, 1.0, true, CycleMethod.NO_CYCLE, Stop(0.0, paint), Stop(0.75, backgroundColor))
}
children.addAll(border, line1, line2, ellipse, borderTop)
when(button) {
MouseButton.PRIMARY -> {
val highlight = Rectangle(size / 2.5, size / 6 * 3.5)
highlight.fill = LinearGradient(0.5, 0.0, 0.5, 1.0, true, CycleMethod.NO_CYCLE, Stop(0.0, backgroundColor), Stop(0.25, color), Stop(0.8, color), Stop(0.9, backgroundColor))
highlight.arcWidth = size / 4
highlight.arcHeight = size / 4
highlight.translateX = size / 20
highlight.translateY = size / 8
border.strokeProperty().addListener { _, _, paint ->
if (paint is Color)
highlight.fill = LinearGradient(0.5, 0.0, 0.5, 1.0, true, CycleMethod.NO_CYCLE, Stop(0.0, backgroundColor), Stop(0.25, paint), Stop(0.8, paint), Stop(0.9, backgroundColor))
}
children.add(1, highlight)
}
MouseButton.SECONDARY -> {
val highlight = Rectangle(size / 2.5, size / 6 * 3.5)
highlight.fill = LinearGradient(0.5, 0.0, 0.5, 1.0, true, CycleMethod.NO_CYCLE, Stop(0.0, backgroundColor), Stop(0.25, color), Stop(0.8, color), Stop(0.9, backgroundColor))
highlight.arcWidth = size / 4
highlight.arcHeight = size / 4
highlight.translateX = size - size / 20 - highlight.width
highlight.translateY = size / 8
border.strokeProperty().addListener { _, _, paint ->
if (paint is Color)
highlight.fill = LinearGradient(0.5, 0.0, 0.5, 1.0, true, CycleMethod.NO_CYCLE, Stop(0.0, backgroundColor), Stop(0.25, paint), Stop(0.8, paint), Stop(0.9, backgroundColor))
}
children.add(1, highlight)
}
else -> {
throw IllegalArgumentException("View for $button type is not (yet?) supported")
}
}
}
} | mit |
AlmasB/FXGL | fxgl-entity/src/main/kotlin/com/almasb/fxgl/entity/components/DataComponents.kt | 1 | 3473 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.entity.components
import com.almasb.fxgl.core.serialization.Bundle
import com.almasb.fxgl.entity.component.Component
import com.almasb.fxgl.entity.component.SerializableComponent
import javafx.beans.property.*
/**
* @author Almas Baimagambetov (AlmasB) ([email protected])
*/
/**
* Represents a boolean value based component.
*/
abstract class BooleanComponent
@JvmOverloads constructor(initialValue: Boolean = false) : Component(), SerializableComponent {
private val property: BooleanProperty = SimpleBooleanProperty(initialValue)
var value: Boolean
get() = property.get()
set(value) = property.set(value)
fun valueProperty() = property
override fun write(bundle: Bundle) {
bundle.put("value", value)
}
override fun read(bundle: Bundle) {
value = bundle.get("value")
}
override fun toString() = "${javaClass.simpleName.substringBefore("Component")}($value)"
}
/**
* Represents an int value based component.
*/
abstract class IntegerComponent
@JvmOverloads constructor(initialValue: Int = 0) : Component(), SerializableComponent {
private val property: IntegerProperty = SimpleIntegerProperty(initialValue)
var value: Int
get() = property.get()
set(value) = property.set(value)
fun valueProperty() = property
override fun write(bundle: Bundle) {
bundle.put("value", value)
}
override fun read(bundle: Bundle) {
value = bundle.get("value")
}
override fun toString() = "${javaClass.simpleName.substringBefore("Component")}($value)"
}
/**
* Represents a double value based component.
*/
abstract class DoubleComponent
@JvmOverloads constructor(initialValue: Double = 0.0) : Component(), SerializableComponent {
private val property: DoubleProperty = SimpleDoubleProperty(initialValue)
var value: Double
get() = property.get()
set(value) = property.set(value)
fun valueProperty() = property
override fun write(bundle: Bundle) {
bundle.put("value", value)
}
override fun read(bundle: Bundle) {
value = bundle.get("value")
}
override fun toString() = "${javaClass.simpleName.substringBefore("Component")}($value)"
}
/**
* Represents a String value based component.
*/
abstract class StringComponent
@JvmOverloads constructor(initialValue: String = "") : Component(), SerializableComponent {
private val property: StringProperty = SimpleStringProperty(initialValue)
var value: String
get() = property.get()
set(value) = property.set(value)
fun valueProperty() = property
override fun write(bundle: Bundle) {
bundle.put("value", value)
}
override fun read(bundle: Bundle) {
value = bundle.get("value")
}
override fun toString() = "${javaClass.simpleName.substringBefore("Component")}($value)"
}
/**
* Represents an Object value based component.
*/
abstract class ObjectComponent<T>(initialValue: T) : Component() {
private val property: ObjectProperty<T> = SimpleObjectProperty(initialValue)
var value: T
get() = property.get()
set(value) = property.set(value)
fun valueProperty() = property
override fun toString() = "${javaClass.simpleName.substringBefore("Component")}($value)"
}
| mit |
RP-Kit/RPKit | bukkit/rpk-player-lib-bukkit/src/main/kotlin/com/rpkit/players/bukkit/profile/minecraft/RPKMinecraftProfile.kt | 1 | 1319 | /*
* Copyright 2021 Ren Binden
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.players.bukkit.profile.minecraft
import com.rpkit.core.bukkit.command.sender.RPKBukkitCommandSender
import com.rpkit.players.bukkit.profile.RPKThinProfile
import net.md_5.bungee.api.chat.BaseComponent
import java.util.UUID
interface RPKMinecraftProfile : RPKBukkitCommandSender {
var id: RPKMinecraftProfileId?
var profile: RPKThinProfile
val minecraftUUID: UUID
val minecraftUsername: RPKMinecraftUsername
override val name: String
val isOnline: Boolean
override fun sendMessage(message: String)
override fun sendMessage(messages: Array<String>)
override fun sendMessage(vararg components: BaseComponent)
override fun hasPermission(permission: String): Boolean
} | apache-2.0 |
AsynkronIT/protoactor-kotlin | examples/src/main/kotlin/actor/proto/examples/spawnbenchmark/SpawnBenchmark.kt | 1 | 2654 | package actor.proto.examples.spawnbenchmark
import actor.proto.Actor
import actor.proto.Context
import actor.proto.PID
import actor.proto.Props
import actor.proto.fromFunc
import actor.proto.fromProducer
import actor.proto.send
import actor.proto.spawn
import actor.proto.stop
import java.util.concurrent.CountDownLatch
fun main(args: Array<String>) {
repeat(10) {
runOnce()
}
readLine()
}
private fun runOnce() {
val (cd, managerPid: PID) = spawnManager()
send(managerPid, Begin)
cd.await()
System.gc()
System.runFinalization()
}
private fun spawnManager(): Pair<CountDownLatch, PID> {
var start: Long = 0
val cd = CountDownLatch(1)
val managerProps = fromFunc { msg ->
when (msg) {
is Begin -> {
val root = spawn(SpawnActor.props)
start = System.currentTimeMillis()
send(root, Request(10, 0, 1_000_000, self))
}
is Long -> {
val millis = System.currentTimeMillis() - start
println("Elapsed $millis")
println("Result $msg")
cd.countDown()
}
}
}
val managerPid: PID = spawn(managerProps)
return Pair(cd, managerPid)
}
object Begin
data class Request(val div: Long, val num: Long, val size: Long, val respondTo: PID)
class SpawnActor : Actor {
companion object Foo {
private fun produce() = SpawnActor()
val props: Props = fromProducer(SpawnActor.Foo::produce)
}
private var replies: Long = 0
private lateinit var replyTo: PID
private var sum: Long = 0
override suspend fun Context.receive(msg: Any) {
when (msg) {
is Request -> when {
msg.size == 1L -> {
send(msg.respondTo, msg.num)
stop(self)
}
else -> {
replies = msg.div
replyTo = msg.respondTo
for (i in 0 until msg.div) {
val child: PID = spawn(props)
val s = msg.size / msg.div
send(
child, Request(
msg.div,
msg.num + i * s,
s,
self
)
)
}
}
}
is Long -> {
sum += msg
replies--
if (replies == 0L) send(replyTo, sum)
}
}
}
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.