content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.android.devtools
import arcs.android.devtools.DevToolsMessage.Companion.RAW_MESSAGE
import arcs.core.util.JsonValue
/**
* An implementation of [DevToolsMessage] to pass raw [ProxyMessage]s.
*/
class RawDevToolsMessage(override val message: JsonValue.JsonString) : DevToolsMessage {
override val kind: String = RAW_MESSAGE
}
| java/arcs/android/devtools/RawDevToolsMessage.kt | 1540682563 |
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.handler
import com.maddyhome.idea.vim.action.change.VimRepeater
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.VimMotionGroupBase
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.Command
import com.maddyhome.idea.vim.command.CommandFlags
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.command.SelectionType
import com.maddyhome.idea.vim.diagnostic.debug
import com.maddyhome.idea.vim.diagnostic.vimLogger
import com.maddyhome.idea.vim.group.visual.VimBlockSelection
import com.maddyhome.idea.vim.group.visual.VimSelection
import com.maddyhome.idea.vim.group.visual.VimSimpleSelection
import com.maddyhome.idea.vim.group.visual.VisualChange
import com.maddyhome.idea.vim.group.visual.VisualOperation
import com.maddyhome.idea.vim.helper.exitVisualMode
import com.maddyhome.idea.vim.helper.inBlockSubMode
import com.maddyhome.idea.vim.helper.inRepeatMode
import com.maddyhome.idea.vim.helper.inVisualMode
import com.maddyhome.idea.vim.helper.vimStateMachine
/**
* @author Alex Plate
*
* Base class for visual operation handlers.
*
* Use subclasses of this handler:
* - [VisualOperatorActionHandler.SingleExecution]
* - [VisualOperatorActionHandler.ForEachCaret]
*/
sealed class VisualOperatorActionHandler : EditorActionHandlerBase(false) {
/**
* Base class for visual operation handlers.
* This handler executes an action for each caret. That means that if you have 5 carets,
* [executeAction] will be called 5 times.
* @see [VisualOperatorActionHandler.SingleExecution] for only one execution.
*/
abstract class ForEachCaret : VisualOperatorActionHandler() {
/**
* Execute an action for current [caret].
* The selection offsets and type should be takes from [range] because this [caret] doesn't have this selection
* anymore in time of action execution (and editor is in normal mode, not visual).
*
* This method is executed once for each caret except case with block selection. If there is block selection,
* the method will be executed only once with [Caret#primaryCaret].
*/
abstract fun executeAction(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
cmd: Command,
range: VimSelection,
operatorArguments: OperatorArguments,
): Boolean
/**
* This method executes before [executeAction] and only once for all carets.
* [caretsAndSelections] contains a map of all current carets and corresponding selections.
* If there is block selection, only one caret is in [caretsAndSelections].
*/
open fun beforeExecution(
editor: VimEditor,
context: ExecutionContext,
cmd: Command,
caretsAndSelections: Map<VimCaret, VimSelection>,
) = true
/**
* This method executes after [executeAction] and only once for all carets.
* [res] has true if ALL executions of [executeAction] returned true.
*/
open fun afterExecution(editor: VimEditor, context: ExecutionContext, cmd: Command, res: Boolean) {}
}
/**
* Base class for visual operation handlers.
* This handler executes an action only once for all carets. That means that if you have 5 carets,
* [executeForAllCarets] will be called 1 time.
* @see [VisualOperatorActionHandler.ForEachCaret] for per-caret execution
*/
abstract class SingleExecution : VisualOperatorActionHandler() {
/**
* Execute an action
* [caretsAndSelections] contains a map of all current carets and corresponding selections.
* If there is block selection, only one caret is in [caretsAndSelections].
*
* This method is executed once for all carets.
*/
abstract fun executeForAllCarets(
editor: VimEditor,
context: ExecutionContext,
cmd: Command,
caretsAndSelections: Map<VimCaret, VimSelection>,
operatorArguments: OperatorArguments,
): Boolean
}
final override fun baseExecute(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
cmd: Command,
operatorArguments: OperatorArguments
): Boolean {
logger.info("Execute visual command $cmd")
editor.vimChangeActionSwitchMode = null
val selections = editor.collectSelections() ?: return false
logger.debug { "Count of selection segments: ${selections.size}" }
logger.debug { selections.values.joinToString("\n") { vimSelection -> "Caret: $vimSelection" } }
val commandWrapper = VisualStartFinishWrapper(editor, cmd, this)
commandWrapper.start()
val res = arrayOf(true)
when (this) {
is SingleExecution -> {
res[0] = executeForAllCarets(editor, context, cmd, selections, operatorArguments)
}
is ForEachCaret -> {
logger.debug("Calling 'before execution'")
if (!beforeExecution(editor, context, cmd, selections)) {
logger.debug("Before execution block returned false. Stop further processing")
return false
}
when {
selections.keys.isEmpty() -> return false
selections.keys.size == 1 -> res[0] =
executeAction(
editor,
selections.keys.first(),
context,
cmd,
selections.values.first(),
operatorArguments
)
else -> editor.forEachNativeCaret(
{ currentCaret ->
val range = selections.getValue(currentCaret)
val loopRes = executeAction(editor, currentCaret, context, cmd, range, operatorArguments)
res[0] = loopRes and res[0]
},
true
)
}
logger.debug("Calling 'after execution'")
afterExecution(editor, context, cmd, res[0])
}
}
commandWrapper.finish(res[0])
editor.vimChangeActionSwitchMode?.let {
injector.changeGroup.processPostChangeModeSwitch(editor, context, it)
}
return res[0]
}
private fun VimEditor.collectSelections(): Map<VimCaret, VimSelection>? {
return when {
!this.inVisualMode && this.inRepeatMode -> {
if (this.vimLastSelectionType == SelectionType.BLOCK_WISE) {
val primaryCaret = primaryCaret()
val range = primaryCaret.vimLastVisualOperatorRange ?: return null
val end = VisualOperation.calculateRange(this, range, 1, primaryCaret)
mapOf(
primaryCaret to VimBlockSelection(
primaryCaret.offset.point,
end,
this, range.columns >= VimMotionGroupBase.LAST_COLUMN
)
)
} else {
val carets = mutableMapOf<VimCaret, VimSelection>()
this.nativeCarets().forEach { caret ->
val range = caret.vimLastVisualOperatorRange ?: return@forEach
val end = VisualOperation.calculateRange(this, range, 1, caret)
carets += caret to VimSelection.create(caret.offset.point, end, range.type, this)
}
carets.toMap()
}
}
this.inBlockSubMode -> {
val primaryCaret = primaryCaret()
mapOf(
primaryCaret to VimBlockSelection(
primaryCaret.vimSelectionStart,
primaryCaret.offset.point,
this, primaryCaret.vimLastColumn >= VimMotionGroupBase.LAST_COLUMN
)
)
}
else -> this.nativeCarets().associateWith { caret ->
val subMode = this.vimStateMachine.subMode
VimSimpleSelection.createWithNative(
caret.vimSelectionStart,
caret.offset.point,
caret.selectionStart,
caret.selectionEnd,
SelectionType.fromSubMode(subMode),
this
)
}
}
}
private class VisualStartFinishWrapper(
private val editor: VimEditor,
private val cmd: Command,
private val visualOperatorActionHandler: VisualOperatorActionHandler
) {
private val visualChanges = mutableMapOf<VimCaret, VisualChange?>()
fun start() {
logger.debug("Preparing visual command")
editor.vimKeepingVisualOperatorAction = CommandFlags.FLAG_EXIT_VISUAL !in cmd.flags
editor.forEachCaret {
val change =
if ([email protected] && [email protected]) {
VisualOperation.getRange([email protected], it, [email protected])
} else null
[email protected][it] = change
}
logger.debug { visualChanges.values.joinToString("\n") { "Caret: $visualChanges" } }
// If this is a mutli key change then exit visual now
if (CommandFlags.FLAG_MULTIKEY_UNDO in cmd.flags || CommandFlags.FLAG_EXIT_VISUAL in cmd.flags) {
logger.debug("Exit visual before command executing")
editor.exitVisualMode()
}
}
fun finish(res: Boolean) {
logger.debug("Finish visual command. Result: $res")
if (visualOperatorActionHandler.id != "VimVisualOperatorAction" ||
injector.keyGroup.operatorFunction?.postProcessSelection() != false
) {
if (CommandFlags.FLAG_MULTIKEY_UNDO !in cmd.flags && CommandFlags.FLAG_EXPECT_MORE !in cmd.flags) {
logger.debug("Not multikey undo - exit visual")
editor.exitVisualMode()
}
}
if (res) {
VimRepeater.saveLastChange(cmd)
VimRepeater.repeatHandler = false
editor.forEachCaret { caret ->
val visualChange = visualChanges[caret]
if (visualChange != null) {
caret.vimLastVisualOperatorRange = visualChange
}
}
}
editor.vimKeepingVisualOperatorAction = false
}
}
private companion object {
val logger = vimLogger<VisualOperatorActionHandler>()
}
}
| vim-engine/src/main/kotlin/com/maddyhome/idea/vim/handler/VisualOperatorActionHandler.kt | 1941582609 |
package org.ligi.passandroid.reader
import org.json.JSONObject
fun JSONObject.getBarcodeJson(): JSONObject? {
if (has("barcode")) {
return getJSONObject("barcode")
}
if (has("barcodes")) {
getJSONArray("barcodes").let {
if (length() > 0) {
return it.getJSONObject(0)
}
}
}
return null
}
| android/src/main/java/org/ligi/passandroid/reader/AppleStylePassReaderFunctions.kt | 1843538553 |
package org.ligi.passandroid.ui
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import kotlinx.android.synthetic.main.fullscreen_image.*
import org.ligi.kaxt.lockOrientation
import org.ligi.passandroid.R
import timber.log.Timber
class FullscreenBarcodeActivity : PassViewActivityBase() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.fullscreen_image)
if (Build.VERSION.SDK_INT >= 27) {
setShowWhenLocked(true)
setTurnScreenOn(true)
} else {
this.window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED)
}
}
override fun onResume() {
super.onResume()
if (currentPass.barCode == null) {
Timber.w("FullscreenBarcodeActivity in bad state")
finish() // this should never happen, but better safe than sorry
return
}
setBestFittingOrientationForBarCode()
fullscreen_barcode.setImageDrawable(currentPass.barCode!!.getBitmap(resources))
if (currentPass.barCode!!.alternativeText != null) {
alternativeBarcodeText.visibility = View.VISIBLE
alternativeBarcodeText.text = currentPass.barCode!!.alternativeText
} else {
alternativeBarcodeText.visibility = View.GONE
}
}
/**
* QR and AZTEC are best fit in Portrait
* PDF417 is best viewed in Landscape
*
*
* main work is to avoid changing if we are already optimal
* ( reverse orientation / sensor is the problem here ..)
*/
private fun setBestFittingOrientationForBarCode() {
if (currentPass.barCode!!.format!!.isQuadratic()) {
when (requestedOrientation) {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT,
ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT,
ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT -> return // do nothing
else -> lockOrientation(Configuration.ORIENTATION_PORTRAIT)
}
} else {
when (requestedOrientation) {
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE,
ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE,
ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE -> return // do nothing
else -> lockOrientation(Configuration.ORIENTATION_LANDSCAPE)
}
}
}
}
| android/src/main/java/org/ligi/passandroid/ui/FullscreenBarcodeActivity.kt | 1383371779 |
@file:Suppress("DEPRECATION")
package org.wordpress.android.util.image.getters
import android.annotation.SuppressLint
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.PixelFormat
import android.graphics.Rect
import android.graphics.drawable.Animatable
import android.graphics.drawable.Drawable
import android.widget.TextView
import com.bumptech.glide.request.Request
import com.bumptech.glide.request.target.SizeReadyCallback
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.target.ViewTarget
import com.bumptech.glide.request.transition.Transition
import org.wordpress.android.ui.WPTextViewDrawableCallback
import org.wordpress.android.util.ImageUtils
/**
* A class that we can load a remote resource into. Automatically displays placeholder while the remote img is
* loading and displays an error image if the loading fails.
*
* We could probably subclass BaseTarget instead of ViewTarget, since we basically override most of its functionality.
* However, we might want to use ViewTarget.clearOnDetach(..) when it becomes stable (it's experimental now).
* It clears the View's Request when the View is detached from its Window and restarts the Request when the View is
* re-attached from its Window.
*/
@Suppress("DEPRECATION")
internal class WPRemoteResourceViewTarget(
view: TextView,
private val maxSize: Int
) : ViewTarget<TextView, Drawable>(view) {
private val drawableWrapper = RemoteDrawableWrapper()
private var request: Request? = null
val drawable: Drawable get() = drawableWrapper
override fun onResourceReady(res: Drawable, transition: Transition<in Drawable>?) {
if (res is Animatable) {
// Bind a Callback object to this Drawable. Required for clients that want to support
// animated drawables.
res.callback = WPTextViewDrawableCallback(getView())
(res as Animatable).start()
}
replaceDrawable(res, ImageUtils.getScaledBounds(res.intrinsicWidth, res.intrinsicHeight, maxSize))
}
override fun onLoadFailed(errorDrawable: Drawable?) {
errorDrawable?.let {
replaceDrawable(it, Rect(0, 0, it.intrinsicWidth, it.intrinsicHeight))
}
}
override fun onLoadStarted(res: Drawable?) {
super.onLoadStarted(res)
res?.let {
replaceDrawable(it, Rect(0, 0, it.intrinsicWidth, it.intrinsicHeight))
}
}
private fun replaceDrawable(drawable: Drawable, bounds: Rect) {
drawableWrapper.setDrawable(drawable)
drawableWrapper.bounds = bounds
// force textView to resize correctly by resetting the content to itself
getView().text = getView().text
}
/**
* Since this target can be used for loading multiple images into a single TextView, we can't use the default
* implementation which supports only one request per view. On the other hand, by using field to store the request
* we lose the ability to clear previous requests if the client creates new instance of the
* WPRemoteResourceViewTarget for the new request on the same view. Canceling any previous requests for the same
* View must be handled by the client (see WPCustomImageGetter.clear(..) methods for reference).
*/
override fun getRequest(): Request? {
return request
}
override fun setRequest(request: Request?) {
this.request = request
}
/**
* We don't want to call super, since it determines the size from the size of the View. But this target may be used
* for loading multiple images into a single View.
*/
@SuppressLint("MissingSuperCall")
override fun getSize(cb: SizeReadyCallback) {
cb.onSizeReady(maxSize, Target.SIZE_ORIGINAL)
}
/**
* Drawable wrapper so we can replace placeholder with remote/error resource, after the requests finishes.
*
* We need to synchronously return drawable in WPCustomImageGetter.getDrawable(...).
* If we return regular drawable - let's say a placeholder, we won't be able to replace it with the actual image
* ==> This wrapper just adds us ability to change the content of the drawable after the asynchronous call finishes.
*/
private class RemoteDrawableWrapper : Drawable() {
internal var drawable: Drawable? = null
fun setDrawable(drawable: Drawable) {
this.drawable = drawable
}
override fun draw(canvas: Canvas) {
drawable?.draw(canvas)
}
override fun setAlpha(alpha: Int) {
drawable?.alpha = alpha
}
override fun setColorFilter(colorFilter: ColorFilter?) {
drawable?.colorFilter = colorFilter
}
@Suppress("DEPRECATION")
override fun getOpacity(): Int {
return drawable?.opacity ?: PixelFormat.UNKNOWN
}
override fun setBounds(bounds: Rect) {
super.setBounds(bounds)
drawable?.bounds = bounds
}
}
}
| WordPress/src/main/java/org/wordpress/android/util/image/getters/WPRemoteResourceViewTarget.kt | 1459106022 |
package com.linxuedesign.handyman
/**
* Created by Brandon Elam Barker on 4/5/2015.
*/
import kotlin.js.dom.html.document
fun main(args: Array<String>) {
val el = document.createElement("div")
el.appendChild(document.createTextNode("Hello!"))
document.body.appendChild(el)
document.getElementById("email").setAttribute(
"value", "[email protected]"
)
} | src/main/kotlin/main.kt | 2377354998 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.toml.lang.parse
import com.intellij.lang.PsiBuilder
import com.intellij.lang.parser.GeneratedParserUtilBase
import com.intellij.psi.TokenType
import com.intellij.psi.tree.IElementType
object TomlParserUtil : GeneratedParserUtilBase() {
@Suppress("UNUSED_PARAMETER")
@JvmStatic
fun remap(b: PsiBuilder, level: Int, from: IElementType, to: IElementType): Boolean {
if (b.tokenType == from) {
b.remapCurrentToken(to)
b.advanceLexer()
return true
}
return false
}
@Suppress("UNUSED_PARAMETER")
@JvmStatic
fun any(b: PsiBuilder, level: Int): Boolean = true
@JvmStatic
fun atSameLine(b: PsiBuilder, level: Int, parser: Parser): Boolean {
val marker = enter_section_(b)
b.eof() // skip whitespace
val isSameLine = !isNextAfterNewLine(b)
if (!isSameLine) addVariant(b, "VALUE")
val result = isSameLine && parser.parse(b, level)
exit_section_(b, marker, null, result)
return result
}
@JvmStatic
fun atNewLine(b: PsiBuilder, level: Int, parser: Parser): Boolean {
val marker = enter_section_(b)
b.eof() // skip whitespace
val result = isNextAfterNewLine(b) && parser.parse(b, level)
exit_section_(b, marker, null, result)
return result
}
}
private fun isNextAfterNewLine(b: PsiBuilder): Boolean {
val prevToken = b.rawLookup(-1)
return prevToken == null || prevToken == TokenType.WHITE_SPACE && b.rawLookupText(-1).contains("\n")
}
/** Similar to [com.intellij.lang.PsiBuilderUtil.rawTokenText] */
private fun PsiBuilder.rawLookupText(steps: Int): CharSequence {
val start = rawTokenTypeStart(steps)
val end = rawTokenTypeStart(steps + 1)
return if (start == -1 || end == -1) "" else originalText.subSequence(start, end)
}
| plugins/toml/core/src/main/kotlin/org/toml/lang/parse/TomlParserUtil.kt | 1812486980 |
package foo.bar.baz
annotation class Ann1
annotation class Ann2
annotation class Ann3
@foo.bar.baz.Ann1
@foo.bar.baz.Ann2
fun test<caret>() {}
// ANNOTATION: foo/bar/baz/Ann1, foo/bar/baz/Ann2 | plugins/kotlin/base/fir/analysis-api-providers/testData/annotationsResolver/same_package_fqname.kt | 3769230970 |
package com.kelsos.mbrc.ui.navigation.nowplaying
import android.content.Context
import android.view.GestureDetector
import android.view.MotionEvent
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnItemTouchListener
import timber.log.Timber
class NowPlayingTouchListener(context: Context, private val onLongClick: (Boolean) -> Unit) :
OnItemTouchListener {
private val gestureDetector: GestureDetector
init {
gestureDetector = GestureDetector(context,
object : GestureDetector.SimpleOnGestureListener() {
override fun onLongPress(e: MotionEvent?) {
Timber.v("Marking start of long press event")
onLongClick.invoke(true)
super.onLongPress(e)
}
})
}
override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {
}
override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
gestureDetector.onTouchEvent(e)
val action = e.actionMasked
if (action == MotionEvent.ACTION_UP) {
Timber.v("Marking end of long press event")
onLongClick.invoke(false)
}
return false
}
override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
}
}
| app/src/main/kotlin/com/kelsos/mbrc/ui/navigation/nowplaying/NowPlayingTouchListener.kt | 665017710 |
// AFTER-WARNING: Parameter 'x' is never used
// AFTER-WARNING: Parameter 'y' is never used
// AFTER-WARNING: Parameter 'z' is never used
fun test(b: Boolean) {
<caret>if (b) println(1, 2, 3) else println(x = 1, y = 4, z = 3)
}
fun println(x: Int, y: Int, z: Int) {} | plugins/kotlin/idea/tests/testData/intentions/branched/folding/ifToFunctionCall/multiArguments3.kt | 478943837 |
package com.darkoverlordofdata.entitas.demo.systems
/**
* Entitas Generated Systems for com.darkoverlordofdata.entitas.demo
*
*/
import com.darkoverlordofdata.entitas.ISetPool
import com.darkoverlordofdata.entitas.IExecuteSystem
import com.darkoverlordofdata.entitas.IInitializeSystem
import com.darkoverlordofdata.entitas.IReactiveExecuteSystem
import com.darkoverlordofdata.entitas.IMultiReactiveSystem
import com.darkoverlordofdata.entitas.IReactiveSystem
import com.darkoverlordofdata.entitas.IEnsureComponents
import com.darkoverlordofdata.entitas.IExcludeComponents
import com.darkoverlordofdata.entitas.IClearReactiveSystem
import com.darkoverlordofdata.entitas.Pool
class SoundEffectSystem()
: ", I, I, n, i, t, i, a, l, i, z, e, S, y, s, t, e, m, ", ,, , ", I, E, x, e, c, u, t, e, S, y, s, t, e, m, ", ,, , ", I, S, e, t, P, o, o, l, " {
} | lib/src/systems/SoundEffectSystem.kt | 647431316 |
/*
* CardKeys.kt
*
* Copyright (C) 2012 Eric Butler
*
* Authors:
* Eric Butler <[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 au.id.micolous.metrodroid.key
import android.content.Context
import android.content.res.AssetManager
import java.lang.Exception
class CardKeysFileReaderEmbed(private val context: Context,
private val baseDir: String) : CardKeysFileReader {
override fun readFile(fileName: String): String? = try {
context.assets.open("$baseDir/$fileName",
AssetManager.ACCESS_RANDOM).reader(Charsets.UTF_8).readText()
} catch (e: Exception) {
null
}
override fun listFiles(dir: String) = context.assets.list("$baseDir/$dir")?.toList()
}
fun CardKeysEmbed(context: Context, baseDir: String) = CardKeysFromFiles(CardKeysFileReaderEmbed(context, baseDir))
| src/main/java/au/id/micolous/metrodroid/key/CardKeysEmbed.kt | 436276100 |
package com.an.deviceinfo.ads
import android.content.Context
import java.io.IOException
class AdInfo(private val context: Context) {
//Send Data to callback
val ad: Ad
@Throws(Exception::class)
get() {
val adInfo = AdvertisingIdClient.getAdvertisingIdInfo(context)
val advertisingId = adInfo.id
val adDoNotTrack = adInfo.isLimitAdTrackingEnabled
val ad = Ad()
ad.isAdDoNotTrack = adDoNotTrack
ad.advertisingId = advertisingId
return ad
}
fun getAndroidAdId(callback: AdIdCallback) {
Thread(Runnable {
try {
val ad = ad
callback.onResponse(context, ad)
} catch (e: Exception) {
e.printStackTrace()
}
}).start()
}
interface AdIdCallback {
fun onResponse(context: Context, ad: Ad)
}
}
| deviceinfo/src/main/java/com/an/deviceinfo/ads/AdInfo.kt | 3936000731 |
/*
* Copyright (C) 2019. Zac Sweers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.sweers.catchup.service.reddit.model
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class RedditResponse(val data: RedditListing)
| services/reddit/src/main/kotlin/io/sweers/catchup/service/reddit/model/RedditResponse.kt | 1358820186 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic
import com.intellij.openapi.extensions.PluginId
interface FeaturedPluginsInfoProvider {
/**
* Returns a list of pre-defined featured plugins suggested in IDE customization wizard.
* All plugins returned from this method has to be available on public Marketplace.
*/
fun getFeaturedPluginsFromMarketplace(): Set<PluginId>
} | platform/statistics/src/com/intellij/internal/statistic/FeaturedPluginsInfoProvider.kt | 668021571 |
// 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.workspaceModel.storage
import com.intellij.testFramework.UsefulTestCase.assertOneElement
import com.intellij.workspaceModel.storage.entities.test.api.*
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.assertConsistency
import junit.framework.TestCase
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import kotlin.test.assertNotNull
import kotlin.test.assertNull
class AbstractEntitiesTest {
@Test
fun `simple adding`() {
val builder = MutableEntityStorage.create()
val middleEntity = builder.addMiddleEntity()
builder.addLeftEntity(sequenceOf(middleEntity))
val storage = builder.toSnapshot()
val leftEntity = assertOneElement(storage.entities(LeftEntity::class.java).toList())
assertOneElement(leftEntity.children.toList())
}
@Test
fun `modifying left entity`() {
val builder = MutableEntityStorage.create()
val middleEntity = builder.addMiddleEntity("first")
val leftEntity = builder.addLeftEntity(sequenceOf(middleEntity))
val anotherMiddleEntity = builder.addMiddleEntity("second")
builder.modifyEntity(leftEntity) {
}
builder.modifyEntity(leftEntity) {
this.children = listOf(anotherMiddleEntity)
}
val storage = builder.toSnapshot()
val actualLeftEntity = assertOneElement(storage.entities(LeftEntity::class.java).toList())
val actualChild = assertOneElement(actualLeftEntity.children.toList())
assertEquals(anotherMiddleEntity, actualChild)
assertEquals(anotherMiddleEntity.property, (actualChild as MiddleEntity).property)
}
@Test
fun `modifying abstract entity`() {
val builder = MutableEntityStorage.create()
val middleEntity = builder.addMiddleEntity()
val leftEntity = builder.addLeftEntity(sequenceOf(middleEntity))
val anotherMiddleEntity = builder.addMiddleEntity()
builder.modifyEntity(leftEntity) {
this.children = listOf(anotherMiddleEntity)
}
val storage = builder.toSnapshot()
val actualLeftEntity = assertOneElement(storage.entities(LeftEntity::class.java).toList())
val actualChild = assertOneElement(actualLeftEntity.children.toList())
assertEquals(anotherMiddleEntity, actualChild)
assertEquals(anotherMiddleEntity.property, (actualChild as MiddleEntity).property)
}
@Test
fun `children replace in addDiff`() {
val builder = MutableEntityStorage.create()
val middleEntity = builder.addMiddleEntity()
val leftEntity = builder.addLeftEntity(sequenceOf(middleEntity))
val anotherBuilder = MutableEntityStorage.from(builder)
val anotherMiddleEntity = anotherBuilder.addMiddleEntity("Another")
anotherBuilder.modifyEntity(leftEntity.from(anotherBuilder)) {
this.children = listOf(middleEntity, anotherMiddleEntity)
}
val initialMiddleEntity = builder.addMiddleEntity("Initial")
builder.modifyEntity(leftEntity) {
this.children = listOf(middleEntity, initialMiddleEntity)
}
builder.addDiff(anotherBuilder)
val actualLeftEntity = assertOneElement(builder.entities(LeftEntity::class.java).toList())
val children = actualLeftEntity.children.toList() as List<MiddleEntity>
assertEquals(2, children.size)
assertTrue(children.any { it.property == "Another" })
assertTrue(children.none { it.property == "Initial" })
}
@Test
fun `keep children ordering when making storage`() {
val builder = MutableEntityStorage.create()
val middleEntity1 = builder.addMiddleEntity("One")
val middleEntity2 = builder.addMiddleEntity("Two")
builder.addLeftEntity(sequenceOf(middleEntity1, middleEntity2))
val storage = builder.toSnapshot()
val children = storage.entities(LeftEntity::class.java).single().children.toList()
assertEquals(middleEntity1, children[0])
assertEquals(middleEntity2, children[1])
}
@Test
fun `keep children ordering when making storage 2`() {
val builder = MutableEntityStorage.create()
val middleEntity1 = builder.addMiddleEntity("Two")
val middleEntity2 = builder.addMiddleEntity("One")
builder.addLeftEntity(sequenceOf(middleEntity1, middleEntity2))
val anotherBuilder = makeBuilder(builder) {
addLeftEntity(sequenceOf(middleEntity2, middleEntity1))
}
builder.addDiff(anotherBuilder)
val storage = builder.toSnapshot()
val children = storage.entities(LeftEntity::class.java).last().children.toList()
assertEquals(middleEntity2, children[0])
assertEquals(middleEntity1, children[1])
}
@Test
fun `keep children ordering after rbs 1`() {
val builder = MutableEntityStorage.create()
val middleEntity1 = builder.addMiddleEntity("One")
val middleEntity2 = builder.addMiddleEntity("Two")
builder.addLeftEntity(sequenceOf(middleEntity1, middleEntity2))
val target = MutableEntityStorage.create()
target.replaceBySource({ true }, builder)
val children = target.toSnapshot().entities(LeftEntity::class.java).last().children.toList()
assertEquals(middleEntity1.property, (children[0] as MiddleEntity).property)
assertEquals(middleEntity2.property, (children[1] as MiddleEntity).property)
}
@Test
fun `keep children ordering after rbs 2`() {
val builder = MutableEntityStorage.create()
val middleEntity1 = builder.addMiddleEntity("One")
val middleEntity2 = builder.addMiddleEntity("Two")
builder.addLeftEntity(sequenceOf(middleEntity2, middleEntity1))
val target = MutableEntityStorage.create()
target.replaceBySource({ true }, builder)
val children = target.toSnapshot().entities(LeftEntity::class.java).last().children.toList()
assertEquals(middleEntity2.property, (children[0] as MiddleEntity).property)
assertEquals(middleEntity1.property, (children[1] as MiddleEntity).property)
}
@Test
fun `modifying one to one child switch`() {
val builder = MutableEntityStorage.create()
val headAbstractionEntity = HeadAbstractionEntity("info", MySource)
builder.addEntity(headAbstractionEntity)
builder.addEntity(LeftEntity(AnotherSource) {
this.parent = headAbstractionEntity
})
builder.addEntity(LeftEntity(MySource) {
this.parent = headAbstractionEntity
})
builder.assertConsistency()
assertNull(builder.entities(LeftEntity::class.java).single { it.entitySource == AnotherSource }.parent)
assertNotNull(builder.entities(LeftEntity::class.java).single { it.entitySource == MySource }.parent)
}
@Test
fun `modifying one to one parent switch`() {
val builder = MutableEntityStorage.create()
val child = builder addEntity LeftEntity(AnotherSource)
builder addEntity HeadAbstractionEntity("Info", MySource) {
this.child = child
}
builder addEntity HeadAbstractionEntity("Info2", MySource) {
this.child = child
}
builder.assertConsistency()
assertNull(builder.entities(HeadAbstractionEntity::class.java).single { it.data == "Info" }.child)
assertNotNull(builder.entities(HeadAbstractionEntity::class.java).single { it.data == "Info2" }.child)
}
@Test
fun `entity changes visible in mutable storage`() {
var builder = MutableEntityStorage.create()
val entity = ParentNullableEntity("ParentData", MySource)
builder.addEntity(entity)
builder = MutableEntityStorage.from(builder.toSnapshot())
val resultEntity = builder.entities(ParentNullableEntity::class.java).single()
resultEntity.parentData
var firstEntityData = (entity as ModifiableWorkspaceEntityBase<*, *>).getEntityData()
var secondEntityData = (resultEntity as ModifiableWorkspaceEntityBase<*, *>).getEntityData()
TestCase.assertSame(firstEntityData, secondEntityData)
val originalEntityData = firstEntityData
builder.modifyEntity(resultEntity) {
this.parentData = "NewParentData"
}
val anotherResult = builder.entities(ParentNullableEntity::class.java).single()
TestCase.assertEquals(resultEntity.parentData, anotherResult.parentData)
firstEntityData = (resultEntity as ModifiableWorkspaceEntityBase<*, *>).getEntityData()
secondEntityData = (anotherResult as ModifiableWorkspaceEntityBase<*, *>).getEntityData()
TestCase.assertSame(firstEntityData, secondEntityData)
TestCase.assertNotSame(firstEntityData, originalEntityData)
builder.modifyEntity(anotherResult) {
this.parentData = "AnotherParentData"
}
val oneMoreResult = builder.entities(ParentNullableEntity::class.java).single()
TestCase.assertEquals(resultEntity.parentData, anotherResult.parentData)
TestCase.assertEquals(oneMoreResult.parentData, anotherResult.parentData)
TestCase.assertEquals(oneMoreResult.parentData, resultEntity.parentData)
}
}
| platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/AbstractEntitiesTest.kt | 1737901020 |
class A {
private val a = B()
private class <caret>B {
private val c = C()
}
private class C()
} | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveNestedClass/privateClass/before/main.kt | 2023900854 |
// 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.openapi.vcs.impl.projectlevelman
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.vcs.VcsRootChecker
import com.intellij.openapi.vfs.VirtualFile
internal object VcsDefaultMappingUtils {
/**
* Provides VCS roots where [projectRoots] are located using [rootChecker].
*
* [mappedDirs] are took into account during detection, so that direct mappings shouldn't be overwritten by <Project> mappings.
* E.g. if directory `/project` has direct mapping for Hg and there is `/project/.git` folder
* (that is going to be detected as <Project> mapping),
* `/project` shouldn't be returned as <Project> mapping. It should stay as Hg direct mapping.
* So, already mapped files and directories from [mappedDirs] are excluded from the result.
*
* NB: if [rootChecker]'s [com.intellij.openapi.vcs.VcsRootChecker.areChildrenValidMappings]
* is true then a result may contain directories under [project] but not "pure" VCS roots.
* Example: for `root/svn_root_dir/project_root_dir` if `svn_root_dir` is not under project
* `project_dir` will be returned as VCS root, not `svn_root_dir`.
* It is needed to detect changes only under `project_root_dir`, not under `svn_root_dir/unrelated_project`
*
* @param projectRoots files and directories that are a part of the [project]
* @param mappedDirs directories that were already mapped with VCS
*/
@JvmStatic
fun detectProjectMappings(
project: Project,
rootChecker: VcsRootChecker,
projectRoots: Collection<VirtualFile>,
mappedDirs: Set<VirtualFile>
): Set<VirtualFile> {
return VcsDefaultMappingDetector(project, rootChecker).detectProjectMappings(projectRoots, mappedDirs)
}
}
private class VcsDefaultMappingDetector(
private val project: Project,
private val rootChecker: VcsRootChecker
) {
private val fileIndex = ProjectFileIndex.getInstance(project)
private val checkedDirs = mutableMapOf<VirtualFile, Boolean>()
fun detectProjectMappings(
projectRoots: Collection<VirtualFile>,
mappedDirs: Set<VirtualFile>
): Set<VirtualFile> {
for (dir in mappedDirs) {
checkedDirs[dir] = true
}
val vcsRoots = mutableSetOf<VirtualFile>()
for (projectRoot in projectRoots) {
val root = detectVcsForProjectRoot(projectRoot)
if (root != null) {
vcsRoots.add(root)
}
}
vcsRoots.removeAll(mappedDirs) // do not report known mappings
return vcsRoots
}
private fun detectVcsForProjectRoot(projectRoot: VirtualFile): VirtualFile? {
for (file in generateSequence(projectRoot) { it.parent }) {
if (isVcsRoot(file)) {
return file
}
val parent = file.parent
if (parent != null && !isUnderProject(parent)) {
if (rootChecker.areChildrenValidMappings() &&
isUnderVcsRoot(parent)) {
return file
}
else {
return null
}
}
}
return null
}
private fun isUnderVcsRoot(file: VirtualFile): Boolean {
return generateSequence(file) { it.parent }.any { isVcsRoot(it) }
}
private fun isVcsRoot(file: VirtualFile): Boolean {
ProgressManager.checkCanceled()
return checkedDirs.computeIfAbsent(file) { key -> rootChecker.isRoot(key) }
}
private fun isUnderProject(f: VirtualFile): Boolean {
return runReadAction {
if (project.isDisposed) {
throw ProcessCanceledException()
}
fileIndex.isInContent(f)
}
}
} | platform/vcs-impl/src/com/intellij/openapi/vcs/impl/projectlevelman/VcsDefaultMappingUtils.kt | 3681576106 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.tools.projectWizard.core.entity
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.tools.projectWizard.KotlinNewProjectWizardBundle
import org.jetbrains.kotlin.tools.projectWizard.core.Failure
import org.jetbrains.kotlin.tools.projectWizard.core.Reader
import org.jetbrains.kotlin.tools.projectWizard.core.UNIT_SUCCESS
import org.jetbrains.kotlin.tools.projectWizard.core.ValidationError
@JvmInline
value class SettingValidator<V>(val validate: Reader.(V) -> ValidationResult) {
infix fun and(other: SettingValidator<V>) = SettingValidator<V> { value ->
validate(value) and other.validate(this, value)
}
operator fun Reader.invoke(value: V) = validate(value)
}
fun <V> settingValidator(validator: Reader.(V) -> ValidationResult) =
SettingValidator(validator)
fun <V> inValidatorContext(validator: Reader.(V) -> SettingValidator<V>) =
SettingValidator<V> { value ->
validator(value).validate(this, value)
}
object StringValidators {
fun shouldNotBeBlank(name: String) = settingValidator { value: String ->
if (value.isBlank()) ValidationResult.ValidationError(
KotlinNewProjectWizardBundle.message("validation.should.not.be.blank", name.capitalize())
)
else ValidationResult.OK
}
fun shouldBeValidIdentifier(name: String, allowedExtraSymbols: Set<Char>) = settingValidator { value: String ->
if (value.any { char -> !char.isLetterOrDigit() && char !in allowedExtraSymbols }) {
val allowedExtraSymbolsStringified = allowedExtraSymbols
.takeIf { it.isNotEmpty() }
?.joinToString(separator = ", ") { char -> "'$char'" }
?.let { chars -> KotlinNewProjectWizardBundle.message("validation.identifier.additional.symbols", chars) }
.orEmpty()
ValidationResult.ValidationError(
KotlinNewProjectWizardBundle.message("validation.identifier", name.capitalize(), allowedExtraSymbolsStringified)
)
} else ValidationResult.OK
}
}
fun List<ValidationResult>.fold() = fold(ValidationResult.OK, ValidationResult::and)
sealed class ValidationResult {
abstract val isOk: Boolean
object OK : ValidationResult() {
override val isOk = true
}
data class ValidationError(val messages: List<@Nls String>, val target: Any? = null) : ValidationResult() {
constructor(@Nls message: String, target: Any? = null) : this(listOf(message), target)
override val isOk = false
}
infix fun and(other: ValidationResult) = when {
this is OK -> other
this is ValidationError && other is ValidationError -> ValidationError(messages + other.messages, target ?: other.target)
else -> this
}
companion object {
fun create(condition: Boolean, @Nls message: String) =
if (condition) OK else ValidationError(message)
inline fun create(condition: Boolean, message: () -> @Nls String) =
if (condition) OK else ValidationError(message())
}
}
fun <V> SettingValidator<V>.withTarget(target: Any) = SettingValidator<V> { value ->
this.validate(value).withTarget(target)
}
infix fun ValidationResult.isSpecificError(error: ValidationResult.ValidationError) =
this is ValidationResult.ValidationError && messages.firstOrNull() == error.messages.firstOrNull()
fun ValidationResult.withTarget(target: Any) = when (this) {
ValidationResult.OK -> this
is ValidationResult.ValidationError -> copy(target = target)
}
fun ValidationResult.withTargetIfNull(target: Any) = when (this) {
ValidationResult.OK -> this
is ValidationResult.ValidationError -> if (this.target == null) copy(target = target) else this
}
fun ValidationResult.toResult() = when (this) {
ValidationResult.OK -> UNIT_SUCCESS
is ValidationResult.ValidationError -> Failure(messages.map { ValidationError(it) })
}
interface Validatable<out V> {
val validator: SettingValidator<@UnsafeVariance V>
}
fun <V, Q : Validatable<Q>> Reader.validateList(list: List<Q>) = settingValidator<V> {
list.fold(ValidationResult.OK as ValidationResult) { result, value ->
result and value.validator.validate(this, value).withTarget(value)
}
}
| plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/entity/SettingValidator.kt | 1372422594 |
fun foo() {
val b = !(!<caret>true)
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/doubleNegation/parenthesized.kt | 2439246983 |
// 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.actions
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ex.ToolWindowManagerEx
import com.intellij.openapi.wm.impl.ToolWindowManagerImpl
import com.intellij.toolWindow.ToolWindowEventSource
internal class HideSideWindowsAction : AnAction(), DumbAware {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val toolWindowManager = ToolWindowManagerEx.getInstanceEx(project) as ToolWindowManagerImpl
val id = toolWindowManager.activeToolWindowId ?: toolWindowManager.lastActiveToolWindowId ?: return
val window = toolWindowManager.getToolWindow(id) ?: return
if (HideToolWindowAction.shouldBeHiddenByShortCut(window)) {
toolWindowManager.hideToolWindow(id = id, hideSide = true, source = ToolWindowEventSource.HideSideWindowsAction)
}
}
override fun update(event: AnActionEvent) {
val presentation = event.presentation
val project = event.project
if (project == null) {
presentation.isEnabled = false
return
}
val toolWindowManager = ToolWindowManager.getInstance(project)
if (toolWindowManager.activeToolWindowId == null) {
val window = toolWindowManager.getToolWindow(toolWindowManager.lastActiveToolWindowId ?: return)
presentation.isEnabled = window != null && HideToolWindowAction.shouldBeHiddenByShortCut(window)
}
else {
presentation.isEnabled = true
}
}
override fun getActionUpdateThread() = ActionUpdateThread.EDT
} | platform/platform-impl/src/com/intellij/ide/actions/HideSideWindowsAction.kt | 2257505371 |
package com.onyx.interactors.scanner.impl
import com.onyx.persistence.query.QueryCriteriaOperator
interface RangeScanner {
var isBetween:Boolean
var rangeFrom:Any?
var rangeTo:Any?
var fromOperator:QueryCriteriaOperator?
var toOperator:QueryCriteriaOperator?
} | onyx-database/src/main/kotlin/com/onyx/interactors/scanner/impl/RangeScanner.kt | 4264960487 |
package foo
expect class <!LINE_MARKER("descr='Has actuals in jvmAndJs module'")!>ExpectInCommonActualInMiddle<!>
expect class <!LINE_MARKER("descr='Has actuals in [jvm, js] module'")!>ExpectInCommonActualInPlatforms<!>
expect class <!NO_ACTUAL_FOR_EXPECT, NO_ACTUAL_FOR_EXPECT!>ExpectInCommonWithoutActual<!>
| plugins/kotlin/idea/tests/testData/multiplatform/hierarcicalActualization/common/common.kt | 1825329513 |
/*
* 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.settingsRepository.actions
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.StorageScheme
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectEx
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.FileStatus
import com.intellij.openapi.vcs.actions.CommonCheckinFilesAction
import com.intellij.openapi.vcs.actions.VcsContext
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.CommitContext
import com.intellij.openapi.vcs.changes.CommitExecutor
import com.intellij.openapi.vcs.checkin.BeforeCheckinDialogHandler
import com.intellij.openapi.vcs.checkin.CheckinHandler
import com.intellij.openapi.vcs.checkin.CheckinHandlerFactory
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.project.stateStore
import com.intellij.util.SmartList
import org.jetbrains.settingsRepository.CommitToIcsDialog
import org.jetbrains.settingsRepository.ProjectId
import org.jetbrains.settingsRepository.icsManager
import org.jetbrains.settingsRepository.icsMessage
import java.util.*
class CommitToIcsAction : CommonCheckinFilesAction() {
class IcsBeforeCommitDialogHandler : CheckinHandlerFactory() {
override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler {
return CheckinHandler.DUMMY
}
override fun createSystemReadyHandler(project: Project): BeforeCheckinDialogHandler? {
return BEFORE_CHECKIN_DIALOG_HANDLER
}
companion object {
private val BEFORE_CHECKIN_DIALOG_HANDLER = object : BeforeCheckinDialogHandler() {
override fun beforeCommitDialogShown(project: Project, changes: List<Change>, executors: Iterable<CommitExecutor>, showVcsCommit: Boolean): Boolean {
val collectConsumer = ProjectChangeCollectConsumer(project)
collectProjectChanges(changes, collectConsumer)
showDialog(project, collectConsumer, null)
return true
}
}
}
}
override fun getActionName(dataContext: VcsContext): String = icsMessage("action.CommitToIcs.text")
override fun isApplicableRoot(file: VirtualFile, status: FileStatus, dataContext: VcsContext): Boolean {
val project = dataContext.project
return project is ProjectEx && project.stateStore.storageScheme == StorageScheme.DIRECTORY_BASED && super.isApplicableRoot(file, status, dataContext) && !file.isDirectory && isProjectConfigFile(file, dataContext.project!!)
}
override fun prepareRootsForCommit(roots: Array<FilePath>, project: Project): Array<FilePath> = roots
override fun performCheckIn(context: VcsContext, project: Project, roots: Array<out FilePath>) {
val projectId = getProjectId(project) ?: return
val changes = context.selectedChanges
val collectConsumer = ProjectChangeCollectConsumer(project)
if (changes != null && changes.isNotEmpty()) {
for (change in changes) {
collectConsumer.consume(change)
}
}
else {
val manager = ChangeListManager.getInstance(project)
for (path in getRoots(context)) {
collectProjectChanges(manager.getChangesIn(path), collectConsumer)
}
}
showDialog(project, collectConsumer, projectId)
}
}
private class ProjectChangeCollectConsumer(private val project: Project) {
private var projectChanges: MutableList<Change>? = null
fun consume(change: Change) {
if (isProjectConfigFile(change.virtualFile, project)) {
if (projectChanges == null) {
projectChanges = SmartList<Change>()
}
projectChanges!!.add(change)
}
}
fun getResult() = if (projectChanges == null) listOf<Change>() else projectChanges!!
fun hasResult() = projectChanges != null
}
private fun getProjectId(project: Project): String? {
val projectId = ServiceManager.getService<ProjectId>(project, ProjectId::class.java)!!
if (projectId.uid == null) {
if (icsManager.settings.doNoAskMapProject ||
MessageDialogBuilder.yesNo("Settings Server Project Mapping", "Project is not mapped on Settings Server. Would you like to map?").project(project).doNotAsk(object : DialogWrapper.DoNotAskOption.Adapter() {
override fun isSelectedByDefault(): Boolean {
return true
}
override fun rememberChoice(isSelected: Boolean, exitCode: Int) {
icsManager.settings.doNoAskMapProject = isSelected
}
}).show() == Messages.YES) {
projectId.uid = UUID.randomUUID().toString()
}
}
return projectId.uid
}
private fun showDialog(project: Project, collectConsumer: ProjectChangeCollectConsumer, projectId: String?) {
if (!collectConsumer.hasResult()) {
return
}
var effectiveProjectId = projectId
if (effectiveProjectId == null) {
effectiveProjectId = getProjectId(project)
if (effectiveProjectId == null) {
return
}
}
CommitToIcsDialog(project, effectiveProjectId, collectConsumer.getResult()).show()
}
private fun collectProjectChanges(changes: Collection<Change>, collectConsumer: ProjectChangeCollectConsumer) {
for (change in changes) {
collectConsumer.consume(change)
}
}
private fun isProjectConfigFile(file: VirtualFile?, project: Project): Boolean {
if (file == null) {
return false
}
return FileUtil.isAncestor(project.basePath!!, file.path, true)
}
| plugins/settings-repository/src/actions/CommitToIcsAction.kt | 3320476618 |
package engineer.carrot.warren.warren.handler
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.never
import com.nhaarman.mockito_kotlin.verify
import engineer.carrot.warren.kale.irc.CharacterCodes
import engineer.carrot.warren.kale.irc.message.rfc1459.PrivMsgMessage
import engineer.carrot.warren.kale.irc.message.utility.CaseMapping
import engineer.carrot.warren.kale.irc.prefix.Prefix
import engineer.carrot.warren.warren.event.*
import engineer.carrot.warren.warren.state.*
import org.junit.Before
import org.junit.Test
class PrivMsgHandlerTests {
lateinit var handler: PrivMsgHandler
lateinit var channelTypesState: ChannelTypesState
lateinit var joinedChannelsState: JoinedChannelsState
lateinit var mockEventDispatcher: IWarrenEventDispatcher
@Before fun setUp() {
joinedChannelsState = JoinedChannelsState(mappingState = CaseMappingState(CaseMapping.RFC1459))
channelTypesState = ChannelTypesState(types = setOf('#', '&'))
mockEventDispatcher = mock()
handler = PrivMsgHandler(mockEventDispatcher, joinedChannelsState, channelTypesState)
}
@Test fun test_handle_ChannelMessage_FiresEvent() {
val channel = emptyChannel("&channel")
channel.users += generateUser("someone")
joinedChannelsState += channel
handler.handle(PrivMsgMessage(source = Prefix(nick = "someone"), target = "&channel", message = "a test message"), mapOf())
verify(mockEventDispatcher).fire(ChannelMessageEvent(user = generateUser("someone"), channel = channel, message = "a test message"))
}
@Test fun test_handle_ChannelMessage_NotInChannel_DoesNothing() {
handler.handle(PrivMsgMessage(source = Prefix(nick = "someone"), target = "¬InChannel", message = "a test message"), mapOf())
verify(mockEventDispatcher, never()).fire(any<IWarrenEvent>())
}
@Test fun test_handle_PrivateMessage_FiresEvent() {
handler.handle(PrivMsgMessage(source = Prefix(nick = "someone"), target = "not-a-channel", message = "a test message"), mapOf())
verify(mockEventDispatcher).fire(PrivateMessageEvent(user = Prefix(nick = "someone"), message = "a test message"))
}
@Test fun test_handle_NoSource_DoesNothing() {
handler.handle(PrivMsgMessage(source = null, target = "not-a-channel", message = "a test message"), mapOf())
verify(mockEventDispatcher, never()).fire(any<IWarrenEvent>())
}
@Test fun test_handle_ChannelMessage_Action_FiresEvent() {
val channel = emptyChannel("&channel")
channel.users += generateUser("someone")
joinedChannelsState += channel
handler.handle(PrivMsgMessage(source = Prefix(nick = "someone"), target = "&channel", message = "${CharacterCodes.CTCP}ACTION an action${CharacterCodes.CTCP}"), mapOf())
verify(mockEventDispatcher).fire(ChannelActionEvent(user = generateUser("someone"), channel = channel, message = "an action"))
}
@Test fun test_handle_PrivateMessage_Action_FiresEvent() {
handler.handle(PrivMsgMessage(source = Prefix(nick = "someone"), target = "not a channel", message = "${CharacterCodes.CTCP}ACTION an action${CharacterCodes.CTCP}"), mapOf())
verify(mockEventDispatcher).fire(PrivateActionEvent(user = Prefix(nick = "someone"), message = "an action"))
}
} | src/test/kotlin/engineer/carrot/warren/warren/handler/PrivMsgHandlerTests.kt | 2895929042 |
package rrozanski.wisiszmihajs.di
import rrozanski.wisiszmihajs.App
import rrozanski.wisiszmihajs.MainActivity
/**
* Created by Robert Różański on 27.08.2017.
*/
class DI {
private val injector = Injector()
private var appComponent: AppComponent? = null
fun injectors(): Injector {
return injector
}
fun initAppComponent(app: App) {
appComponent = DaggerAppComponent.builder().contextModule(ContextModule(app)).build()
}
fun obtainAppComponent(): AppComponent? {
return appComponent
}
inner class Injector {
fun inject(activity: MainActivity) {
obtainAppComponent()?.inject(activity)
}
}
companion object {
val di = DI()
fun di(): DI {
return di
}
}
}
| app/src/main/java/rrozanski/wisiszmihajs/di/DI.kt | 3934887922 |
package object_keyword
/**
* Desc: companion object里声明方法 演示
* Created by Chiclaim on 2018/9/20.
*/
class ObjectKeywordTest2 {
companion object {
fun run() {
println("run...")
}
}
}
/*
需要注意的是上面的run方法并不是一个static静态方法,只是让我们在调用的时候像静态方法(ObjectKeywordTest2.run())
底层调用依然是通过ObjectKeywordTest2的静态内部类来访问的:ObjectKeywordTest2.Companion.run();
对应的Java代码如下所示:
public final class ObjectKeywordTest2 {
public static final ObjectKeywordTest2.Companion Companion = new ObjectKeywordTest2.Companion((DefaultConstructorMarker)null);
public static final class Companion {
public final void run() {
String var1 = "run...";
System.out.println(var1);
}
private Companion() {
}
}
}
据此可得:在companion object中声明的方法、静态变量、私有常量都只能通过Companion访问
在companion object中声明的方法会放到静态内部类Companion中
*/ | language-kotlin/kotlin-sample/kotlin-in-action/src/object_keyword/ObjectKeywordTest2.kt | 2391694546 |
package com.airbnb.lottie.sample.compose.composables
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.LottieConstants
import com.airbnb.lottie.compose.rememberLottieComposition
import com.airbnb.lottie.sample.compose.R
@Composable
fun Loader(
modifier: Modifier = Modifier
) {
val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(R.raw.loading))
LottieAnimation(
composition,
iterations = LottieConstants.IterateForever,
modifier = modifier
.size(100.dp)
)
}
| sample-compose/src/main/java/com/airbnb/lottie/sample/compose/composables/Loader.kt | 1375366027 |
/*
* Copyright (C) 2018 Yaroslav Mytkalyk
*
* 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.doctoror.particleswallpaper.engine.opengl
import android.annotation.TargetApi
import android.opengl.GLSurfaceView
import android.os.Build
import android.os.Handler
import android.view.SurfaceHolder
import com.doctoror.particlesdrawable.contract.SceneScheduler
import com.doctoror.particlesdrawable.opengl.chooser.FailsafeEGLConfigChooserFactory
import com.doctoror.particlesdrawable.opengl.renderer.GlSceneRenderer
import com.doctoror.particlesdrawable.opengl.util.GLErrorChecker
import com.doctoror.particleswallpaper.engine.EngineController
import com.doctoror.particleswallpaper.engine.EnginePresenter
import com.doctoror.particleswallpaper.engine.EngineSceneRenderer
import com.doctoror.particleswallpaper.engine.makeInjectArgumentsForWallpaperServiceEngineImpl
import com.doctoror.particleswallpaper.framework.di.get
import com.doctoror.particleswallpaper.framework.execution.GlScheduler
import com.doctoror.particleswallpaper.framework.opengl.KnownOpenglIssuesHandler
import com.doctoror.particleswallpaper.userprefs.data.OpenGlSettings
import net.rbgrn.android.glwallpaperservice.GLWallpaperService
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10
class GlWallpaperServiceImpl : GLWallpaperService() {
override fun onCreateEngine(): Engine {
val renderer = GlEngineSceneRenderer()
val settingsOpenGL: OpenGlSettings = get(this)
val knownOpenglIssuesHandler: KnownOpenglIssuesHandler = get(this)
val engine = EngineImpl(knownOpenglIssuesHandler, renderer, settingsOpenGL.numSamples)
engine.presenter = get(
context = this,
parameters = {
makeInjectArgumentsForWallpaperServiceEngineImpl(
engine,
GlScheduler(engine),
renderer as EngineSceneRenderer,
engine as SceneScheduler
)
}
)
return engine
}
inner class EngineImpl(
private val knownOpenglIssuesHandler: KnownOpenglIssuesHandler,
private val renderer: GlSceneRenderer,
samples: Int
) : GLEngine(), EngineController, GLSurfaceView.Renderer, SceneScheduler {
private val handler = Handler()
lateinit var presenter: EnginePresenter
@Volatile
private var surfaceWidth = 0
@Volatile
private var surfaceHeight = 0
private var firstDraw = true
init {
GLErrorChecker.setShouldCheckGlError(true)
setEGLContextClientVersion(2)
setEGLConfigChooser(
FailsafeEGLConfigChooserFactory.newFailsafeEGLConfigChooser(samples, null)
)
setRenderer(this)
renderMode = RENDERMODE_WHEN_DIRTY
}
override fun onCreate(surfaceHolder: SurfaceHolder?) {
super.onCreate(surfaceHolder)
queueEvent { presenter.onCreate() }
}
override fun onDestroy() {
super.onDestroy()
queueEvent { presenter.onDestroy() }
}
override fun onSurfaceCreated(gl: GL10, config: EGLConfig?) {
renderer.setupGl()
presenter.onSurfaceCreated()
}
override fun onSurfaceChanged(gl: GL10, width: Int, height: Int) {
surfaceWidth = width
surfaceHeight = height
notifyDimensions(
width,
height,
desiredMinimumWidth
)
}
override fun onDesiredSizeChanged(desiredWidth: Int, desiredHeight: Int) {
super.onDesiredSizeChanged(desiredWidth, desiredHeight)
queueEvent {
notifyDimensions(
surfaceWidth,
surfaceHeight,
desiredWidth
)
}
}
private fun notifyDimensions(
surfaceWidth: Int,
surfaceHeight: Int,
desiredWidth: Int
) {
if (surfaceWidth != 0 && surfaceHeight != 0) {
presenter.setDimensions(
EnginePresenter.WallpaperDimensions(
width = surfaceWidth,
height = surfaceHeight,
desiredWidth = Math.max(surfaceWidth, desiredWidth)
)
)
}
}
override fun onOffsetsChanged(
xOffset: Float,
yOffset: Float,
xOffsetStep: Float,
yOffsetStep: Float,
xPixelOffset: Int,
yPixelOffset: Int
) {
queueEvent { presenter.setTranslationX(xPixelOffset.toFloat()) }
}
override fun onDrawFrame(gl: GL10) {
if (firstDraw) {
// Never check draw errors there. Disable on first call.
GLErrorChecker.setShouldCheckGlError(false)
}
presenter.onDrawFrame()
if (firstDraw) {
firstDraw = false
// Check draw error once here, where known issues expected.
knownOpenglIssuesHandler.handleGlError("GlWallpaperServiceImpl.onDrawFrame")
}
}
override fun onSurfaceDestroyed(holder: SurfaceHolder) {
super.onSurfaceDestroyed(holder)
presenter.visible = false
}
override fun onVisibilityChanged(visible: Boolean) {
super.onVisibilityChanged(visible)
queueEvent { presenter.visible = visible }
}
@TargetApi(Build.VERSION_CODES.O_MR1)
override fun onComputeColors() = presenter.onComputeColors()
override fun scheduleNextFrame(delay: Long) {
if (presenter.visible) {
if (delay == 0L) {
requestRender()
} else {
handler.postDelayed(renderRunnable, delay)
}
}
}
override fun unscheduleNextFrame() {
handler.removeCallbacksAndMessages(null)
}
private val renderRunnable = Runnable { requestRender() }
}
}
| app/src/main/java/com/doctoror/particleswallpaper/engine/opengl/GlWallpaperServiceImpl.kt | 1890391074 |
/*
* Copyright 2017-2021 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 info.novatec.testit.logrecorder.assertion.blocks
import info.novatec.testit.logrecorder.api.LogLevel.DEBUG
import info.novatec.testit.logrecorder.api.LogLevel.INFO
import info.novatec.testit.logrecorder.assertion.LogRecordAssertion.Companion.assertThat
import info.novatec.testit.logrecorder.assertion.isEmpty
import info.novatec.testit.logrecorder.assertion.logEntry
import info.novatec.testit.logrecorder.assertion.logRecord
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
internal class IsEmptyTests {
@Test
fun `reference check - empty`() {
val emptyLog = logRecord()
assertThat(emptyLog) { isEmpty() }
}
@Test
fun `non empty record throws assertion error`() {
val log = logRecord(
logEntry(level = INFO, message = "message #1"),
logEntry(level = DEBUG, message = "message #2")
)
val ex = assertThrows<AssertionError> {
assertThat(log) { isEmpty() }
}
assertThat(ex).hasMessage(
"""
Expected log to be empty but there were messages:
INFO | message #1
DEBUG | message #2
""".trimIndent()
)
}
}
| logrecorder/logrecorder-assertions/src/test/kotlin/info/novatec/testit/logrecorder/assertion/blocks/IsEmptyTests.kt | 4241191908 |
/*
* Copyright (c) 2016-2018 ayatk.
*
* 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.ayatk.biblio.infrastructure.database
import androidx.room.TypeConverter
import com.ayatk.biblio.infrastructure.database.entity.enums.BigGenre
import com.ayatk.biblio.infrastructure.database.entity.enums.Genre
import com.ayatk.biblio.infrastructure.database.entity.enums.NovelState
import com.ayatk.biblio.infrastructure.database.entity.enums.Publisher
import com.ayatk.biblio.infrastructure.database.entity.enums.ReadingState
import java.util.Date
import java.util.UUID
@Suppress("TooManyFunctions")
object Converters {
@JvmStatic
@TypeConverter
fun serializeBigGenre(genre: BigGenre): String = genre.name
@JvmStatic
@TypeConverter
fun deserializeBigGenre(genre: String): BigGenre = BigGenre.valueOf(genre)
@JvmStatic
@TypeConverter
fun serializeGenre(genre: Genre): String = genre.name
@JvmStatic
@TypeConverter
fun deserializeGenre(genre: String): Genre = Genre.valueOf(genre)
@JvmStatic
@TypeConverter
fun serializeNovelType(state: NovelState): String = state.name
@JvmStatic
@TypeConverter
fun deserializeNovelType(state: String): NovelState = NovelState.valueOf(state)
@JvmStatic
@TypeConverter
fun serializePublisher(publisher: Publisher): String = publisher.name
@JvmStatic
@TypeConverter
fun deserializePublisher(publisher: String): Publisher = Publisher.valueOf(publisher)
@JvmStatic
@TypeConverter
fun serializeReadingState(readingState: ReadingState): String = readingState.name
@JvmStatic
@TypeConverter
fun deserializeReadingState(state: String): ReadingState = ReadingState.valueOf(state)
@JvmStatic
@TypeConverter
fun deserializeUUID(value: String): UUID = UUID.fromString(value)
@JvmStatic
@TypeConverter
fun serializeUUID(value: UUID): String = value.toString()
@JvmStatic
@TypeConverter
fun deserializeDate(value: Long): Date = Date(value)
@JvmStatic
@TypeConverter
fun serializeDate(value: Date): Long = value.time
}
| infrastructure/database/src/main/java/com/ayatk/biblio/infrastructure/database/Converters.kt | 755183838 |
package ru.bozaro.gitlfs.client.internal
import org.apache.http.HttpStatus
import org.slf4j.LoggerFactory
import ru.bozaro.gitlfs.client.AuthHelper
import ru.bozaro.gitlfs.client.BatchSettings
import ru.bozaro.gitlfs.client.Client
import ru.bozaro.gitlfs.client.Client.ConnectionClosePolicy
import ru.bozaro.gitlfs.client.exceptions.ForbiddenException
import ru.bozaro.gitlfs.client.exceptions.UnauthorizedException
import ru.bozaro.gitlfs.common.Constants.PATH_BATCH
import ru.bozaro.gitlfs.common.data.*
import java.io.FileNotFoundException
import java.io.IOException
import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
import java.util.stream.Collectors
/**
* Base batch client.
*
* @author Artem V. Navrotskiy
*/
abstract class BatchWorker<T, R>(
protected val client: Client,
protected val pool: ExecutorService,
private val settings: BatchSettings,
private val operation: Operation
) {
private val log = LoggerFactory.getLogger(BatchWorker::class.java)
private val batchSequence = AtomicInteger(0)
private val batchInProgress = AtomicInteger()
private val objectQueue: ConcurrentMap<String, State<T, R?>> = ConcurrentHashMap()
private val objectInProgress = AtomicInteger(0)
private val currentAuth = AtomicReference<Link?>(null)
/**
* This method start send object metadata to server.
*
* @param context Object worker context.
* @param meta Object metadata.
* @return Return future with result. For same objects can return same future.
*/
protected fun enqueue(meta: Meta, context: T): CompletableFuture<R?> {
var state = objectQueue[meta.oid]
if (state != null) {
if (state.future.isCancelled) {
objectQueue.remove(meta.oid, state)
state = null
}
}
if (state == null) {
val newState = State<T, R?>(meta, context)
state = objectQueue.putIfAbsent(meta.oid, newState)
if (state == null) {
state = newState
stateEnqueue(true)
}
}
return state.future
}
private fun stateEnqueue(pooled: Boolean) {
val batchId = batchSequence.incrementAndGet()
tryBatchRequest(batchId, pooled)
}
private fun tryBatchRequestPredicate(): Boolean {
return (objectInProgress.get() < settings.threshold
&& !objectQueue.isEmpty())
}
private fun tryBatchRequest(batchId: Int, pooled: Boolean): Boolean {
if (!tryBatchRequestPredicate()) {
return false
}
if (batchInProgress.compareAndSet(0, batchId)) {
executeInPool(
"batch request: " + objectQueue.size + " in queue",
{
var curBatchId = batchId
while (true) {
try {
submitBatchTask()
} finally {
batchInProgress.set(0)
}
val newBatchId = batchSequence.get()
if (newBatchId == curBatchId && !tryBatchRequestPredicate()) {
break
}
curBatchId = newBatchId
if (!batchInProgress.compareAndSet(0, curBatchId)) {
break
}
}
},
{ batchInProgress.compareAndSet(batchId, 0) },
pooled
)
return true
}
return false
}
private fun invalidateAuth(auth: Link) {
if (currentAuth.compareAndSet(auth, null)) {
client.authProvider.invalidateAuth(operation, auth)
}
}
private fun submitBatchTask() {
val batch = takeBatch()
var auth = currentAuth.get()
try {
if (batch.isNotEmpty()) {
if (auth == null) {
auth = client.authProvider.getAuth(operation)
currentAuth.set(auth)
}
val metas = batch.values.stream().map { s: State<T, R?> -> s.meta }.collect(Collectors.toList())
val result = client.doRequest(
auth,
JsonPost(BatchReq(operation, metas), BatchRes::class.java),
AuthHelper.join(auth.href, PATH_BATCH),
ConnectionClosePolicy.Close
)
for (item in result.objects) {
val state = batch.remove(item.oid)
if (state != null) {
val error = item.error
if (error != null) {
objectQueue.remove(item.oid, state)
state.future.completeExceptionally(createError(error))
} else {
submitTask(state, item, auth)
}
}
}
for (value in batch.values) {
value.future.completeExceptionally(IOException("Requested object not found in server response: " + value.meta.oid))
}
}
} catch (e: UnauthorizedException) {
auth?.let { invalidateAuth(it) }
} catch (e: IOException) {
for (state in batch.values) {
state.onException(e, state.retry)
}
}
}
protected fun createError(error: Error): Throwable {
return if (error.code == HttpStatus.SC_NOT_FOUND) {
FileNotFoundException(error.message)
} else IOException("Can't process object (code " + error.code + "): " + error.message)
}
protected abstract fun objectTask(state: State<T, R?>, item: BatchItem): Work<R>?
/**
* Submit object processing task.
*
* @param state Current object state
* @param item Metadata information with upload/download urls.
* @param auth Urls authentication state.
*/
private fun submitTask(state: State<T, R?>, item: BatchItem, auth: Link) {
// Submit task
val holder = StateHolder(state)
try {
state.auth = auth
val worker = objectTask(state, item)
if (state.future.isDone) {
holder.close()
return
}
checkNotNull(worker) { "Uncompleted task worker is null: $item" }
executeInPool(
"task: " + state.meta.oid,
{ processObject(state, auth, worker) }, { holder.close() },
true
)
} catch (e: Throwable) {
holder.close()
throw e
}
}
private fun takeBatch(): MutableMap<String, State<T, R?>> {
val batch: MutableMap<String, State<T, R?>> = HashMap()
val completed: MutableList<State<T, R?>> = ArrayList()
for (state in objectQueue.values) {
if (state.future.isDone) {
completed.add(state)
continue
}
if (state.auth == null) {
batch[state.meta.oid] = state
if (batch.size >= settings.limit) {
break
}
}
}
for (state in completed) {
objectQueue.remove(state.meta.oid, state)
}
return batch
}
private fun processObject(state: State<T, R?>, auth: Link, worker: Work<R>) {
if (currentAuth.get() != auth) {
state.auth = null
return
}
try {
state.auth = auth
val result = worker.exec(auth)
objectQueue.remove(state.meta.oid, state)
state.future.complete(result)
} catch (e: UnauthorizedException) {
invalidateAuth(auth)
} catch (e: ForbiddenException) {
state.onException(e, 0)
} catch (e: Throwable) {
state.onException(e, settings.retryCount)
} finally {
state.auth = null
}
}
/**
* Schedule task in thread pool.
*
*
* If pool reject task - task will execute immediately in current thread.
*
*
* If pool is shutdown - task will not run, but finalizer will executed.
*
* @param name Task name for debug
* @param task Task runnable
* @param finalizer Finalizer to execute like 'try-final' block
*/
private fun executeInPool(name: String, task: Runnable, finalizer: Runnable?, pooled: Boolean) {
if (pool.isShutdown) {
log.warn("Thread pool is shutdown")
finalizer?.run()
return
}
if (!pooled) {
log.debug("Begin: $name")
try {
task.run()
} catch (e: Throwable) {
log.error("Execute exception: $e")
finalizer?.run()
throw e
} finally {
finalizer?.run()
log.debug("End: $name")
}
return
}
try {
pool.execute(object : Runnable {
override fun run() {
executeInPool(name, task, finalizer, false)
}
override fun toString(): String {
return name
}
})
} catch (e: RejectedExecutionException) {
if (pool.isShutdown) {
log.warn("Thread pool is shutdown")
} else {
executeInPool(name, task, finalizer, false)
}
} catch (e: Throwable) {
log.error("Execute in pool exception: $e")
finalizer?.run()
throw e
}
}
class State<T, R>(
val meta: Meta,
val context: T
) {
val future = CompletableFuture<R>()
@Volatile
var auth: Link? = null
var retry = 0
fun onException(e: Throwable, maxRetryCount: Int) {
retry++
if (retry >= maxRetryCount) {
future.completeExceptionally(e)
}
auth = null
}
}
private inner class StateHolder(state: State<T, R?>) : AutoCloseable {
private val stateRef: AtomicReference<State<T, R?>> = AtomicReference(state)
override fun close() {
val state = stateRef.getAndSet(null) ?: return
if (state.future.isDone) {
objectInProgress.decrementAndGet()
objectQueue.remove(state.meta.oid, state)
} else {
state.auth = null
objectInProgress.decrementAndGet()
}
stateEnqueue(false)
}
init {
objectInProgress.incrementAndGet()
}
}
}
| gitlfs-client/src/main/kotlin/ru/bozaro/gitlfs/client/internal/BatchWorker.kt | 2883115270 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package vulkan.templates
import org.lwjgl.generator.*
import vulkan.*
val EXT_border_color_swizzle = "EXTBorderColorSwizzle".nativeClassVK("EXT_border_color_swizzle", type = "device", postfix = "EXT") {
documentation =
"""
After the publication of VK_EXT_custom_border_color, it was discovered that some implementations had undefined behavior when combining a sampler that uses a custom border color with image views whose component mapping is not the identity mapping.
Since VK_EXT_custom_border_color has already shipped, this new extension VK_EXT_border_color_swizzle was created to define the interaction between custom border colors and non-identity image view swizzles, and provide a work-around for implementations that must pre-swizzle the sampler border color to match the image view component mapping it is combined with.
This extension also defines the behavior between samplers with an opaque black border color and image views with a non-identity component swizzle, which was previously left undefined.
<h5>VK_EXT_border_color_swizzle</h5>
<dl>
<dt><b>Name String</b></dt>
<dd>{@code VK_EXT_border_color_swizzle}</dd>
<dt><b>Extension Type</b></dt>
<dd>Device extension</dd>
<dt><b>Registered Extension Number</b></dt>
<dd>412</dd>
<dt><b>Revision</b></dt>
<dd>1</dd>
<dt><b>Extension and Version Dependencies</b></dt>
<dd><ul>
<li>Requires support for Vulkan 1.0</li>
<li>Requires {@link EXTCustomBorderColor VK_EXT_custom_border_color} to be enabled for any device-level functionality</li>
</ul></dd>
<dt><b>Special Uses</b></dt>
<dd><ul>
<li><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#extendingvulkan-compatibility-specialuse">OpenGL / ES support</a></li>
<li><a target="_blank" href="https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html\#extendingvulkan-compatibility-specialuse">D3D support</a></li>
</ul></dd>
<dt><b>Contact</b></dt>
<dd><ul>
<li>Piers Daniell <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_border_color_swizzle]%20@pdaniell-nv%250A*Here%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_EXT_border_color_swizzle%20extension*">pdaniell-nv</a></li>
</ul></dd>
</dl>
<h5>Other Extension Metadata</h5>
<dl>
<dt><b>Last Modified Date</b></dt>
<dd>2021-10-12</dd>
<dt><b>IP Status</b></dt>
<dd>No known IP claims.</dd>
<dt><b>Contributors</b></dt>
<dd><ul>
<li>Graeme Leese, Broadcom</li>
<li>Jan-Harald Fredriksen, Arm</li>
<li>Ricardo Garcia, Igalia</li>
<li>Shahbaz Youssefi, Google</li>
<li>Stu Smith, AMD</li>
</ul></dd>
</dl>
"""
IntConstant(
"The extension specification version.",
"EXT_BORDER_COLOR_SWIZZLE_SPEC_VERSION".."1"
)
StringConstant(
"The extension name.",
"EXT_BORDER_COLOR_SWIZZLE_EXTENSION_NAME".."VK_EXT_border_color_swizzle"
)
EnumConstant(
"Extends {@code VkStructureType}.",
"STRUCTURE_TYPE_PHYSICAL_DEVICE_BORDER_COLOR_SWIZZLE_FEATURES_EXT".."1000411000",
"STRUCTURE_TYPE_SAMPLER_BORDER_COLOR_COMPONENT_MAPPING_CREATE_INFO_EXT".."1000411001"
)
} | modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/EXT_border_color_swizzle.kt | 4261159756 |
package ru.bozaro.gitlfs.client.io
import java.io.IOException
import java.io.InputStream
import java.net.URL
/**
* Create stream by URL.
*
* @author Artem V. Navrotskiy
*/
class UrlStreamProvider(private val url: URL) : StreamProvider {
@get:Throws(IOException::class)
override val stream: InputStream
get() = url.openStream()
}
| gitlfs-client/src/main/kotlin/ru/bozaro/gitlfs/client/io/UrlStreamProvider.kt | 4045964762 |
/*
* 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 it.codingjam.github.core
import com.google.gson.annotations.SerializedName
data class Contributor(
val login: String,
val contributions: Int,
@SerializedName("avatar_url")
val avatarUrl: String
) | core/src/main/java/it/codingjam/github/core/Contributor.kt | 4236824502 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
val NV_vertex_array_range = "NVVertexArrayRange".nativeClassGL("NV_vertex_array_range", postfix = NV) {
documentation =
"""
Native bindings to the $registryLink extension.
The goal of this extension is to permit extremely high vertex processing rates via OpenGL vertex arrays even when the CPU lacks the necessary data
movement bandwidth to keep up with the rate at which the vertex engine can consume vertices.
"""
IntConstant(
"""
Accepted by the {@code cap} parameter of EnableClientState, DisableClientState, and IsEnabled.
""",
"VERTEX_ARRAY_RANGE_NV"..0x851D
)
IntConstant(
"""
Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.
""",
"VERTEX_ARRAY_RANGE_LENGTH_NV"..0x851E,
"VERTEX_ARRAY_RANGE_VALID_NV"..0x851F,
"MAX_VERTEX_ARRAY_RANGE_ELEMENT_NV"..0x8520
)
IntConstant(
"""
Accepted by the {@code pname} parameter of GetPointerv.
""",
"VERTEX_ARRAY_RANGE_POINTER_NV"..0x8521
)
void(
"VertexArrayRangeNV",
"",
AutoSize("pointer")..GLsizei("length", ""),
void.p("pointer", "")
)
void(
"FlushVertexArrayRangeNV",
""
)
} | modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/NV_vertex_array_range.kt | 2502773830 |
package rynkbit.tk.coffeelist.ui.entity
import rynkbit.tk.coffeelist.contract.entity.Item
class UIItem(override val id: Int,
override val name: String,
override val price: Double,
override val stock: Int
) : Item | app/src/main/java/rynkbit/tk/coffeelist/ui/entity/UIItem.kt | 883595052 |
package com.ashish.movieguide.ui.discover.filter
import com.ashish.movieguide.di.multibindings.AbstractComponent
import com.ashish.movieguide.di.multibindings.fragment.FragmentComponentBuilder
import dagger.Subcomponent
/**
* Created by Ashish on Jan 24.
*/
@Subcomponent
interface FilterComponent : AbstractComponent<FilterBottomSheetDialogFragment> {
@Subcomponent.Builder
interface Builder : FragmentComponentBuilder<FilterBottomSheetDialogFragment, FilterComponent>
} | app/src/main/kotlin/com/ashish/movieguide/ui/discover/filter/FilterComponent.kt | 2923658506 |
// Copyright 2000-2017 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.debugger.streams.lib.impl
import com.intellij.debugger.streams.lib.IntermediateOperation
import com.intellij.debugger.streams.resolve.ValuesOrderResolver
import com.intellij.debugger.streams.trace.CallTraceInterpreter
import com.intellij.debugger.streams.trace.IntermediateCallHandler
import com.intellij.debugger.streams.trace.dsl.Dsl
import com.intellij.debugger.streams.wrapper.IntermediateStreamCall
/**
* @author Vitaliy.Bibaev
*/
abstract class IntermediateOperationBase(override val name: String,
private val handlerFactory: (Int, IntermediateStreamCall, Dsl) -> IntermediateCallHandler,
override val traceInterpreter: CallTraceInterpreter,
override val valuesOrderResolver: ValuesOrderResolver) : IntermediateOperation {
override fun getTraceHandler(callOrder: Int, call: IntermediateStreamCall, dsl: Dsl): IntermediateCallHandler =
handlerFactory.invoke(callOrder, call, dsl)
} | plugins/stream-debugger/src/com/intellij/debugger/streams/lib/impl/IntermediateOperationBase.kt | 616939066 |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.arch.db.adapters.custom.internal
import org.hisp.dhis.android.core.arch.json.internal.ObjectMapperFactory
internal class IntegerListColumnAdapter : JSONObjectListColumnAdapter<Int>() {
override fun getObjectClass(): Class<List<Int>> {
return ArrayList<Int>().javaClass
}
override fun serialize(o: List<Int>?): String? = IntegerListColumnAdapter.serialize(o)
companion object {
fun serialize(o: List<Int>?): String? {
return o?.let {
ObjectMapperFactory.objectMapper().writeValueAsString(it)
}
}
}
}
| core/src/main/java/org/hisp/dhis/android/core/arch/db/adapters/custom/internal/IntegerListColumnAdapter.kt | 2068439310 |
/*
* Copyright (C) 2016-2021 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker 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 org.isoron.uhabits.core.ui.screens.habits.list
import org.isoron.uhabits.core.commands.ArchiveHabitsCommand
import org.isoron.uhabits.core.commands.ChangeHabitColorCommand
import org.isoron.uhabits.core.commands.CommandRunner
import org.isoron.uhabits.core.commands.DeleteHabitsCommand
import org.isoron.uhabits.core.commands.UnarchiveHabitsCommand
import org.isoron.uhabits.core.models.Habit
import org.isoron.uhabits.core.models.HabitList
import org.isoron.uhabits.core.models.PaletteColor
import org.isoron.uhabits.core.ui.callbacks.OnColorPickedCallback
import org.isoron.uhabits.core.ui.callbacks.OnConfirmedCallback
import javax.inject.Inject
class ListHabitsSelectionMenuBehavior @Inject constructor(
private val habitList: HabitList,
private val screen: Screen,
private val adapter: Adapter,
var commandRunner: CommandRunner
) {
fun canArchive(): Boolean {
for (habit in adapter.getSelected()) if (habit.isArchived) return false
return true
}
fun canEdit(): Boolean {
return adapter.getSelected().size == 1
}
fun canUnarchive(): Boolean {
for (habit in adapter.getSelected()) if (!habit.isArchived) return false
return true
}
fun onArchiveHabits() {
commandRunner.run(ArchiveHabitsCommand(habitList, adapter.getSelected()))
adapter.clearSelection()
}
fun onChangeColor() {
val (color) = adapter.getSelected()[0]
screen.showColorPicker(color) { selectedColor: PaletteColor ->
commandRunner.run(ChangeHabitColorCommand(habitList, adapter.getSelected(), selectedColor))
adapter.clearSelection()
}
}
fun onDeleteHabits() {
screen.showDeleteConfirmationScreen(
{
adapter.performRemove(adapter.getSelected())
commandRunner.run(DeleteHabitsCommand(habitList, adapter.getSelected()))
adapter.clearSelection()
},
adapter.getSelected().size
)
}
fun onEditHabits() {
val selected = adapter.getSelected()
if (selected.isNotEmpty()) screen.showEditHabitsScreen(selected)
adapter.clearSelection()
}
fun onUnarchiveHabits() {
commandRunner.run(UnarchiveHabitsCommand(habitList, adapter.getSelected()))
adapter.clearSelection()
}
interface Adapter {
fun clearSelection()
fun getSelected(): List<Habit>
fun performRemove(selected: List<Habit>)
}
interface Screen {
fun showColorPicker(
defaultColor: PaletteColor,
callback: OnColorPickedCallback
)
fun showDeleteConfirmationScreen(
callback: OnConfirmedCallback,
quantity: Int
)
fun showEditHabitsScreen(selected: List<Habit>)
}
}
| uhabits-core/src/jvmMain/java/org/isoron/uhabits/core/ui/screens/habits/list/ListHabitsSelectionMenuBehavior.kt | 2911830252 |
// 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.intellij.build.images.sync
import org.apache.http.HttpEntityEnclosingRequest
import org.apache.http.HttpHeaders
import org.apache.http.client.methods.HttpRequestBase
import org.apache.http.entity.ContentType
import java.net.URLEncoder
import java.util.concurrent.TimeUnit
private val UPSOURCE = System.getProperty("upsource.url")
private fun upsourceGet(method: String, args: String): String {
val params = if (args.isEmpty()) "" else "?params=${URLEncoder.encode(args, Charsets.UTF_8.name())}"
return get("$UPSOURCE/~rpc/$method$params") {
upsourceAuthAndLog()
}
}
private fun upsourcePost(method: String, args: String) = post("$UPSOURCE/~rpc/$method", args) {
upsourceAuthAndLog()
addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString())
}
private fun HttpRequestBase.upsourceAuthAndLog() {
log("Calling $uri${if (this is HttpEntityEnclosingRequest && entity != null) " with ${entity.asString()}" else ""}")
basicAuth(System.getProperty("upsource.user.name"), System.getProperty("upsource.user.password"))
}
internal class Review(val id: String, val url: String)
@Suppress("ReplaceSingleLineLet")
internal fun createReview(projectId: String, branch: String, commits: Collection<String>): Review {
var revisions = emptyList<String>()
loop@ for (i in 1..20) {
revisions = getBranchRevisions(projectId, branch, commits.size)
when {
revisions.isNotEmpty() -> break@loop
i == 20 -> error("$commits are not found")
else -> {
log("Upsource hasn't updated branch list yet. Retrying in 30s..")
TimeUnit.SECONDS.sleep(30)
}
}
}
val reviewId = upsourcePost("createReview", """{
"projectId" : "$projectId",
"revisions" : [
${revisions.joinToString { "\"$it\"" }}
]}""")
.let { extract(it, Regex(""""reviewId":\{([^}]+)""")) }
.let { extract(it, Regex(""""reviewId":"([^,"]+)"""")) }
val review = Review(reviewId, "$UPSOURCE/$projectId/review/$reviewId")
removeReviewer(projectId, review, System.getProperty("upsource.user.email"))
return review
}
private fun getBranchRevisions(projectId: String, branch: String, limit: Int) =
extractAll(upsourceGet("getRevisionsListFiltered", """{
"projectId" : "$projectId",
"limit" : $limit,
"query" : "branch: $branch"
}"""), Regex(""""revisionId":"([^,"]+)""""))
internal fun addReviewer(projectId: String, review: Review, email: String) {
try {
actionOnReviewer("addParticipantToReview", projectId, review, email)
}
catch (e: Exception) {
e.printStackTrace()
if (email != DEFAULT_INVESTIGATOR) addReviewer(projectId, review, DEFAULT_INVESTIGATOR)
}
}
private fun removeReviewer(projectId: String, review: Review, email: String) {
callSafely {
actionOnReviewer("removeParticipantFromReview", projectId, review, email)
}
}
private fun actionOnReviewer(action: String, projectId: String, review: Review, email: String) {
val userId = userId(email, projectId)
upsourcePost(action, """{
"reviewId" : {
"projectId" : "$projectId",
"reviewId" : "${review.id}"
},
"participant" : {
"userId" : "$userId",
"role" : 2
}
}""")
}
private fun userId(email: String, projectId: String): String {
val invitation = upsourceGet("inviteUser", """{"projectId":"$projectId","email":"$email"}""")
return extract(invitation, Regex(""""userId":"([^,"]+)""""))
}
private fun extract(json: String, regex: Regex) = extractAll(json, regex).last()
private fun extractAll(json: String, regex: Regex) = json
.replace(" ", "")
.replace(System.lineSeparator(), "").let { str ->
regex.findAll(str).map { it.groupValues.last() }.toList()
}
internal fun postComment(projectId: String, review: Review, comment: String) {
upsourcePost("createDiscussion", """{
"projectId" : "$projectId",
"reviewId": {
"projectId" : "$projectId",
"reviewId": "${review.id}"
},
"text" : "$comment",
"anchor" : {}
}""")
} | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/upsource.kt | 2339921581 |
fun test() {
x()
<selection>// <caret>comment for several lines</selection>
foo()
bar()
y()
} | plugins/kotlin/idea/tests/testData/wordSelection/CommentForStatements/3.kt | 1329785431 |
// PROBLEM: none
// WITH_STDLIB
class SomeException : RuntimeException()
fun foo(): Int = 1
fun test(x: Boolean, y: Boolean) {
if (x) {
throw SomeException()
} else if (y) {
// empty
} else<caret> {
foo()
}
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantElseInIf/empty.kt | 1726927706 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.builtins.DefaultBuiltIns
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.util.calleeTextRangeInThis
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.util.getExplicitReceiverValue
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf
import org.jetbrains.kotlin.resolve.descriptorUtil.overriddenTreeAsSequence
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class ReplacePutWithAssignmentInspection : AbstractApplicabilityBasedInspection<KtDotQualifiedExpression>(
KtDotQualifiedExpression::class.java
), CleanupLocalInspectionTool {
override fun isApplicable(element: KtDotQualifiedExpression): Boolean {
if (element.receiverExpression is KtSuperExpression) return false
val callExpression = element.callExpression
if (callExpression?.valueArguments?.size != 2) return false
val calleeExpression = callExpression.calleeExpression as? KtNameReferenceExpression ?: return false
if (calleeExpression.getReferencedName() !in compatibleNames) return false
val context = element.analyze()
if (element.isUsedAsExpression(context)) return false
// This fragment had to be added because of incorrect behaviour of isUsesAsExpression
// TODO: remove it after fix of KT-25682
val binaryExpression = element.getStrictParentOfType<KtBinaryExpression>()
val right = binaryExpression?.right
if (binaryExpression?.operationToken == KtTokens.ELVIS &&
right != null && (right == element || KtPsiUtil.deparenthesize(right) == element)
) return false
val resolvedCall = element.getResolvedCall(context)
val receiverType = resolvedCall?.getExplicitReceiverValue()?.type ?: return false
val receiverClass = receiverType.constructor.declarationDescriptor as? ClassDescriptor ?: return false
if (!receiverClass.isSubclassOf(DefaultBuiltIns.Instance.mutableMap)) return false
val overriddenTree =
resolvedCall.resultingDescriptor.safeAs<CallableMemberDescriptor>()?.overriddenTreeAsSequence(true) ?: return false
if (overriddenTree.none { it.fqNameOrNull() == mutableMapPutFqName }) return false
val assignment = createAssignmentExpression(element) ?: return false
val newContext = assignment.analyzeAsReplacement(element, context)
return assignment.left.getResolvedCall(newContext)?.resultingDescriptor?.fqNameOrNull() == collectionsSetFqName
}
override fun applyTo(element: KtDotQualifiedExpression, project: Project, editor: Editor?) {
val assignment = createAssignmentExpression(element) ?: return
element.replace(assignment)
}
private fun createAssignmentExpression(element: KtDotQualifiedExpression): KtBinaryExpression? {
val valueArguments = element.callExpression?.valueArguments ?: return null
val firstArg = valueArguments[0]?.getArgumentExpression() ?: return null
val secondArg = valueArguments[1]?.getArgumentExpression() ?: return null
val label = if (secondArg is KtLambdaExpression) {
val returnLabel = secondArg.findDescendantOfType<KtReturnExpression>()?.getLabelName()
compatibleNames.firstOrNull { it == returnLabel }?.plus("@") ?: ""
} else ""
return KtPsiFactory(element).createExpressionByPattern(
"$0[$1] = $label$2",
element.receiverExpression, firstArg, secondArg,
reformat = false
) as? KtBinaryExpression
}
override fun inspectionHighlightRangeInElement(element: KtDotQualifiedExpression) = element.calleeTextRangeInThis()
override fun inspectionText(element: KtDotQualifiedExpression): String =
KotlinBundle.message("map.put.should.be.converted.to.assignment")
override val defaultFixText get() = KotlinBundle.message("convert.put.to.assignment")
companion object {
private val compatibleNames = setOf("put")
private val collectionsSetFqName = FqName("kotlin.collections.set")
private val mutableMapPutFqName = FqName("kotlin.collections.MutableMap.put")
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplacePutWithAssignmentInspection.kt | 3306309186 |
package pl.elpassion.elspace.hub.report.list
import android.support.test.InstrumentationRegistry.getTargetContext
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.assertion.ViewAssertions.matches
import android.support.test.espresso.contrib.RecyclerViewActions
import android.support.test.espresso.contrib.RecyclerViewActions.scrollToPosition
import android.support.test.espresso.matcher.ViewMatchers.*
import android.support.v7.widget.RecyclerView
import android.widget.TextView
import com.elpassion.android.commons.espresso.*
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import org.hamcrest.Matchers.instanceOf
import org.hamcrest.core.AllOf.allOf
import org.hamcrest.core.IsNot.not
import org.junit.Rule
import org.junit.Test
import pl.elpassion.elspace.R
import pl.elpassion.elspace.common.rule
import pl.elpassion.elspace.common.stubAllIntents
import pl.elpassion.elspace.commons.stubCurrentTime
import pl.elpassion.elspace.hub.project.CachedProjectRepository
import pl.elpassion.elspace.hub.project.CachedProjectRepositoryProvider
import pl.elpassion.elspace.hub.project.dto.newDailyReport
import pl.elpassion.elspace.hub.project.dto.newPaidVacationHourlyReport
import pl.elpassion.elspace.hub.project.dto.newProject
import pl.elpassion.elspace.hub.project.dto.newRegularHourlyReport
import pl.elpassion.elspace.hub.report.DailyReportType
import pl.elpassion.elspace.hub.report.add.ReportAddActivity
import pl.elpassion.elspace.hub.report.edit.ReportEditActivity
import io.reactivex.Observable
import org.junit.Assert.assertTrue
class ReportListActivityTest {
val service = mock<ReportList.Service>()
@JvmField @Rule
val rule = rule<ReportListActivity> {
CachedProjectRepositoryProvider.override = { mock<CachedProjectRepository>().apply { whenever(getPossibleProjects()).thenReturn(listOf(newProject())) } }
stubCurrentTime(year = 2016, month = 10, day = 4)
whenever(service.getReports(any())).thenReturn(Observable.just(listOf(
newRegularHourlyReport(year = 2016, month = 10, day = 3, project = newProject(name = "Project"), description = "Description", reportedHours = 8.0),
newRegularHourlyReport(year = 2016, month = 10, day = 2, reportedHours = 3.0),
newRegularHourlyReport(year = 2016, month = 10, day = 6, reportedHours = 4.0),
newDailyReport(year = 2016, month = 10, day = 7, reportType = DailyReportType.SICK_LEAVE),
newDailyReport(year = 2016, month = 10, day = 8, reportType = DailyReportType.UNPAID_VACATIONS),
newRegularHourlyReport(year = 2016, month = 10, day = 9, reportedHours = 3.0),
newPaidVacationHourlyReport(year = 2016, month = 10, day = 10, reportedHours = 3.0),
newDailyReport(year = 2016, month = 10, day = 11, reportType = DailyReportType.PAID_CONFERENCE))))
ReportList.ServiceProvider.override = { service }
}
@JvmField @Rule
val intents = InitIntentsRule()
@Test
fun shouldShowCorrectlyDayNameOnWeekendDays() {
onId(R.id.reportsContainer).hasChildWithText("1 Sat")
}
@Test
fun shouldShowCorrectlyDayNameOnNotFilledInDays() {
onId(R.id.reportsContainer).hasChildWithText("4 Tue")
}
@Test
fun shouldShowCorrectlyDayNameOnNormalDays() {
onId(R.id.reportsContainer).hasChildWithText("3 Mon")
}
@Test
fun shouldShowCorrectTotalHoursInEveryDay() {
onId(R.id.reportsContainer).hasChildWithText("Total: 8 hours")
}
@Test
fun shouldShowRegularHourlyReportOnContainer() {
onId(R.id.reportsContainer).hasChildWithText("8h - Project")
onId(R.id.reportsContainer).hasChildWithText("Description")
}
@Test
fun shouldOpenAddReportScreenOnWeekendDayClick() {
stubAllIntents()
onText("1 Sat").click()
checkIntent(ReportAddActivity::class.java)
}
@Test
fun shouldOpenAddReportScreenOnNotFilledInDayClick() {
stubAllIntents()
onText("4 Tue").click()
checkIntent(ReportAddActivity::class.java)
}
@Test
fun shouldOpenAddReportScreenOnNormalDayClick() {
stubAllIntents()
onText("3 Mon").click()
checkIntent(ReportAddActivity::class.java)
}
@Test
fun shouldOpenEditReportScreenOnDailyReportClick() {
stubAllIntents()
scrollToItemWithText("8 Sat")
onText("7 Fri").click()
checkIntent(ReportEditActivity::class.java)
}
@Test
fun shouldOpenEditReportScreenOnPaidVacationReportClick() {
stubAllIntents()
scrollToItemWithText("11 Tue")
onText("3h - ${getTargetContext().getString(R.string.report_paid_vacations_title)}").click()
checkIntent(ReportEditActivity::class.java)
}
@Test
fun shouldOpenEditReportScreenOnRegularReportClick() {
stubAllIntents()
onText("8h - Project").click()
checkIntent(ReportEditActivity::class.java)
}
@Test
fun shouldHaveOneDayWithMissingStatus() {
onId(R.id.reportsContainer).hasChildWithText(R.string.report_missing)
}
@Test
fun shouldNotHaveMissingInformationOnWeekendDays() {
verifyIfDayNumberOneHasNotMissingText()
}
@Test
fun shouldNotHaveTotalInformationOnNotPassedDays() {
verifyIfFifthDayHasNoInformationAboutTotal()
}
@Test
fun shouldShowTotalInformationOnWeekendDaysIfThereIsAReport() {
verifyIfWeekendDayWithReportHasTotalInformation()
}
@Test
fun shouldShowTotalInformationOnDayFromFutureIfThereAreReports() {
onView(withId(R.id.reportsContainer)).perform(scrollToPosition<RecyclerView.ViewHolder>(6))
verifyIfDayFromFutureWithReportsHasTotalInformation()
}
@Test
fun shouldShowCorrectlyMonthNameOnStart() {
onToolbarTitle()
.isDisplayed()
.hasText("October")
}
@Test
fun shouldShowCorrectlyMonthNameAfterClickOnNextMonth() {
onId(R.id.action_next_month).click()
onToolbarTitle()
.isDisplayed()
.hasText("November")
}
@Test
fun shouldShowCorrectlyMonthNameAfterClickOnPrevMonth() {
onId(R.id.action_prev_month).click()
onToolbarTitle()
.isDisplayed()
.hasText("September")
}
@Test
fun shouldOpenAddReportOnClickOnFAB() {
stubAllIntents()
onId(R.id.fabAddReport).click()
checkIntent(ReportAddActivity::class.java)
}
@Test
fun shouldNotShowMissingInformationWhenDayHasNoReportsButIsFromFuture() {
scrollToItemWithText("9 Sun")
onItemWithText("9 Sun").check(matches(not(hasDescendant(withText(R.string.report_missing)))))
}
@Test
fun shouldDisplayCorrectDescriptionOnNextButton() {
onId(R.id.action_next_month).check(matches(withContentDescription(R.string.next_month)))
}
@Test
fun shouldDisplayCorrectDescriptionOnPreviousButton() {
onId(R.id.action_prev_month).check(matches(withContentDescription(R.string.previous_month)))
}
@Test
fun shouldShowPaidVacationsInformationForPaidVacationReport() {
scrollToItemWithText("11 Tue")
onId(R.id.reportsContainer).hasChildWithText("3h - ${getTargetContext().getString(R.string.report_paid_vacations_title)}")
}
@Test
fun shouldShowUnpaidVacationsInformationForDailyReportTypeUnpaidVacations() {
scrollToItemWithText("8 Sat")
onItemWithText("8 Sat").check(matches(hasDescendant(withText(R.string.report_unpaid_vacations_title))))
}
@Test
fun shouldShowSickLeaveInformationForDailyReportTypeSickLeave() {
onItemWithText("7 Fri").check(matches(hasDescendant(withText(R.string.report_sick_leave_title))))
}
@Test
fun shouldShowPaidConferenceInformationForDailyReportTypePaidConference() {
scrollToItemWithText("11 Tue")
onItemWithText("11 Tue").check(matches(hasDescendant(withText(R.string.report_paid_conference_title))))
}
@Test
fun shouldHaveVisibleBackArrow() {
onToolbarBackArrow().isDisplayed()
}
@Test
fun shouldCloseActivityOnBackClicked() {
onToolbarBackArrow().click()
assertTrue(rule.activity.isFinishing)
}
private fun verifyIfDayNumberOneHasNotMissingText() {
onItemWithText("1 Sat").check(matches(not(hasDescendant(withText(R.string.report_missing)))))
}
private fun verifyIfFifthDayHasNoInformationAboutTotal() {
onItemWithText("5 Wed").check(matches(not(hasDescendant(withText("Total: 0 hours")))))
}
private fun verifyIfWeekendDayWithReportHasTotalInformation() {
onItemWithText("2 Sun").check(matches(hasDescendant(withText("Total: 3 hours"))))
}
private fun verifyIfDayFromFutureWithReportsHasTotalInformation() {
onItemWithText("6 Thu").check(matches(hasDescendant(withText("Total: 4 hours"))))
}
private fun onItemWithText(text: String) = onView(allOf(hasDescendant(withText(text)), withParent(withId(R.id.reportsContainer))))
private fun onToolbarTitle() = onView(allOf(instanceOf(TextView::class.java), withParent(withId(R.id.toolbar))))
private fun scrollToItemWithText(s: String) {
onView(withId(R.id.reportsContainer)).perform(RecyclerViewActions.scrollTo<RecyclerView.ViewHolder>(hasDescendant(withText(s))))
}
}
| el-space-app/src/androidTest/java/pl/elpassion/elspace/hub/report/list/ReportListActivityTest.kt | 3543954880 |
package com.packt.chapter7
class SomeClass() {
@JvmOverloads
fun foo(name: String = "Harry", location: String = "Cardiff"): Unit {
}
} | Chapter07/src/main/kotlin/com/packt/chapter7/7.16.4.JvmOverloads.kt | 1342688538 |
/*
* Copyright 2015-2017 Peng Wan <[email protected]>
*
* This file is part of Jem.
*
* 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 jclp
import jclp.io.defaultClassLoader
import jclp.log.Log
import java.util.*
interface KeyedService {
val keys: Set<String>
val name: String get() = ""
}
open class ServiceManager<S : KeyedService>(type: Class<S>, loader: ClassLoader? = null) {
private val serviceLoader = ServiceLoader.load(type, loader ?: defaultClassLoader())
private val localRegistry = hashMapOf<String, S>()
private val serviceProviders = hashSetOf<S>()
init {
initServices()
}
fun reload() {
localRegistry.clear()
serviceProviders.clear()
serviceLoader.reload()
initServices()
}
val services get() = serviceProviders + localRegistry.values
operator fun get(key: String) = localRegistry.getOrSet(key) {
serviceProviders.firstOrNull { key in it.keys }
}
operator fun set(name: String, factory: S) {
localRegistry[name] = factory
}
private fun initServices() {
val it = serviceLoader.iterator()
try {
while (it.hasNext()) {
try {
serviceProviders += it.next()
} catch (e: ServiceConfigurationError) {
Log.e(javaClass.simpleName, e) { "in providers.next()" }
}
}
} catch (e: ServiceConfigurationError) {
Log.e(javaClass.simpleName, e) { "in providers.hasNext()" }
}
}
}
| commons/src/main/kotlin/jclp/ServiceSpi.kt | 1104386855 |
package ua.com.lavi.komock.http.handler.callback
import ua.com.lavi.komock.model.Request
import ua.com.lavi.komock.model.Response
/**
* Created by Oleksandr Loushkin on 30.03.17.
*/
interface CallbackHandler {
fun handle(request: Request, response: Response)
} | komock-core/src/main/kotlin/ua/com/lavi/komock/http/handler/callback/CallbackHandler.kt | 3226468190 |
package com.mgaetan89.showsrage.model
import com.google.gson.annotations.SerializedName
data class ShowStat(
val archived: Int = 0,
val downloaded: Map<String, Int>? = null,
val failed: Int = 0,
val ignored: Int = 0,
val skipped: Int = 0,
val snatched: Map<String, Int>? = null,
@SerializedName("snatched_best") val snatchedBest: Int = 0,
val subtitled: Int = 0,
val total: Int = 0,
val unaired: Int = 0,
val wanted: Int = 0
) {
fun getTotalDone(): Int {
if (this.downloaded == null) {
return this.archived
}
val total = this.downloaded["total"] ?: return this.archived
return this.archived + total
}
fun getTotalPending(): Int {
if (this.snatched == null) {
return this.snatchedBest
}
val total = this.snatched["total"] ?: return this.snatchedBest
return this.snatchedBest + total
}
}
| app/src/main/kotlin/com/mgaetan89/showsrage/model/ShowStat.kt | 3455008171 |
package com.mgaetan89.showsrage.model
enum class ImageType(val command: String) {
BANNER("show.getbanner"),
FAN_ART("show.getfanart"),
POSTER("show.getposter")
}
| app/src/main/kotlin/com/mgaetan89/showsrage/model/ImageType.kt | 2830865461 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt
open class MalformedNbtFileException : Exception {
constructor(message: String) : super(message)
constructor(message: String, cause: Throwable) : super(message, cause)
}
class NbtFileParseTimeoutException(message: String) : MalformedNbtFileException(message)
| src/main/kotlin/com/demonwav/mcdev/nbt/MalformedNbtFileException.kt | 478979396 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util
import com.intellij.openapi.util.RecursionManager
import java.util.concurrent.atomic.AtomicReference
/**
* Same as [SafePublicationLazyImpl], but returns `null` in case of computation recursion occurred.
*/
class RecursionPreventingSafePublicationLazy<T>(recursionKey: Any?, initializer: () -> T) : Lazy<T?> {
@Volatile
private var initializer: (() -> T)? = { ourNotNullizer.notNullize(initializer()) }
private val valueRef: AtomicReference<T> = AtomicReference()
private val recursionKey: Any = recursionKey ?: this
override val value: T?
get() {
val computedValue = valueRef.get()
if (computedValue !== null) {
return ourNotNullizer.nullize(computedValue)
}
val initializerValue = initializer
if (initializerValue === null) {
// Some thread managed to clear the initializer => it managed to set the value.
return ourNotNullizer.nullize(valueRef.get())
}
val stamp = ourRecursionGuard.markStack()
val newValue = ourRecursionGuard.doPreventingRecursion(recursionKey, false, initializerValue)
// In case of recursion don't update [valueRef] and don't clear [initializer].
if (newValue === null) {
// Recursion occurred for this lazy.
return null
}
if (!stamp.mayCacheNow()) {
// Recursion occurred somewhere deep.
return ourNotNullizer.nullize(newValue)
}
if (!valueRef.compareAndSet(null, newValue)) {
// Some thread managed to set the value.
return ourNotNullizer.nullize(valueRef.get())
}
initializer = null
return ourNotNullizer.nullize(newValue)
}
override fun isInitialized(): Boolean = valueRef.get() !== null
override fun toString(): String = if (isInitialized()) value.toString() else "Lazy value not initialized yet."
companion object {
private val ourRecursionGuard = RecursionManager.createGuard("RecursionPreventingSafePublicationLazy")
private val ourNotNullizer = NotNullizer("RecursionPreventingSafePublicationLazy")
}
}
| platform/projectModel-api/src/com/intellij/util/RecursionPreventingSafePublicationLazy.kt | 72070843 |
// 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.nj2k.printing
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.PsiShortNamesCache
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.nj2k.JKImportStorage
import org.jetbrains.kotlin.nj2k.conversions.TOP_LEVEL_FUNCTIONS_THAT_MAY_BE_SHADOWED_BY_EXISTING_METHODS
import org.jetbrains.kotlin.nj2k.escaped
import org.jetbrains.kotlin.nj2k.symbols.*
import org.jetbrains.kotlin.nj2k.tree.JKClassAccessExpression
import org.jetbrains.kotlin.nj2k.tree.JKQualifiedExpression
import org.jetbrains.kotlin.nj2k.tree.JKTreeElement
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
internal class JKSymbolRenderer(private val importStorage: JKImportStorage, project: Project) {
private val canBeShortenedClassNameCache = CanBeShortenedCache(project)
private fun JKSymbol.isFqNameExpected(owner: JKTreeElement?): Boolean {
if (owner?.isSelectorOfQualifiedExpression() == true) return false
return fqName in TOP_LEVEL_FUNCTIONS_THAT_MAY_BE_SHADOWED_BY_EXISTING_METHODS ||
this is JKClassSymbol || isStaticMember || isEnumConstant
}
private fun JKSymbol.isFromJavaLangPackage() =
fqName.startsWith(JAVA_LANG_FQ_PREFIX)
fun renderSymbol(symbol: JKSymbol, owner: JKTreeElement?): String {
val name = symbol.name.escaped()
if (!symbol.isFqNameExpected(owner)) return name
val fqName = symbol.getDisplayFqName().escapedAsQualifiedName()
if (owner is JKClassAccessExpression && symbol.isFromJavaLangPackage()) return fqName
return when {
symbol is JKClassSymbol && canBeShortenedClassNameCache.canBeShortened(symbol) -> {
importStorage.addImport(fqName)
name
}
symbol.isStaticMember && symbol.containingClass?.isUnnamedCompanion == true -> {
val containingClass = symbol.containingClass ?: return fqName
val classContainingCompanion = containingClass.containingClass ?: return fqName
if (!canBeShortenedClassNameCache.canBeShortened(classContainingCompanion)) return fqName
importStorage.addImport(classContainingCompanion.getDisplayFqName())
"${classContainingCompanion.name.escaped()}.${SpecialNames.DEFAULT_NAME_FOR_COMPANION_OBJECT}.$name"
}
symbol.isEnumConstant || symbol.isStaticMember -> {
val containingClass = symbol.containingClass ?: return fqName
if (!canBeShortenedClassNameCache.canBeShortened(containingClass)) return fqName
importStorage.addImport(containingClass.getDisplayFqName())
"${containingClass.name.escaped()}.$name"
}
else -> fqName
}
}
private fun JKTreeElement.isSelectorOfQualifiedExpression() =
parent?.safeAs<JKQualifiedExpression>()?.selector == this
companion object {
private const val JAVA_LANG_FQ_PREFIX = "java.lang"
}
}
private class CanBeShortenedCache(project: Project) {
private val shortNameCache = PsiShortNamesCache.getInstance(project)
private val searchScope = GlobalSearchScope.allScope(project)
private val canBeShortenedCache = mutableMapOf<String, Boolean>().apply {
CLASS_NAMES_WHICH_HAVE_DIFFERENT_MEANINGS_IN_KOTLIN_AND_JAVA.forEach { name ->
this[name] = false
}
}
fun canBeShortened(symbol: JKClassSymbol): Boolean = canBeShortenedCache.getOrPut(symbol.name) {
var symbolsWithSuchNameCount = 0
val processSymbol = { _: PsiClass ->
symbolsWithSuchNameCount++
symbolsWithSuchNameCount <= 1 //stop if met more than one symbol with such name
}
shortNameCache.processClassesWithName(symbol.name, processSymbol, searchScope, null)
symbolsWithSuchNameCount == 1
}
companion object {
private val CLASS_NAMES_WHICH_HAVE_DIFFERENT_MEANINGS_IN_KOTLIN_AND_JAVA = setOf(
"Function",
"Serializable"
)
}
} | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/printing/JKSymbolRenderer.kt | 3359714961 |
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.model
import com.google.samples.apps.iosched.shared.data.ConferenceDataRepository
import com.google.samples.apps.iosched.shared.data.ConferenceDataSource
import com.google.samples.apps.iosched.test.data.TestData
import com.google.samples.apps.iosched.test.util.fakes.FakeAppDatabase
/**
* Test data for unit tests.
*/
object TestDataSource : ConferenceDataSource {
override fun getRemoteConferenceData(): ConferenceData? {
return TestData.conferenceData
}
override fun getOfflineConferenceData(): ConferenceData? {
return TestData.conferenceData
}
}
/** ConferenceDataRepository for tests */
object TestDataRepository : ConferenceDataRepository(
TestDataSource,
TestDataSource,
FakeAppDatabase()
) {
override fun getConferenceDays(): List<ConferenceDay> {
return TestData.TestConferenceDays
}
}
| mobile/src/test/java/com/google/samples/apps/iosched/model/MobileTestData.kt | 3877384938 |
package xyz.swagbot.features.music
import discord4j.common.util.*
class TrackContext(val requesterId: Snowflake, val requestedChannelId: Snowflake) {
private val skipList: MutableSet<Snowflake> = mutableSetOf()
val skipVoteCount: Int
get() = skipList.size
fun addSkipVote(userId: Snowflake): Boolean = skipList.add(userId)
}
| src/main/kotlin/features/music/TrackContext.kt | 3721763201 |
package com.apollographql.apollo3
import com.apollographql.apollo3.api.ApolloRequest
import com.apollographql.apollo3.api.ApolloResponse
import com.apollographql.apollo3.api.ExecutionContext
import com.apollographql.apollo3.api.ExecutionOptions
import com.apollographql.apollo3.api.MutableExecutionOptions
import com.apollographql.apollo3.api.Operation
import com.apollographql.apollo3.api.http.HttpHeader
import com.apollographql.apollo3.api.http.HttpMethod
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.single
class ApolloCall<D : Operation.Data> internal constructor(
internal val apolloClient: ApolloClient,
val operation: Operation<D>,
) : MutableExecutionOptions<ApolloCall<D>> {
override var executionContext: ExecutionContext = ExecutionContext.Empty
override var httpMethod: HttpMethod? = null
override var httpHeaders: List<HttpHeader>? = null
override var sendApqExtensions: Boolean? = null
override var sendDocument: Boolean? = null
override var enableAutoPersistedQueries: Boolean? = null
override fun addExecutionContext(executionContext: ExecutionContext) = apply {
this.executionContext = this.executionContext + executionContext
}
override fun httpMethod(httpMethod: HttpMethod?) = apply {
this.httpMethod = httpMethod
}
override fun httpHeaders(httpHeaders: List<HttpHeader>?) = apply {
this.httpHeaders = httpHeaders
}
override fun addHttpHeader(name: String, value: String) = apply {
this.httpHeaders = (this.httpHeaders ?: emptyList()) + HttpHeader(name, value)
}
override fun sendApqExtensions(sendApqExtensions: Boolean?) = apply {
this.sendApqExtensions = sendApqExtensions
}
override fun sendDocument(sendDocument: Boolean?) = apply {
this.sendDocument = sendDocument
}
override fun enableAutoPersistedQueries(enableAutoPersistedQueries: Boolean?) = apply {
this.enableAutoPersistedQueries = enableAutoPersistedQueries
}
override var canBeBatched: Boolean? = null
override fun canBeBatched(canBeBatched: Boolean?) = apply {
this.canBeBatched = canBeBatched
if (canBeBatched != null) addHttpHeader(ExecutionOptions.CAN_BE_BATCHED, canBeBatched.toString())
}
fun copy(): ApolloCall<D> {
return ApolloCall(apolloClient, operation)
.addExecutionContext(executionContext)
.httpMethod(httpMethod)
.httpHeaders(httpHeaders)
.sendApqExtensions(sendApqExtensions)
.sendDocument(sendDocument)
.enableAutoPersistedQueries(enableAutoPersistedQueries)
}
/**
* Returns a cold Flow that produces [ApolloResponse]s for this [ApolloCall].
* Note that the execution happens when collecting the Flow.
* This method can be called several times to execute a call again.
*
* Example:
* ```
* apolloClient.subscription(NewOrders())
* .toFlow()
* .collect {
* println("order received: ${it.data?.order?.id"})
* }
* ```
*/
fun toFlow(): Flow<ApolloResponse<D>> {
val request = ApolloRequest.Builder(operation)
.executionContext(executionContext)
.httpMethod(httpMethod)
.httpHeaders(httpHeaders)
.sendApqExtensions(sendApqExtensions)
.sendDocument(sendDocument)
.enableAutoPersistedQueries(enableAutoPersistedQueries)
.build()
return apolloClient.executeAsFlow(request)
}
/**
* A shorthand for `toFlow().single()`.
* Use this for queries and mutation to get a single [ApolloResponse] from the network or the cache.
* For subscriptions, you usually want to use [toFlow] instead to listen to all values.
*/
suspend fun execute(): ApolloResponse<D> {
return toFlow().single()
}
}
| apollo-runtime/src/commonMain/kotlin/com/apollographql/apollo3/ApolloCall.kt | 197205314 |
internal interface I
internal class C
internal class O
internal class E {
override fun equals(o: Any?): Boolean {
return super.equals(o)
}
}
internal open class B {
override fun equals(o: Any?): Boolean {
return super.equals(o)
}
}
internal class BB : B()
internal enum class EE {
A,
B,
C
}
internal class X {
fun foo(
i1: I?,
i2: I?,
s1: String,
s2: String,
c1: C,
c2: C,
i: Int,
o1: O,
o2: O,
e1: E,
e2: E,
bb1: BB,
bb2: BB,
arr1: IntArray,
arr2: IntArray,
ee1: EE?,
ee2: EE
) {
if (i1 === i2) return
if (s1 === s2) return
if (c1 == c2) return
if (i1 == null) return
if (null == i2) return
if (i == 0) return
if (o1 === o2) return
if (e1 === e2) return
if (bb1 === bb2) return
if (arr1 == arr2) return
if (ee1 == ee2 || ee1 == null) return
if (s1 !== s2) return
if (c1 != c2) return
}
}
| plugins/kotlin/j2k/new/tests/testData/newJ2k/equals/EqOperator.kt | 3799474498 |
import org.junit.Rule
import org.junit.rules.ExpectedException
import kotlin.test.Test
import kotlin.test.assertEquals
class DominoesTest {
@Test
fun `empty input = empty output`() = Dominoes.formChain().should { haveSize(0) }
@Test
fun `singleton input = singleton output`() {
val input = listOf(Domino(1, 1))
Dominoes.formChain(input).should { beValidDominoes(input) }
}
@Test(ChainNotFoundException::class)
fun `singleton can't be chained`() {
Dominoes.formChain(Domino(1, 2))
}
@Test
fun `three elements`() {
val input = listOf(Domino(1, 2), Domino(3, 1), Domino(2, 3))
Dominoes.formChain(input).should { beValidDominoes(input) }
}
@Test
fun `can reverse dominoes`() {
val input = listOf(Domino(1, 2), Domino(1, 3), Domino(2, 3))
Dominoes.formChain(input).should { beValidDominoes(input) }
}
@Test(expected = ChainNotFoundException::class)
fun `can't be chained`() {
Dominoes.formChain(Domino(1, 2), Domino(4, 1), Domino(2, 3))
}
@Test(expected = ChainNotFoundException::class)
fun `disconnected - simple`() {
Dominoes.formChain(Domino(1, 1), Domino(2, 2))
}
@Test(expected = ChainNotFoundException::class)
fun `disconnected - double loop`() {
Dominoes.formChain(Domino(1, 2), Domino(2, 1), Domino(3, 4), Domino(4, 3))
}
@Test(expected = ChainNotFoundException::class)
fun `disconnected - single isolated`() {
Dominoes.formChain(Domino(1, 2), Domino(2, 3), Domino(3, 1), Domino(4, 4))
}
@Test
fun `need backtrack`() {
val input = listOf(
Domino(1, 2),
Domino(2, 3),
Domino(3, 1),
Domino(2, 4),
Domino(4, 2))
Dominoes.formChain(input).should { beValidDominoes(input) }
}
@Test
fun `separate loops`() {
val input = listOf(
Domino(1, 2),
Domino(2, 3),
Domino(3, 1),
Domino(1, 1),
Domino(2, 2),
Domino(3, 3))
Dominoes.formChain(input).should { beValidDominoes(input) }
}
@Test
fun `nine elements`() {
val input = listOf(
Domino(1, 2),
Domino(5, 3),
Domino(3, 1),
Domino(1, 2),
Domino(2, 4),
Domino(1, 6),
Domino(2, 3),
Domino(3, 4),
Domino(5, 6))
Dominoes.formChain(input).should { beValidDominoes(input) }
}
private fun List<Domino>.should(what: DominoListAsserter.() -> Unit) = what(DominoListAsserter(this))
private class DominoListAsserter(private val outputDominoes: List<Domino>) {
fun haveSize(n: Int) = assertEquals(n, outputDominoes.size)
fun beValidDominoes(inputDominoes: List<Domino>) {
haveSameDominoesAs(inputDominoes)
haveMatchingEnds()
haveConsecutiveDominoes()
}
private fun haveSameDominoesAs(inputDominoes: List<Domino>) {
val errorMessage = "The number of dominoes in the input list (${inputDominoes.size}) needs to match the number of dominoes in the output chain (${outputDominoes.size})"
assertEquals(inputDominoes.size, outputDominoes.size, errorMessage)
inputDominoes.forEach { domino ->
val inputFrequency: Int = dominoFrequency(inputDominoes, domino)
val outputFrequency: Int = dominoFrequency(outputDominoes, domino)
val frequencyErrorMessage = "The frequency of domino (${domino.left}, ${domino.right}) in the input is ($inputFrequency), but ($outputFrequency) in the output."
assertEquals(inputFrequency, outputFrequency, frequencyErrorMessage)
}
}
private fun haveMatchingEnds() {
val leftValueOfFirstDomino = outputDominoes.first().left
val rightValueOfLastDomino = outputDominoes.last().right
val errorMessage = "The left value of the first domino ($leftValueOfFirstDomino) needs to match the right value of the last domino ($rightValueOfLastDomino)."
assertEquals(leftValueOfFirstDomino, rightValueOfLastDomino, errorMessage)
}
private fun haveConsecutiveDominoes() {
(0 until outputDominoes.size - 1).forEach { i ->
val rightValueOfIthDomino = outputDominoes[i].right
val leftValueOfNextDomino = outputDominoes[i + 1].left
val errorMessage = "The right value of domino number $i ($rightValueOfIthDomino) needs to match the left value of domino number ${i + 1} ($leftValueOfNextDomino)."
assertEquals(outputDominoes[i].right, outputDominoes[i + 1].left, errorMessage)
}
}
private fun dominoFrequency(list: List<Domino>, d: Domino) =
list.count {
(it.left == d.left && it.right == d.right) || (it.left == d.right && it.right == d.left)
}
}
}
| exercises/practice/dominoes/src/test/kotlin/DominoesTest.kt | 141008761 |
package org.stepik.android.view.course_info.mapper
import android.content.Context
import androidx.annotation.StringRes
import org.stepic.droid.R
import org.stepik.android.domain.course_info.model.CourseInfoData
import org.stepik.android.view.course_info.model.CourseInfoItem
import org.stepik.android.view.course_info.model.CourseInfoType
private const val NEW_LINE = "<br/>"
fun CourseInfoData.toSortedItems(context: Context): List<CourseInfoItem> {
val items = arrayListOf<CourseInfoItem>()
if (summary != null) {
items.add(CourseInfoItem.SummaryBlock(summary))
}
if (authors != null) {
items.add(CourseInfoItem.AuthorsBlock(authors))
}
if (videoMediaData != null) {
items.add(CourseInfoItem.VideoBlock(videoMediaData))
}
if (acquiredSkills != null && acquiredSkills.isNotEmpty()) {
items.add(CourseInfoItem.Skills(acquiredSkills))
}
if (about != null) {
items.add(CourseInfoItem.AboutBlock(about))
}
items.addTextItem(CourseInfoType.REQUIREMENTS, requirements)
items.addTextItem(CourseInfoType.TARGET_AUDIENCE, targetAudience)
if (timeToComplete > 0) {
val hours = (timeToComplete / 3600).toInt()
items.addTextItem(CourseInfoType.TIME_TO_COMPLETE, context.resources.getQuantityString(R.plurals.hours, hours, hours))
}
if (instructors != null) {
items.add(CourseInfoItem.WithTitle.InstructorsBlock(instructors))
}
items.addTextItem(CourseInfoType.LANGUAGE, mapCourseLanguage(language)?.let(context::getString))
if (certificate != null) {
items.addTextItem(CourseInfoType.CERTIFICATE, certificate.title.ifEmpty { context.getString(R.string.certificate_issuing) })
val certificateConditions = mutableListOf<String>()
if (certificate.regularThreshold > 0) {
val regularPoints = context.resources.getQuantityString(R.plurals.points, certificate.regularThreshold.toInt(), certificate.regularThreshold)
val regularCondition = context.getString(R.string.course_info_certificate_regular, regularPoints)
certificateConditions.add(regularCondition)
}
if (certificate.distinctionThreshold > 0) {
val distinctionPoints = context.resources.getQuantityString(R.plurals.points, certificate.distinctionThreshold.toInt(), certificate.distinctionThreshold)
val distinctionCondition = context.getString(R.string.course_info_certificate_distinction, distinctionPoints)
certificateConditions.add(distinctionCondition)
}
items.addTextItem(CourseInfoType.CERTIFICATE_DETAILS, certificateConditions.joinToString(NEW_LINE))
} else {
items.addTextItem(CourseInfoType.CERTIFICATE, context.getString(R.string.certificate_not_issuing))
}
if (learnersCount > 0) {
items.addTextItem(CourseInfoType.LEARNERS_COUNT, learnersCount.toString())
}
return items
}
private fun MutableList<CourseInfoItem>.addTextItem(type: CourseInfoType, text: String?) {
if (text != null) {
add(CourseInfoItem.WithTitle.TextBlock(type, text))
}
}
@StringRes
private fun mapCourseLanguage(language: String?): Int? =
when (language) {
"ru" -> R.string.course_info_language_ru
"en" -> R.string.course_info_language_en
"de" -> R.string.course_info_language_de
"es" -> R.string.course_info_language_es
"ua" -> R.string.course_info_language_ua
"ch" -> R.string.course_info_language_ch
else -> null
} | app/src/main/java/org/stepik/android/view/course_info/mapper/CourseInfoMapper.kt | 2207345022 |
object PrimeFactorCalculator {
fun primeFactors(int: Int): List<Int> {
TODO("Implement this function to complete the task")
}
fun primeFactors(long: Long): List<Long> {
TODO("Implement this function to complete the task")
}
}
| exercises/practice/prime-factors/src/main/kotlin/PrimeFactors.kt | 1066929423 |
// 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 com.intellij.ide.browsers
import com.intellij.ide.highlighter.XmlFileType
import com.intellij.lang.Language
import com.intellij.lang.html.HTMLLanguage
import com.intellij.lang.xhtml.XHTMLLanguage
import com.intellij.lang.xml.XMLLanguage
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.xml.util.HtmlUtil
class WebBrowserXmlServiceImpl : WebBrowserXmlService() {
override fun isHtmlFile(element: PsiElement): Boolean {
return HtmlUtil.isHtmlFile(element)
}
override fun isHtmlFile(file: VirtualFile): Boolean {
return HtmlUtil.isHtmlFile(file)
}
override fun isHtmlOrXmlFile(psiFile: PsiFile): Boolean {
if (!isHtmlFile(psiFile.virtualFile) && psiFile.virtualFile.fileType != XmlFileType.INSTANCE) {
return false
}
val baseLanguage: Language = psiFile.viewProvider.baseLanguage
if (isHtmlOrXmlLanguage(baseLanguage)) {
return true
}
return if (psiFile.fileType is LanguageFileType) {
isHtmlOrXmlLanguage((psiFile.fileType as LanguageFileType).language)
}
else false
}
override fun isXmlLanguage(language: Language): Boolean {
return language == XMLLanguage.INSTANCE
}
override fun isHtmlOrXmlLanguage(language: Language): Boolean {
return language.isKindOf(HTMLLanguage.INSTANCE)
|| language === XHTMLLanguage.INSTANCE
|| language === XMLLanguage.INSTANCE
}
} | xml/impl/src/com/intellij/ide/browsers/WebBrowserXmlServiceImpl.kt | 1875444603 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jetbrains.python.sdk.add
import com.intellij.CommonBundle
import com.intellij.ide.IdeBundle
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.module.Module
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.util.text.StringUtil
import com.jetbrains.python.PySdkBundle
import com.jetbrains.python.newProject.steps.PyAddNewEnvironmentPanel
import com.jetbrains.python.sdk.*
import com.jetbrains.python.sdk.add.PyAddSdkDialogFlowAction.OK
import com.jetbrains.python.sdk.configuration.PyProjectVirtualEnvConfiguration
import icons.PythonIcons
import java.awt.Component
import java.io.File
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.JPanel
/**
* @author vlan
*/
abstract class PyAddSdkPanel : JPanel(), PyAddSdkView {
override val actions: Map<PyAddSdkDialogFlowAction, Boolean>
get() = mapOf(OK.enabled())
override val component: Component
get() = this
/**
* [component] is permanent. [PyAddSdkStateListener.onComponentChanged] won't
* be called anyway.
*/
override fun addStateListener(stateListener: PyAddSdkStateListener): Unit = Unit
override fun previous(): Nothing = throw UnsupportedOperationException()
override fun next(): Nothing = throw UnsupportedOperationException()
override fun complete(): Unit = Unit
abstract override val panelName: String
override val icon: Icon = PythonIcons.Python.Python
open val sdk: Sdk? = null
open val nameExtensionComponent: JComponent? = null
open var newProjectPath: String? = null
override fun getOrCreateSdk(): Sdk? = sdk
override fun onSelected(): Unit = Unit
override fun validateAll(): List<ValidationInfo> = emptyList()
open fun addChangeListener(listener: Runnable) {}
companion object {
@JvmStatic
fun validateEnvironmentDirectoryLocation(field: TextFieldWithBrowseButton): ValidationInfo? {
val text = field.text
val file = File(text)
val message = when {
StringUtil.isEmptyOrSpaces(text) -> PySdkBundle.message("python.venv.location.field.empty")
file.exists() && !file.isDirectory -> PySdkBundle.message("python.venv.location.field.not.directory")
file.isNotEmptyDirectory -> PySdkBundle.message("python.venv.location.directory.not.empty")
else -> return null
}
return ValidationInfo(message, field)
}
@JvmStatic
protected fun validateSdkComboBox(field: PySdkPathChoosingComboBox, view: PyAddSdkView): ValidationInfo? {
return validateSdkComboBox(field, getDefaultButtonName(view))
}
@JvmStatic
fun validateSdkComboBox(field: PySdkPathChoosingComboBox, @NlsContexts.Button defaultButtonName: String): ValidationInfo? {
return when (val sdk = field.selectedSdk) {
null -> ValidationInfo(PySdkBundle.message("python.sdk.field.is.empty"), field)
is PySdkToInstall -> {
val message = sdk.getInstallationWarning(defaultButtonName)
ValidationInfo(message).asWarning().withOKEnabled()
}
else -> null
}
}
@NlsContexts.Button
private fun getDefaultButtonName(view: PyAddSdkView): String {
return if (view.component.parent?.parent is PyAddNewEnvironmentPanel) {
IdeBundle.message("new.dir.project.create") // ProjectSettingsStepBase.createActionButton
}
else {
CommonBundle.getOkButtonText() // DialogWrapper.createDefaultActions
}
}
}
}
/**
* Obtains a list of sdk on a pool using [sdkObtainer], then fills [sdkComboBox] on the EDT.
*/
fun addInterpretersAsync(sdkComboBox: PySdkPathChoosingComboBox, sdkObtainer: () -> List<Sdk>) {
addInterpretersAsync(sdkComboBox, sdkObtainer, {})
}
/**
* Obtains a list of sdk on a pool using [sdkObtainer], then fills [sdkComboBox] and calls [onAdded] on the EDT.
*/
fun addInterpretersAsync(sdkComboBox: PySdkPathChoosingComboBox,
sdkObtainer: () -> List<Sdk>,
onAdded: () -> Unit) {
ApplicationManager.getApplication().executeOnPooledThread {
val executor = AppUIExecutor.onUiThread(ModalityState.any())
executor.execute { sdkComboBox.setBusy(true) }
var sdks = emptyList<Sdk>()
try {
sdks = sdkObtainer()
}
finally {
executor.execute {
sdkComboBox.setBusy(false)
sdks.forEach(sdkComboBox.childComponent::addItem)
onAdded()
}
}
}
}
/**
* Obtains a list of sdk to be used as a base for a virtual environment on a pool,
* then fills the [sdkComboBox] on the EDT and chooses [PySdkSettings.preferredVirtualEnvBaseSdk] or prepends it.
*/
fun addBaseInterpretersAsync(sdkComboBox: PySdkPathChoosingComboBox,
existingSdks: List<Sdk>,
module: Module?,
context: UserDataHolder,
callback: () -> Unit = {}) {
addInterpretersAsync(
sdkComboBox,
{ findBaseSdks(existingSdks, module, context).takeIf { it.isNotEmpty() } ?: getSdksToInstall() },
{
sdkComboBox.apply {
val preferredSdk = PyProjectVirtualEnvConfiguration.findPreferredVirtualEnvBaseSdk(items)
if (preferredSdk != null) {
if (items.find { it.homePath == preferredSdk.homePath } == null) {
childComponent.insertItemAt(preferredSdk, 0)
}
selectedSdk = preferredSdk
}
}
callback()
}
)
}
| python/src/com/jetbrains/python/sdk/add/PyAddSdkPanel.kt | 808258222 |
package com.aemtools.test.fix
import com.aemtools.common.util.writeCommand
import com.aemtools.test.base.BaseLightTest
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.openapi.application.runWriteAction
import junit.framework.TestCase
import org.intellij.lang.annotations.Language
/**
* @author Dmytro Troynikov
*/
abstract class BaseFixTest : BaseLightTest() {
fun fixTest(fixDsl: QuickFixDsl.() -> Unit) {
val fix = QuickFixDsl().apply(fixDsl)
myFixture.configureByText(
fix.before!!.name,
fix.before!!.content
)
myFixture.enableInspections(
fix.inspection!!
)
val intentionAction = myFixture
.getAvailableIntention(fix.fixName!!)
TestCase.assertNotNull(intentionAction)
myFixture.launchAction(intentionAction!!)
myFixture.checkResult(fix.after!!.content)
}
fun annotationFixTest(annotatorFixDsl: AnnotatorFixDsl.() -> Unit) {
val fix = AnnotatorFixDsl().apply(annotatorFixDsl)
myFixture.configureByText(
fix.before!!.name,
fix.before!!.content
)
val quickFix = myFixture.getAllQuickFixes(fix.before!!.name)
.find { it.text == fix.fixName }
?: throw AssertionError("Unable to find quick fix with name: ${fix.fixName}")
writeCommand(project) {
quickFix.invoke(project, editor, myFixture.file)
}
myFixture.checkResult(fix.after!!.content)
}
}
data class FileDescriptor(
val name: String,
val content: String
)
class QuickFixDsl {
var inspection: Class<out LocalInspectionTool>? = null
var fixName: String? = null
var before: FileDescriptor? = null
var after: FileDescriptor? = null
fun html(name: String, @Language("HTML") text: String) =
FileDescriptor(name, text)
}
class AnnotatorFixDsl {
var fixName: String? = null
var before: FileDescriptor? = null
var after: FileDescriptor? = null
fun html(name: String, @Language("HTML") text: String) =
FileDescriptor(name, text)
}
| test-framework/src/main/kotlin/com/aemtools/test/fix/BaseFixTest.kt | 723895593 |
package customProperties
import codecProvider.CustomCodingContext
import customProperties.differentPackage.writeCustomProperties3
import customProperties.writeCustomProperties2
import io.fluidsonic.json.AbstractJsonCodec
import io.fluidsonic.json.JsonCodingType
import io.fluidsonic.json.JsonDecoder
import io.fluidsonic.json.JsonEncoder
import io.fluidsonic.json.missingPropertyError
import io.fluidsonic.json.readBooleanOrNull
import io.fluidsonic.json.readByteOrNull
import io.fluidsonic.json.readCharOrNull
import io.fluidsonic.json.readDoubleOrNull
import io.fluidsonic.json.readFloatOrNull
import io.fluidsonic.json.readFromMapByElementValue
import io.fluidsonic.json.readIntOrNull
import io.fluidsonic.json.readLongOrNull
import io.fluidsonic.json.readShortOrNull
import io.fluidsonic.json.readStringOrNull
import io.fluidsonic.json.readValueOfType
import io.fluidsonic.json.readValueOfTypeOrNull
import io.fluidsonic.json.writeBooleanOrNull
import io.fluidsonic.json.writeByteOrNull
import io.fluidsonic.json.writeCharOrNull
import io.fluidsonic.json.writeDoubleOrNull
import io.fluidsonic.json.writeFloatOrNull
import io.fluidsonic.json.writeIntOrNull
import io.fluidsonic.json.writeIntoMap
import io.fluidsonic.json.writeLongOrNull
import io.fluidsonic.json.writeMapElement
import io.fluidsonic.json.writeShortOrNull
import io.fluidsonic.json.writeStringOrNull
import io.fluidsonic.json.writeValueOrNull
import kotlin.String
import kotlin.Unit
internal object DifferentPackageJsonCodec :
AbstractJsonCodec<DifferentPackage, CustomCodingContext>() {
public override
fun JsonDecoder<CustomCodingContext>.decode(valueType: JsonCodingType<DifferentPackage>):
DifferentPackage {
var _value: String? = null
readFromMapByElementValue { key ->
when (key) {
"value" -> _value = readString()
else -> skipValue()
}
}
return DifferentPackage(
`value` = _value ?: missingPropertyError("value")
)
}
public override fun JsonEncoder<CustomCodingContext>.encode(`value`: DifferentPackage): Unit {
writeIntoMap {
writeMapElement("value", string = value.`value`)
value.run { [email protected]() }
writeCustomProperties2(value)
writeCustomProperties3(value)
}
}
}
| annotation-processor/test-cases/1/output-expected/customProperties/DifferentPackageJsonCodec.kt | 2597640256 |
/*
* (C) Copyright 2020 Lukas Morawietz (https://github.com/F43nd1r)
*
* 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.faendir.acra.ui.component.grid
import com.faendir.acra.dataprovider.QueryDslDataProvider
import com.faendir.acra.dataprovider.QueryDslFilter
import com.faendir.acra.i18n.Messages
import com.faendir.acra.settings.GridSettings
import com.querydsl.jpa.impl.JPAQuery
import com.vaadin.flow.component.Component
import com.vaadin.flow.component.grid.ItemClickEvent
import com.vaadin.flow.component.icon.VaadinIcon
import com.vaadin.flow.data.renderer.Renderer
import com.vaadin.flow.router.RouteParameters
/**
* @author lukas
* @since 13.07.18
*/
class QueryDslAcrariumGrid<T>(val dataProvider: QueryDslDataProvider<T>, var gridSettings: GridSettings? = null) :
AbstractAcrariumGrid<T, QueryDslAcrariumColumn<T>>() {
override val columnFactory: (Renderer<T>, String) -> QueryDslAcrariumColumn<T> = { renderer, id -> QueryDslAcrariumColumn(this, renderer, id) }
val acrariumColumns: List<QueryDslAcrariumColumn<T>>
get() = super.getColumns().filterIsInstance<QueryDslAcrariumColumn<T>>()
init {
dataCommunicator.setDataProvider(dataProvider, object : QueryDslFilter {
override fun <T> apply(query: JPAQuery<T>): JPAQuery<T> = acrariumColumns.mapNotNull { it.filter }.fold(query) { q, f -> f.apply(q) }
})
setSizeFull()
isMultiSort = true
isColumnReorderingAllowed = true
}
/**
* call when all columns were added
*/
fun loadLayout() {
gridSettings?.apply {
val orderedColumns = columnOrder.mapNotNull { key -> acrariumColumns.find { it.key == key } }
val unorderedColumns = acrariumColumns - orderedColumns
setColumnOrder(orderedColumns + unorderedColumns)
hiddenColumns.forEach { key -> acrariumColumns.find { it.key == key }?.isVisible = false }
}
}
fun addOnLayoutChangedListener(listener: (gridSettings: GridSettings) -> Unit) {
addColumnReorderListener { event ->
val settings = GridSettings(event.columns.mapNotNull { it.key }, gridSettings?.hiddenColumns ?: emptyList())
gridSettings = settings
listener(settings)
}
acrariumColumns.forEach { column ->
column.addVisibilityChangeListener {
val settings = GridSettings(gridSettings?.columnOrder ?: columns.mapNotNull { it.key }, columns.filter { !it.isVisible }.mapNotNull { it.key })
gridSettings = settings
listener(settings)
}
}
}
fun addOnClickNavigation(target: Class<out Component>, getParameters: (T) -> Map<String, String>) {
addItemClickListener { e: ItemClickEvent<T> ->
ui.ifPresent { it.navigate(target, RouteParameters(getParameters(e.item))) }
}
column(RouteButtonRenderer(VaadinIcon.EXTERNAL_LINK, target, getParameters)) {
setCaption(Messages.OPEN)
isAutoWidth = false
width = "100px"
}
}
} | acrarium/src/main/kotlin/com/faendir/acra/ui/component/grid/QueryDslAcrariumGrid.kt | 138353530 |
package net.ofk.kotlinantbug
class Caller(private val kab: KotlinAntBug) {
fun call() {
kab.method()
}
} | src/main/kotlin/net/ofk/kotlinantbug/Caller.kt | 3258991409 |
package pl.edu.amu.wmi.erykandroidcommon.recycler.select
import android.view.View
import android.widget.RadioButton
import pl.edu.amu.wmi.erykandroidcommon.recycler.AbstractViewHolder
/**
* @author Eryk Mariankowski <eryk.mariankowski></eryk.mariankowski>@247.codes> on 31.08.17.
*/
abstract class SelectItemViewHolder<T : Any>(itemView: View) : AbstractViewHolder<T>(itemView) {
var radio: RadioButton? = null
init {
// radio = itemView.radio
}
abstract fun bind(item: T)
}
| src/main/java/pl/edu/amu/wmi/erykandroidcommon/recycler/select/SelectItemViewHolder.kt | 2705961621 |
package jetbrains.buildServer.dotnet
data class MSBuildParameter(val name: String, val value: String) | plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/dotnet/MSBuildParameter.kt | 3394211025 |
/*
* Copyright 2015 Yann Le Moigne
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.javatic.reactkt.core
import fr.javatic.reactkt.core.binding.InternalReactDOM
import org.w3c.dom.Element
object ReactDOM {
fun render(element: ReactElement, container: Element, callback: (() -> Unit)? = null) = InternalReactDOM.render(element, container, callback)
fun <T:Element> findDOMNode(component: ReactElement?): T? = InternalReactDOM.findDOMNode(component)
} | subprojects/core/src/main/kotlin/fr/javatic/reactkt/core/ReactDOM.kt | 1090479913 |
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines
/**
* Thrown by cancellable suspending functions if the [Job] of the coroutine is cancelled while it is suspending.
* It indicates _normal_ cancellation of a coroutine.
* **It is not printed to console/log by default uncaught exception handler**.
* (see [CoroutineExceptionHandler]).
*/
public actual typealias CancellationException = kotlin.coroutines.cancellation.CancellationException
/**
* Thrown by cancellable suspending functions if the [Job] of the coroutine is cancelled or completed
* without cause, or with a cause or exception that is not [CancellationException]
* (see [Job.getCancellationException]).
*/
internal actual class JobCancellationException public actual constructor(
message: String,
cause: Throwable?,
internal actual val job: Job
) : CancellationException(message, cause) {
override fun toString(): String = "${super.toString()}; job=$job"
override fun equals(other: Any?): Boolean =
other === this ||
other is JobCancellationException && other.message == message && other.job == job && other.cause == cause
override fun hashCode(): Int =
(message!!.hashCode() * 31 + job.hashCode()) * 31 + (cause?.hashCode() ?: 0)
}
@Suppress("NOTHING_TO_INLINE")
internal actual inline fun Throwable.addSuppressedThrowable(other: Throwable) { /* empty */ }
// For use in tests
internal actual val RECOVER_STACK_TRACES: Boolean = false
| kotlinx-coroutines-core/js/src/Exceptions.kt | 1074508605 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.build.output
import com.intellij.build.FilePosition
import com.intellij.build.events.BuildEvent
import com.intellij.build.events.MessageEvent
import com.intellij.build.events.impl.FileMessageEventImpl
import com.intellij.build.events.impl.MessageEventImpl
import com.intellij.openapi.util.text.StringUtil
import java.io.File
import java.util.function.Consumer
import java.util.regex.Matcher
import java.util.regex.Pattern
/**
* Parses kotlinc's output.
*/
class KotlincOutputParser : BuildOutputParser {
companion object {
private const val COMPILER_MESSAGES_GROUP = "Kotlin compiler"
}
override fun parse(line: String, reader: BuildOutputInstantReader, consumer: Consumer<in BuildEvent>): Boolean {
val colonIndex1 = line.colon()
val severity = if (colonIndex1 >= 0) line.substringBeforeAndTrim(colonIndex1) else return false
if (!severity.startsWithSeverityPrefix()) return false
val lineWoSeverity = line.substringAfterAndTrim(colonIndex1)
val colonIndex2 = lineWoSeverity.colon().skipDriveOnWin(lineWoSeverity)
if (colonIndex2 < 0) return false
val path = lineWoSeverity.substringBeforeAndTrim(colonIndex2)
val file = File(path)
val fileExtension = file.extension.toLowerCase()
if (!file.isFile || (fileExtension != "kt" && fileExtension != "kts" && fileExtension != "java")) {
return addMessage(createMessage(reader.parentEventId, getMessageKind(severity), lineWoSeverity.amendNextLinesIfNeeded(reader), line),
consumer)
}
val lineWoPath = lineWoSeverity.substringAfterAndTrim(colonIndex2)
var lineWoPositionIndex = -1
var matcher: Matcher? = null
if (lineWoPath.startsWith('(')) {
val colonIndex3 = lineWoPath.colon()
if (colonIndex3 >= 0) {
lineWoPositionIndex = colonIndex3
}
if (lineWoPositionIndex >= 0) {
val position = lineWoPath.substringBeforeAndTrim(lineWoPositionIndex)
matcher = KOTLIN_POSITION_PATTERN.matcher(position).takeIf { it.matches() } ?: JAVAC_POSITION_PATTERN.matcher(position)
}
}
else {
val colonIndex4 = lineWoPath.colon(1)
if (colonIndex4 >= 0) {
lineWoPositionIndex = colonIndex4
}
else {
lineWoPositionIndex = lineWoPath.colon()
}
if (lineWoPositionIndex >= 0) {
val position = lineWoPath.substringBeforeAndTrim(colonIndex4)
matcher = LINE_COLON_COLUMN_POSITION_PATTERN.matcher(position).takeIf { it.matches() } ?: JAVAC_POSITION_PATTERN.matcher(position)
}
}
if (lineWoPositionIndex >= 0) {
val relatedNextLines = "".amendNextLinesIfNeeded(reader)
val message = lineWoPath.substringAfterAndTrim(lineWoPositionIndex) + relatedNextLines
val details = line + relatedNextLines
if (matcher != null && matcher.matches()) {
val lineNumber = matcher.group(1)
val symbolNumber = if (matcher.groupCount() >= 2) matcher.group(2) else "1"
if (lineNumber != null) {
val symbolNumberText = symbolNumber.toInt()
return addMessage(createMessageWithLocation(
reader.parentEventId, getMessageKind(severity), message, path, lineNumber.toInt(), symbolNumberText, details), consumer)
}
}
return addMessage(createMessage(reader.parentEventId, getMessageKind(severity), message, details), consumer)
}
else {
val text = lineWoSeverity.amendNextLinesIfNeeded(reader)
return addMessage(createMessage(reader.parentEventId, getMessageKind(severity), text, text), consumer)
}
}
private val COLON = ":"
private val KOTLIN_POSITION_PATTERN = Pattern.compile("\\(([0-9]*), ([0-9]*)\\)")
private val JAVAC_POSITION_PATTERN = Pattern.compile("([0-9]+)")
private val LINE_COLON_COLUMN_POSITION_PATTERN = Pattern.compile("([0-9]*):([0-9]*)")
private fun String.amendNextLinesIfNeeded(reader: BuildOutputInstantReader): String {
var nextLine = reader.readLine()
val builder = StringBuilder(this)
while (nextLine != null) {
if (nextLine.isNextMessage()) {
reader.pushBack()
break
}
else {
builder.append("\n").append(nextLine)
nextLine = reader.readLine()
}
}
return builder.toString()
}
private fun String.isNextMessage(): Boolean {
val colonIndex1 = indexOf(COLON)
return colonIndex1 == 0
|| (colonIndex1 >= 0 && substring(0, colonIndex1).startsWithSeverityPrefix()) // Next Kotlin message
|| StringUtil.startsWith(this, "Note: ") // Next javac info message candidate
|| StringUtil.startsWith(this, "> Task :") // Next gradle message candidate
|| StringUtil.containsIgnoreCase(this, "FAILURE")
|| StringUtil.containsIgnoreCase(this, "FAILED")
}
private fun String.startsWithSeverityPrefix() = getMessageKind(this) != MessageEvent.Kind.SIMPLE
private fun getMessageKind(kind: String) = when (kind) {
"e" -> MessageEvent.Kind.ERROR
"w" -> MessageEvent.Kind.WARNING
"i" -> MessageEvent.Kind.INFO
"v" -> MessageEvent.Kind.SIMPLE
else -> MessageEvent.Kind.SIMPLE
}
private fun String.substringAfterAndTrim(index: Int) = substring(index + 1).trim()
private fun String.substringBeforeAndTrim(index: Int) = substring(0, index).trim()
private fun String.colon() = indexOf(COLON)
private fun String.colon(skip: Int): Int {
var index = -1
repeat(skip + 1) {
index = indexOf(COLON, index + 1)
if (index < 0) return index
}
return index
}
private fun Int.skipDriveOnWin(line: String): Int {
return if (this == 1) line.indexOf(COLON, this + 1) else this
}
private val KAPT_ERROR_WHILE_ANNOTATION_PROCESSING_MARKER_TEXT =
// KaptError::class.java.canonicalName + ": " + KaptError.Kind.ERROR_RAISED.message
"org.jetbrains.kotlin.kapt3.diagnostic.KaptError" + ": " + "Error while annotation processing"
private fun isKaptErrorWhileAnnotationProcessing(message: MessageEvent): Boolean {
if (message.kind != MessageEvent.Kind.ERROR) return false
val messageText = message.message
return messageText.startsWith(IllegalStateException::class.java.name)
&& messageText.contains(KAPT_ERROR_WHILE_ANNOTATION_PROCESSING_MARKER_TEXT)
}
private fun addMessage(message: MessageEvent, consumer: Consumer<in MessageEvent>): Boolean {
// Ignore KaptError.ERROR_RAISED message from kapt. We already processed all errors from annotation processing
if (isKaptErrorWhileAnnotationProcessing(message)) return true
consumer.accept(message)
return true
}
private fun createMessage(parentId: Any, messageKind: MessageEvent.Kind, text: String, detail: String): MessageEvent {
return MessageEventImpl(parentId, messageKind, COMPILER_MESSAGES_GROUP, text.trim(), detail)
}
private fun createMessageWithLocation(
parentId: Any,
messageKind: MessageEvent.Kind,
text: String,
file: String,
lineNumber: Int,
columnIndex: Int,
detail: String
): FileMessageEventImpl {
return FileMessageEventImpl(parentId, messageKind, COMPILER_MESSAGES_GROUP, text.trim(), detail,
FilePosition(File(file), lineNumber - 1, columnIndex - 1))
}
} | platform/lang-impl/src/com/intellij/build/output/KotlincOutputParser.kt | 3036730300 |
package com.dbflow5.query
import android.content.ContentValues
import com.dbflow5.addContentValues
import com.dbflow5.sql.Query
import com.dbflow5.structure.ChangeAction
/**
* Description: Used to specify the SET part of an [com.dbflow5.query.Update] query.
*/
class Set<T : Any> internal constructor(
override val queryBuilderBase: Query, table: Class<T>)
: BaseTransformable<T>(table), WhereBase<T> {
private val operatorGroup: OperatorGroup = OperatorGroup.nonGroupingClause().setAllCommaSeparated(true)
override val query: String
get() = " ${queryBuilderBase.query}SET ${operatorGroup.query} "
override val primaryAction: ChangeAction
get() = ChangeAction.UPDATE
/**
* Specifies a varg of conditions to append to this SET
*
* @param conditions The varg of conditions
* @return This instance.
*/
fun conditions(vararg conditions: SQLOperator) = apply {
operatorGroup.andAll(*conditions)
}
/**
* Specifies a varg of conditions to append to this SET
*
* @param condition The varg of conditions
* @return This instance.
*/
infix fun and(condition: SQLOperator) = apply {
operatorGroup.and(condition)
}
fun conditionValues(contentValues: ContentValues) = apply {
addContentValues(contentValues, operatorGroup)
}
override fun cloneSelf(): Set<T> {
val set = Set(
when (queryBuilderBase) {
is Update<*> -> queryBuilderBase.cloneSelf()
else -> queryBuilderBase
}, table)
set.operatorGroup.andAll(operatorGroup.conditions)
return set
}
}
| lib/src/main/kotlin/com/dbflow5/query/Set.kt | 2575091410 |
package slatekit.utils.display
import slatekit.utils.writer.ConsoleWriter
import slatekit.common.envs.Envs
import slatekit.common.info.Info
import slatekit.common.log.LogSupport
import slatekit.common.log.Logger
open class Banner(val info: Info,
val envs: Envs,
override val logger: Logger?) : LogSupport {
/**
* Shows the welcome header
*/
open fun welcome() {
// Basic welcome
val writer = ConsoleWriter()
writer.text("************************************")
writer.title("Welcome to ${info.about.name}")
writer.text("************************************")
writer.line()
writer.text("starting in environment: " + this.envs.key)
}
/**
* Displays diagnostic info about the app and process
*/
open fun display() {
val maxLen = Math.max(0, "lang.versionNum ".length)
info("app.area ".padEnd(maxLen) + info.about.area)
info("app.name ".padEnd(maxLen) + info.about.name)
info("app.desc ".padEnd(maxLen) + info.about.desc)
info("app.tags ".padEnd(maxLen) + info.about.tags)
info("app.region ".padEnd(maxLen) + info.about.region)
info("app.contact ".padEnd(maxLen) + info.about.contact)
info("app.url ".padEnd(maxLen) + info.about.url)
info("build.version ".padEnd(maxLen) + info.build.version)
info("build.commit ".padEnd(maxLen) + info.build.commit)
info("build.date ".padEnd(maxLen) + info.build.date)
info("host.name ".padEnd(maxLen) + info.host.name)
info("host.ip ".padEnd(maxLen) + info.host.ip)
info("host.origin ".padEnd(maxLen) + info.host.origin)
info("host.version ".padEnd(maxLen) + info.host.version)
info("lang.name ".padEnd(maxLen) + info.lang.name)
info("lang.version ".padEnd(maxLen) + info.lang.version)
info("lang.versionNum ".padEnd(maxLen) + info.lang.vendor)
info("lang.java ".padEnd(maxLen) + info.lang.origin)
info("lang.home ".padEnd(maxLen) + info.lang.home)
}
/**
* prints the summary at the end of the application run
*/
open fun summary() {
info("===============================================================")
info("SUMMARY : ")
info("===============================================================")
// Standardized info
// e.g. name, desc, env, log, start-time etc.
extra().forEach { info(it.first + " = " + it.second) }
info("===============================================================")
}
/**
* Collection of results executing this application which can be used to display
* at the end of the application
*/
open fun extra(): List<Pair<String, String>> {
return listOf()
}
}
| src/lib/kotlin/slatekit-utils/src/main/kotlin/slatekit/utils/display/Banner.kt | 3356039944 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.slicer
import com.intellij.analysis.AnalysisScope
import com.intellij.codeInsight.daemon.DaemonAnalyzerTestCase
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.impl.ToolWindowHeadlessManagerImpl
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiLiteralExpression
import com.intellij.slicer.*
import com.intellij.testFramework.UsefulTestCase
import junit.framework.TestCase
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
import org.jetbrains.plugins.groovy.slicer.GroovySliceProvider
import org.jetbrains.plugins.groovy.util.TestUtils
class GroovySliceTreeGroupingTest : DaemonAnalyzerTestCase() {
override fun getTestProjectJdk() = null
override fun getTestDataPath() = TestUtils.getAbsoluteTestDataPath() + "slicer/tree/"
private fun loadTreeStructure(getTestFiles: (baseName: String) -> List<String> = { listOf("$it.groovy") }): SliceTreeStructure {
configureByFiles(null, *getTestFiles(getTestName(false)).toTypedArray())
PsiDocumentManager.getInstance(project).commitAllDocuments()
val element = SliceHandler.create(true).getExpressionAtCaret(editor, file)!!
val errors = highlightErrors()
UsefulTestCase.assertEmpty(errors)
val params = SliceAnalysisParams().apply {
scope = AnalysisScope(project)
dataFlowToThis = true
}
val usage = LanguageSlicing.getProvider(element)!!.createRootUsage(element, params)
val toolWindow = ToolWindowHeadlessManagerImpl.MockToolWindow(myProject)
val panel = object : SlicePanel(project, true, SliceRootNode(project, DuplicateMap(), usage), false, toolWindow) {
override fun close() {}
override fun isAutoScroll() = false
override fun setAutoScroll(autoScroll: Boolean) {}
override fun isPreview() = false
override fun setPreview(preview: Boolean) {}
}
Disposer.register(project, panel)
return panel.builder.treeStructure as SliceTreeStructure
}
fun testSimple() {
val treeStructure = loadTreeStructure()
val root = treeStructure.rootElement as SliceNode
val analyzer = GroovySliceProvider.getInstance().createLeafAnalyzer()
val leaf = analyzer.calcLeafExpressions(root, treeStructure, analyzer.createMap()).single()
TestCase.assertEquals(1234567, (leaf as GrLiteral).value)
}
fun testGroovyJavaGroovy() {
val treeStructure = loadTreeStructure { listOf("$it.groovy", "$it.java") }
val root = treeStructure.rootElement as SliceNode
val analyzer = GroovySliceProvider.getInstance().createLeafAnalyzer()
val leaves = analyzer.calcLeafExpressions(root, treeStructure, analyzer.createMap()).toList()
UsefulTestCase.assertSize(2, leaves)
TestCase.assertEquals(123, (leaves[0] as PsiLiteralExpression).value)
TestCase.assertEquals(456, (leaves[1] as GrLiteral).value)
}
fun testJavaGroovy() {
val treeStructure = loadTreeStructure { listOf("$it.java", "$it.groovy") }
val root = treeStructure.rootElement as SliceNode
val analyzer = JavaSlicerAnalysisUtil.createLeafAnalyzer()
val leaves = analyzer.calcLeafExpressions(root, treeStructure, analyzer.createMap()).toList()
UsefulTestCase.assertSize(2, leaves)
TestCase.assertEquals(123, (leaves[0] as PsiLiteralExpression).value)
TestCase.assertEquals(456, (leaves[1] as GrLiteral).value)
}
} | plugins/groovy/test/org/jetbrains/plugins/groovy/lang/slicer/GroovySliceTreeGroupingTest.kt | 3062029692 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.observable.operations
class AnonymousParallelOperationTrace(debugName: String? = null) {
private val delegate = CompoundParallelOperationTrace<Nothing?>(debugName)
fun isOperationCompleted() = delegate.isOperationCompleted()
fun startTask() = delegate.startTask(null)
fun finishTask() = delegate.finishTask(null)
fun beforeOperation(listener: CompoundParallelOperationTrace.Listener) = delegate.beforeOperation(listener)
fun beforeOperation(listener: () -> Unit) = delegate.beforeOperation(listener)
fun afterOperation(listener: CompoundParallelOperationTrace.Listener) = delegate.afterOperation(listener)
fun afterOperation(listener: () -> Unit) = delegate.afterOperation(listener)
} | platform/platform-impl/src/com/intellij/openapi/observable/operations/AnonymousParallelOperationTrace.kt | 3190849063 |
package slatekit.core.common
import java.io.ByteArrayInputStream
import java.io.File
import java.io.InputStream
object FileUtils {
fun loadFromFile(filePath: String): String {
return File(filePath).readText()
}
fun toInputStream(content: String): InputStream {
return ByteArrayInputStream(content.toByteArray())
}
fun toString(input: InputStream): String {
return input.bufferedReader().use { it.readText() }
}
} | src/lib/kotlin/slatekit-core/src/main/kotlin/slatekit/core/common/FileUtils.kt | 3668558833 |
/*
* Copyright 2017 Xuqiang ZHENG
*
* 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 `in`.nerd_is.android_showcase.dribbble.model.repository.remote
import `in`.nerd_is.android_showcase.BuildConfig
import `in`.nerd_is.android_showcase.common.Constant.*
import `in`.nerd_is.android_showcase.common.lib_support.retrofit.RetrofitUtils
import `in`.nerd_is.android_showcase.dribbble.ParamName
import `in`.nerd_is.android_showcase.dribbble.model.Shot
import `in`.nerd_is.android_showcase.dribbble.model.repository.DribbbleDataSource
import `in`.nerd_is.android_showcase.dribbble.model.repository.remote.DribbbleUrl.SHOTS
import io.reactivex.Scheduler
import io.reactivex.Single
import retrofit2.Retrofit
import retrofit2.http.GET
import retrofit2.http.QueryMap
import javax.inject.Inject
import javax.inject.Named
/**
* @author Xuqiang ZHENG on 2017/6/5.
*/
class DribbbleRemoteRepository @Inject constructor(
@Named(TAG_DRIBBBLE) retrofit: Retrofit,
@Named(TAG_IO) val ioScheduler: Scheduler,
@Named(TAG_MAIN) val mainScheduler: Scheduler) : DribbbleDataSource {
private val api = RetrofitUtils.create(retrofit, Api::class.java)
override fun getShots(): Single<List<Shot>> {
return api.getShots(mapOf(ParamName.ACCESS_TOKEN to BuildConfig.DRIBBBLE_ACCESS_TOKEN))
.subscribeOn(ioScheduler)
.observeOn(mainScheduler)
}
override fun getNextPageShots(page: Int): Single<List<Shot>> {
return api.getShots(mapOf(
ParamName.PAGE to page.toString(),
ParamName.ACCESS_TOKEN to BuildConfig.DRIBBBLE_ACCESS_TOKEN
)).subscribeOn(ioScheduler)
.observeOn(mainScheduler)
}
private interface Api {
@GET(value = SHOTS)
fun getShots(@QueryMap params: Map<String, String>): Single<List<Shot>>
}
} | app/src/main/kotlin/in/nerd_is/android_showcase/dribbble/model/repository/remote/DribbbleRemoteRepository.kt | 39009354 |
fun box(): String {
val s = IntArray(1)
s[0] = 5
s[0] += 7
return if (s[0] == 12) "OK" else "Fail ${s[0]}"
}
| backend.native/tests/external/codegen/box/arrays/arrayPlusAssign.kt | 2495278604 |
package com.github.triplet.gradle.play.tasks
import com.github.triplet.gradle.play.PlayPublisherExtension
import com.github.triplet.gradle.play.tasks.internal.PublishTaskBase
import com.github.triplet.gradle.play.tasks.internal.workers.PlayWorkerBase
import com.github.triplet.gradle.play.tasks.internal.workers.paramsForBase
import com.google.api.client.json.gson.GsonFactory
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.FileCollection
import org.gradle.api.file.FileType
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.SkipWhenEmpty
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.submit
import org.gradle.work.ChangeType
import org.gradle.work.DisableCachingByDefault
import org.gradle.work.Incremental
import org.gradle.work.InputChanges
import org.gradle.workers.WorkerExecutor
import javax.inject.Inject
@DisableCachingByDefault
internal abstract class PublishProducts @Inject constructor(
extension: PlayPublisherExtension,
private val executor: WorkerExecutor,
) : PublishTaskBase(extension) {
@get:Incremental
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:InputFiles
abstract val productsDir: ConfigurableFileCollection
// Used by Gradle to skip the task if all inputs are empty
@Suppress("MemberVisibilityCanBePrivate", "unused")
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:SkipWhenEmpty
@get:InputFiles
protected val targetFiles: FileCollection by lazy { productsDir.asFileTree }
// This directory isn't used, but it's needed for up-to-date checks to work
@Suppress("MemberVisibilityCanBePrivate", "unused")
@get:Optional
@get:OutputDirectory
protected val outputDir = null
@TaskAction
fun publishProducts(changes: InputChanges) {
changes.getFileChanges(productsDir)
.filterNot { it.changeType == ChangeType.REMOVED }
.filter { it.fileType == FileType.FILE }
.forEach {
executor.noIsolation().submit(Uploader::class) {
paramsForBase(this)
target.set(it.file)
}
}
}
abstract class Uploader : PlayWorkerBase<Uploader.Params>() {
override fun execute() {
val productFile = parameters.target.get().asFile
val product = productFile.inputStream().use {
GsonFactory.getDefaultInstance().createJsonParser(it).parse(Map::class.java)
}
println("Uploading ${product["sku"]}")
val response = apiService.publisher.updateInAppProduct(productFile)
if (response.needsCreating) apiService.publisher.insertInAppProduct(productFile)
}
interface Params : PlayPublishingParams {
val target: RegularFileProperty
}
}
}
| play/plugin/src/main/kotlin/com/github/triplet/gradle/play/tasks/PublishProducts.kt | 2345678871 |
package org.openmhealth.schema.domain
import java.math.BigDecimal
data class TypedUnitValue<T : Unit>(
val unit: T,
val value: BigDecimal
) {
constructor(unit: T, value: Double) : this(unit, BigDecimal.valueOf(value))
constructor(unit: T, value: Long) : this(unit, BigDecimal.valueOf(value))
}
| kotlin-schema-sdk/src/main/kotlin/org/openmhealth/schema/domain/TypedUnitValue.kt | 1839387642 |
@file:JvmName("MultiFileFacadeClass")
@file:JvmMultifileClass
package facades
public fun funInFacade2(): String = "2" | plugins/kotlin/completion/tests/testData/injava/mockLib/facades/multiFileFacadePart2.kt | 3144303997 |
package test
open class <!LINE_MARKER("descr='Is subclassed by ExpectedChild [common] ExpectedChild [jvm] ExpectedChildChild ExpectedChildChildJvm SimpleChild Click or press ... to navigate'")!>SimpleParent<!> {
open fun <!LINE_MARKER("descr='Is overridden in test.ExpectedChild test.ExpectedChildChild test.ExpectedChildChildJvm test.SimpleChild'")!>`foo fun`<!>(n: Int) {}
open val <!LINE_MARKER("descr='Is overridden in test.ExpectedChild test.ExpectedChildChild test.ExpectedChildChildJvm test.SimpleChild'")!>`bar fun`<!>: Int get() = 1
}
expect open class <!LINE_MARKER("descr='Is subclassed by ExpectedChildChild ExpectedChildChildJvm Click or press ... to navigate'"), LINE_MARKER("descr='Has actuals in JVM'")!>ExpectedChild<!> : SimpleParent {
override fun <!LINE_MARKER("descr='Overrides function in 'SimpleParent''"), LINE_MARKER("descr='Has actuals in JVM'"), LINE_MARKER("descr='Is overridden in test.ExpectedChildChild test.ExpectedChildChildJvm'")!>`foo fun`<!>(n: Int)
override val <!LINE_MARKER("descr='Overrides property in 'SimpleParent''"), LINE_MARKER("descr='Has actuals in JVM'"), LINE_MARKER("descr='Is overridden in test.ExpectedChildChild test.ExpectedChildChildJvm'")!>`bar fun`<!>: Int
}
class ExpectedChildChild : ExpectedChild() {
override fun <!LINE_MARKER("descr='Overrides function in 'ExpectedChild''")!>`foo fun`<!>(n: Int) {}
override val <!LINE_MARKER("descr='Overrides property in 'ExpectedChild''")!>`bar fun`<!>: Int get() = 1
}
class SimpleChild : SimpleParent() {
override fun <!LINE_MARKER("descr='Overrides function in 'SimpleParent''")!>`foo fun`<!>(n: Int) {}
override val <!LINE_MARKER("descr='Overrides property in 'SimpleParent''")!>`bar fun`<!>: Int get() = 1
} | plugins/kotlin/idea/tests/testData/multiModuleLineMarker/hierarchyWithExpectClassCommonSideNonJavaIds/common/common.kt | 2743438257 |
// 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.j2k
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil
interface ReferenceSearcher {
fun findLocalUsages(element: PsiElement, scope: PsiElement): Collection<PsiReference>
fun hasInheritors(`class`: PsiClass): Boolean
fun hasOverrides(method: PsiMethod): Boolean
fun findUsagesForExternalCodeProcessing(element: PsiElement, searchJava: Boolean, searchKotlin: Boolean): Collection<PsiReference>
}
fun ReferenceSearcher.findVariableUsages(variable: PsiVariable, scope: PsiElement): Collection<PsiReferenceExpression>
= findLocalUsages(variable, scope).filterIsInstance<PsiReferenceExpression>()
fun ReferenceSearcher.findMethodCalls(method: PsiMethod, scope: PsiElement): Collection<PsiMethodCallExpression> {
return findLocalUsages(method, scope).mapNotNull {
if (it is PsiReferenceExpression) {
val methodCall = it.parent as? PsiMethodCallExpression
if (methodCall?.methodExpression == it) methodCall else null
}
else {
null
}
}
}
fun PsiField.isVar(searcher: ReferenceSearcher): Boolean {
if (hasModifierProperty(PsiModifier.FINAL)) return false
if (!hasModifierProperty(PsiModifier.PRIVATE)) return true
val containingClass = containingClass ?: return true
val writes = searcher.findVariableUsages(this, containingClass).filter { PsiUtil.isAccessedForWriting(it) }
if (writes.size == 0) return false
if (writes.size > 1) return true
val write = writes.single()
val parent = write.parent
if (parent is PsiAssignmentExpression
&& parent.operationSign.tokenType == JavaTokenType.EQ
&& write.isQualifierEmptyOrThis()
) {
val constructor = write.getContainingConstructor()
return constructor == null
|| constructor.containingClass != containingClass
|| !(parent.parent is PsiExpressionStatement)
|| parent.parent?.parent != constructor.body
}
return true
}
fun PsiVariable.hasWriteAccesses(searcher: ReferenceSearcher, scope: PsiElement?): Boolean
= if (scope != null) searcher.findVariableUsages(this, scope).any { PsiUtil.isAccessedForWriting(it) } else false
fun PsiVariable.isInVariableInitializer(searcher: ReferenceSearcher, scope: PsiElement?): Boolean {
return if (scope != null) searcher.findVariableUsages(this, scope).any {
val parent = PsiTreeUtil.skipParentsOfType(it, PsiParenthesizedExpression::class.java)
parent is PsiVariable && parent.initializer == it
} else false
}
object EmptyReferenceSearcher: ReferenceSearcher {
override fun findLocalUsages(element: PsiElement, scope: PsiElement): Collection<PsiReference> = emptyList()
override fun hasInheritors(`class`: PsiClass) = false
override fun hasOverrides(method: PsiMethod) = false
override fun findUsagesForExternalCodeProcessing(element: PsiElement, searchJava: Boolean, searchKotlin: Boolean): Collection<PsiReference>
= emptyList()
} | plugins/kotlin/j2k/old/src/org/jetbrains/kotlin/j2k/ReferenceSearcher.kt | 3452370048 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetnews.ui.home
import android.content.Context
import android.content.res.Configuration.UI_MODE_NIGHT_YES
import android.widget.Toast
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.CenterAlignedTopAppBar
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.material3.TopAppBarState
import androidx.compose.material3.rememberTopAppBarState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.example.jetnews.R
import com.example.jetnews.data.Result
import com.example.jetnews.data.posts.impl.BlockingFakePostsRepository
import com.example.jetnews.model.Post
import com.example.jetnews.model.PostsFeed
import com.example.jetnews.ui.article.postContentItems
import com.example.jetnews.ui.article.sharePost
import com.example.jetnews.ui.components.JetnewsSnackbarHost
import com.example.jetnews.ui.modifiers.interceptKey
import com.example.jetnews.ui.rememberContentPaddingForScreen
import com.example.jetnews.ui.theme.JetnewsTheme
import com.example.jetnews.ui.utils.BookmarkButton
import com.example.jetnews.ui.utils.FavoriteButton
import com.example.jetnews.ui.utils.ShareButton
import com.example.jetnews.ui.utils.TextSettingsButton
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.isActive
import kotlinx.coroutines.runBlocking
/**
* The home screen displaying the feed along with an article details.
*/
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun HomeFeedWithArticleDetailsScreen(
uiState: HomeUiState,
showTopAppBar: Boolean,
onToggleFavorite: (String) -> Unit,
onSelectPost: (String) -> Unit,
onRefreshPosts: () -> Unit,
onErrorDismiss: (Long) -> Unit,
onInteractWithList: () -> Unit,
onInteractWithDetail: (String) -> Unit,
openDrawer: () -> Unit,
homeListLazyListState: LazyListState,
articleDetailLazyListStates: Map<String, LazyListState>,
snackbarHostState: SnackbarHostState,
modifier: Modifier = Modifier,
onSearchInputChanged: (String) -> Unit,
) {
HomeScreenWithList(
uiState = uiState,
showTopAppBar = showTopAppBar,
onRefreshPosts = onRefreshPosts,
onErrorDismiss = onErrorDismiss,
openDrawer = openDrawer,
snackbarHostState = snackbarHostState,
modifier = modifier,
) { hasPostsUiState, contentModifier ->
val contentPadding = rememberContentPaddingForScreen(
additionalTop = if (showTopAppBar) 0.dp else 8.dp,
excludeTop = showTopAppBar
)
Row(contentModifier) {
PostList(
postsFeed = hasPostsUiState.postsFeed,
favorites = hasPostsUiState.favorites,
showExpandedSearch = !showTopAppBar,
onArticleTapped = onSelectPost,
onToggleFavorite = onToggleFavorite,
contentPadding = contentPadding,
modifier = Modifier
.width(334.dp)
.notifyInput(onInteractWithList),
state = homeListLazyListState,
searchInput = hasPostsUiState.searchInput,
onSearchInputChanged = onSearchInputChanged,
)
// Crossfade between different detail posts
Crossfade(targetState = hasPostsUiState.selectedPost) { detailPost ->
// Get the lazy list state for this detail view
val detailLazyListState by remember {
derivedStateOf {
articleDetailLazyListStates.getValue(detailPost.id)
}
}
// Key against the post id to avoid sharing any state between different posts
key(detailPost.id) {
LazyColumn(
state = detailLazyListState,
contentPadding = contentPadding,
modifier = Modifier
.padding(horizontal = 16.dp)
.fillMaxSize()
.notifyInput {
onInteractWithDetail(detailPost.id)
}
) {
stickyHeader {
val context = LocalContext.current
PostTopBar(
isFavorite = hasPostsUiState.favorites.contains(detailPost.id),
onToggleFavorite = { onToggleFavorite(detailPost.id) },
onSharePost = { sharePost(detailPost, context) },
modifier = Modifier
.fillMaxWidth()
.wrapContentWidth(Alignment.End)
)
}
postContentItems(detailPost)
}
}
}
}
}
}
/**
* A [Modifier] that tracks all input, and calls [block] every time input is received.
*/
private fun Modifier.notifyInput(block: () -> Unit): Modifier =
composed {
val blockState = rememberUpdatedState(block)
pointerInput(Unit) {
while (currentCoroutineContext().isActive) {
awaitPointerEventScope {
awaitPointerEvent(PointerEventPass.Initial)
blockState.value()
}
}
}
}
/**
* The home screen displaying just the article feed.
*/
@Composable
fun HomeFeedScreen(
uiState: HomeUiState,
showTopAppBar: Boolean,
onToggleFavorite: (String) -> Unit,
onSelectPost: (String) -> Unit,
onRefreshPosts: () -> Unit,
onErrorDismiss: (Long) -> Unit,
openDrawer: () -> Unit,
homeListLazyListState: LazyListState,
snackbarHostState: SnackbarHostState,
modifier: Modifier = Modifier,
searchInput: String = "",
onSearchInputChanged: (String) -> Unit,
) {
HomeScreenWithList(
uiState = uiState,
showTopAppBar = showTopAppBar,
onRefreshPosts = onRefreshPosts,
onErrorDismiss = onErrorDismiss,
openDrawer = openDrawer,
snackbarHostState = snackbarHostState,
modifier = modifier
) { hasPostsUiState, contentModifier ->
PostList(
postsFeed = hasPostsUiState.postsFeed,
favorites = hasPostsUiState.favorites,
showExpandedSearch = !showTopAppBar,
onArticleTapped = onSelectPost,
onToggleFavorite = onToggleFavorite,
contentPadding = rememberContentPaddingForScreen(
additionalTop = if (showTopAppBar) 0.dp else 8.dp,
excludeTop = showTopAppBar
),
modifier = contentModifier,
state = homeListLazyListState,
searchInput = searchInput,
onSearchInputChanged = onSearchInputChanged
)
}
}
/**
* A display of the home screen that has the list.
*
* This sets up the scaffold with the top app bar, and surrounds the [hasPostsContent] with refresh,
* loading and error handling.
*
* This helper functions exists because [HomeFeedWithArticleDetailsScreen] and [HomeFeedScreen] are
* extremely similar, except for the rendered content when there are posts to display.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun HomeScreenWithList(
uiState: HomeUiState,
showTopAppBar: Boolean,
onRefreshPosts: () -> Unit,
onErrorDismiss: (Long) -> Unit,
openDrawer: () -> Unit,
snackbarHostState: SnackbarHostState,
modifier: Modifier = Modifier,
hasPostsContent: @Composable (
uiState: HomeUiState.HasPosts,
modifier: Modifier
) -> Unit
) {
val topAppBarState = rememberTopAppBarState()
val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior(topAppBarState)
Scaffold(
snackbarHost = { JetnewsSnackbarHost(hostState = snackbarHostState) },
topBar = {
if (showTopAppBar) {
HomeTopAppBar(
openDrawer = openDrawer,
topAppBarState = topAppBarState
)
}
},
modifier = modifier
) { innerPadding ->
val contentModifier = Modifier
.padding(innerPadding)
.nestedScroll(scrollBehavior.nestedScrollConnection)
LoadingContent(
empty = when (uiState) {
is HomeUiState.HasPosts -> false
is HomeUiState.NoPosts -> uiState.isLoading
},
emptyContent = { FullScreenLoading() },
loading = uiState.isLoading,
onRefresh = onRefreshPosts,
content = {
when (uiState) {
is HomeUiState.HasPosts -> hasPostsContent(uiState, contentModifier)
is HomeUiState.NoPosts -> {
if (uiState.errorMessages.isEmpty()) {
// if there are no posts, and no error, let the user refresh manually
TextButton(
onClick = onRefreshPosts,
modifier.fillMaxSize()
) {
Text(
stringResource(id = R.string.home_tap_to_load_content),
textAlign = TextAlign.Center
)
}
} else {
// there's currently an error showing, don't show any content
Box(contentModifier.fillMaxSize()) { /* empty screen */ }
}
}
}
}
)
}
// Process one error message at a time and show them as Snackbars in the UI
if (uiState.errorMessages.isNotEmpty()) {
// Remember the errorMessage to display on the screen
val errorMessage = remember(uiState) { uiState.errorMessages[0] }
// Get the text to show on the message from resources
val errorMessageText: String = stringResource(errorMessage.messageId)
val retryMessageText = stringResource(id = R.string.retry)
// If onRefreshPosts or onErrorDismiss change while the LaunchedEffect is running,
// don't restart the effect and use the latest lambda values.
val onRefreshPostsState by rememberUpdatedState(onRefreshPosts)
val onErrorDismissState by rememberUpdatedState(onErrorDismiss)
// Effect running in a coroutine that displays the Snackbar on the screen
// If there's a change to errorMessageText, retryMessageText or snackbarHostState,
// the previous effect will be cancelled and a new one will start with the new values
LaunchedEffect(errorMessageText, retryMessageText, snackbarHostState) {
val snackbarResult = snackbarHostState.showSnackbar(
message = errorMessageText,
actionLabel = retryMessageText
)
if (snackbarResult == SnackbarResult.ActionPerformed) {
onRefreshPostsState()
}
// Once the message is displayed and dismissed, notify the ViewModel
onErrorDismissState(errorMessage.id)
}
}
}
/**
* Display an initial empty state or swipe to refresh content.
*
* @param empty (state) when true, display [emptyContent]
* @param emptyContent (slot) the content to display for the empty state
* @param loading (state) when true, display a loading spinner over [content]
* @param onRefresh (event) event to request refresh
* @param content (slot) the main content to show
*/
@Composable
private fun LoadingContent(
empty: Boolean,
emptyContent: @Composable () -> Unit,
loading: Boolean,
onRefresh: () -> Unit,
content: @Composable () -> Unit
) {
if (empty) {
emptyContent()
} else {
SwipeRefresh(
state = rememberSwipeRefreshState(loading),
onRefresh = onRefresh,
content = content,
)
}
}
/**
* Display a feed of posts.
*
* When a post is clicked on, [onArticleTapped] will be called.
*
* @param postsFeed (state) the feed to display
* @param onArticleTapped (event) request navigation to Article screen
* @param modifier modifier for the root element
*/
@Composable
private fun PostList(
postsFeed: PostsFeed,
favorites: Set<String>,
showExpandedSearch: Boolean,
onArticleTapped: (postId: String) -> Unit,
onToggleFavorite: (String) -> Unit,
modifier: Modifier = Modifier,
contentPadding: PaddingValues = PaddingValues(0.dp),
state: LazyListState = rememberLazyListState(),
searchInput: String = "",
onSearchInputChanged: (String) -> Unit,
) {
LazyColumn(
modifier = modifier,
contentPadding = contentPadding,
state = state
) {
if (showExpandedSearch) {
item {
HomeSearch(
Modifier.padding(horizontal = 16.dp),
searchInput = searchInput,
onSearchInputChanged = onSearchInputChanged,
)
}
}
item { PostListTopSection(postsFeed.highlightedPost, onArticleTapped) }
if (postsFeed.recommendedPosts.isNotEmpty()) {
item {
PostListSimpleSection(
postsFeed.recommendedPosts,
onArticleTapped,
favorites,
onToggleFavorite
)
}
}
if (postsFeed.popularPosts.isNotEmpty() && !showExpandedSearch) {
item {
PostListPopularSection(
postsFeed.popularPosts, onArticleTapped
)
}
}
if (postsFeed.recentPosts.isNotEmpty()) {
item { PostListHistorySection(postsFeed.recentPosts, onArticleTapped) }
}
}
}
/**
* Full screen circular progress indicator
*/
@Composable
private fun FullScreenLoading() {
Box(
modifier = Modifier
.fillMaxSize()
.wrapContentSize(Alignment.Center)
) {
CircularProgressIndicator()
}
}
/**
* Top section of [PostList]
*
* @param post (state) highlighted post to display
* @param navigateToArticle (event) request navigation to Article screen
*/
@Composable
private fun PostListTopSection(post: Post, navigateToArticle: (String) -> Unit) {
Text(
modifier = Modifier.padding(start = 16.dp, top = 16.dp, end = 16.dp),
text = stringResource(id = R.string.home_top_section_title),
style = MaterialTheme.typography.titleMedium
)
PostCardTop(
post = post,
modifier = Modifier.clickable(onClick = { navigateToArticle(post.id) })
)
PostListDivider()
}
/**
* Full-width list items for [PostList]
*
* @param posts (state) to display
* @param navigateToArticle (event) request navigation to Article screen
*/
@Composable
private fun PostListSimpleSection(
posts: List<Post>,
navigateToArticle: (String) -> Unit,
favorites: Set<String>,
onToggleFavorite: (String) -> Unit
) {
Column {
posts.forEach { post ->
PostCardSimple(
post = post,
navigateToArticle = navigateToArticle,
isFavorite = favorites.contains(post.id),
onToggleFavorite = { onToggleFavorite(post.id) }
)
PostListDivider()
}
}
}
/**
* Horizontal scrolling cards for [PostList]
*
* @param posts (state) to display
* @param navigateToArticle (event) request navigation to Article screen
*/
@Composable
private fun PostListPopularSection(
posts: List<Post>,
navigateToArticle: (String) -> Unit
) {
Column {
Text(
modifier = Modifier.padding(16.dp),
text = stringResource(id = R.string.home_popular_section_title),
style = MaterialTheme.typography.titleLarge
)
LazyRow(
contentPadding = PaddingValues(horizontal = 16.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
items(posts) { post ->
PostCardPopular(
post,
navigateToArticle
)
}
}
Spacer(Modifier.height(16.dp))
PostListDivider()
}
}
/**
* Full-width list items that display "based on your history" for [PostList]
*
* @param posts (state) to display
* @param navigateToArticle (event) request navigation to Article screen
*/
@Composable
private fun PostListHistorySection(
posts: List<Post>,
navigateToArticle: (String) -> Unit
) {
Column {
posts.forEach { post ->
PostCardHistory(post, navigateToArticle)
PostListDivider()
}
}
}
/**
* Full-width divider with padding for [PostList]
*/
@Composable
private fun PostListDivider() {
Divider(
modifier = Modifier.padding(horizontal = 14.dp),
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.08f)
)
}
/**
* Expanded search UI - includes support for enter-to-send on the search field
*/
@OptIn(ExperimentalMaterial3Api::class, ExperimentalComposeUiApi::class)
@Composable
private fun HomeSearch(
modifier: Modifier = Modifier,
searchInput: String = "",
onSearchInputChanged: (String) -> Unit,
) {
val context = LocalContext.current
val focusManager = LocalFocusManager.current
val keyboardController = LocalSoftwareKeyboardController.current
OutlinedTextField(
value = searchInput,
onValueChange = onSearchInputChanged,
placeholder = { Text(stringResource(R.string.home_search)) },
leadingIcon = { Icon(Icons.Filled.Search, null) },
modifier = modifier
.fillMaxWidth()
.interceptKey(Key.Enter) {
// submit a search query when Enter is pressed
submitSearch(onSearchInputChanged, context)
keyboardController?.hide()
focusManager.clearFocus(force = true)
},
singleLine = true,
// keyboardOptions change the newline key to a search key on the soft keyboard
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
// keyboardActions submits the search query when the search key is pressed
keyboardActions = KeyboardActions(
onSearch = {
submitSearch(onSearchInputChanged, context)
keyboardController?.hide()
}
)
)
}
/**
* Stub helper function to submit a user's search query
*/
private fun submitSearch(
onSearchInputChanged: (String) -> Unit,
context: Context
) {
onSearchInputChanged("")
Toast.makeText(
context,
"Search is not yet implemented",
Toast.LENGTH_SHORT
).show()
}
/**
* Top bar for a Post when displayed next to the Home feed
*/
@Composable
private fun PostTopBar(
isFavorite: Boolean,
onToggleFavorite: () -> Unit,
onSharePost: () -> Unit,
modifier: Modifier = Modifier
) {
Surface(
shape = RoundedCornerShape(8.dp),
border = BorderStroke(Dp.Hairline, MaterialTheme.colorScheme.onSurface.copy(alpha = .6f)),
modifier = modifier.padding(end = 16.dp)
) {
Row(Modifier.padding(horizontal = 8.dp)) {
FavoriteButton(onClick = { /* Functionality not available */ })
BookmarkButton(isBookmarked = isFavorite, onClick = onToggleFavorite)
ShareButton(onClick = onSharePost)
TextSettingsButton(onClick = { /* Functionality not available */ })
}
}
}
/**
* TopAppBar for the Home screen
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun HomeTopAppBar(
openDrawer: () -> Unit,
modifier: Modifier = Modifier,
topAppBarState: TopAppBarState = rememberTopAppBarState(),
scrollBehavior: TopAppBarScrollBehavior? =
TopAppBarDefaults.enterAlwaysScrollBehavior(topAppBarState)
) {
val title = stringResource(id = R.string.app_name)
CenterAlignedTopAppBar(
title = {
Image(
painter = painterResource(R.drawable.ic_jetnews_wordmark),
contentDescription = title,
contentScale = ContentScale.Inside,
colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.onBackground),
modifier = Modifier.fillMaxWidth()
)
},
navigationIcon = {
IconButton(onClick = openDrawer) {
Icon(
painter = painterResource(R.drawable.ic_jetnews_logo),
contentDescription = stringResource(R.string.cd_open_navigation_drawer),
tint = MaterialTheme.colorScheme.primary
)
}
},
actions = {
IconButton(onClick = { /* TODO: Open search */ }) {
Icon(
imageVector = Icons.Filled.Search,
contentDescription = stringResource(R.string.cd_search)
)
}
},
scrollBehavior = scrollBehavior,
modifier = modifier
)
}
@Preview("Home list drawer screen")
@Preview("Home list drawer screen (dark)", uiMode = UI_MODE_NIGHT_YES)
@Preview("Home list drawer screen (big font)", fontScale = 1.5f)
@Composable
fun PreviewHomeListDrawerScreen() {
val postsFeed = runBlocking {
(BlockingFakePostsRepository().getPostsFeed() as Result.Success).data
}
JetnewsTheme {
HomeFeedScreen(
uiState = HomeUiState.HasPosts(
postsFeed = postsFeed,
selectedPost = postsFeed.highlightedPost,
isArticleOpen = false,
favorites = emptySet(),
isLoading = false,
errorMessages = emptyList(),
searchInput = ""
),
showTopAppBar = false,
onToggleFavorite = {},
onSelectPost = {},
onRefreshPosts = {},
onErrorDismiss = {},
openDrawer = {},
homeListLazyListState = rememberLazyListState(),
snackbarHostState = SnackbarHostState(),
onSearchInputChanged = {}
)
}
}
@Preview("Home list navrail screen", device = Devices.NEXUS_7_2013)
@Preview(
"Home list navrail screen (dark)",
uiMode = UI_MODE_NIGHT_YES,
device = Devices.NEXUS_7_2013
)
@Preview("Home list navrail screen (big font)", fontScale = 1.5f, device = Devices.NEXUS_7_2013)
@Composable
fun PreviewHomeListNavRailScreen() {
val postsFeed = runBlocking {
(BlockingFakePostsRepository().getPostsFeed() as Result.Success).data
}
JetnewsTheme {
HomeFeedScreen(
uiState = HomeUiState.HasPosts(
postsFeed = postsFeed,
selectedPost = postsFeed.highlightedPost,
isArticleOpen = false,
favorites = emptySet(),
isLoading = false,
errorMessages = emptyList(),
searchInput = ""
),
showTopAppBar = true,
onToggleFavorite = {},
onSelectPost = {},
onRefreshPosts = {},
onErrorDismiss = {},
openDrawer = {},
homeListLazyListState = rememberLazyListState(),
snackbarHostState = SnackbarHostState(),
onSearchInputChanged = {}
)
}
}
@Preview("Home list detail screen", device = Devices.PIXEL_C)
@Preview("Home list detail screen (dark)", uiMode = UI_MODE_NIGHT_YES, device = Devices.PIXEL_C)
@Preview("Home list detail screen (big font)", fontScale = 1.5f, device = Devices.PIXEL_C)
@Composable
fun PreviewHomeListDetailScreen() {
val postsFeed = runBlocking {
(BlockingFakePostsRepository().getPostsFeed() as Result.Success).data
}
JetnewsTheme {
HomeFeedWithArticleDetailsScreen(
uiState = HomeUiState.HasPosts(
postsFeed = postsFeed,
selectedPost = postsFeed.highlightedPost,
isArticleOpen = false,
favorites = emptySet(),
isLoading = false,
errorMessages = emptyList(),
searchInput = ""
),
showTopAppBar = true,
onToggleFavorite = {},
onSelectPost = {},
onRefreshPosts = {},
onErrorDismiss = {},
onInteractWithList = {},
onInteractWithDetail = {},
openDrawer = {},
homeListLazyListState = rememberLazyListState(),
articleDetailLazyListStates = postsFeed.allPosts.associate { post ->
key(post.id) {
post.id to rememberLazyListState()
}
},
snackbarHostState = SnackbarHostState(),
onSearchInputChanged = {}
)
}
}
| JetNews/app/src/main/java/com/example/jetnews/ui/home/HomeScreens.kt | 445175677 |
// 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.formatting.visualLayer
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.editor.event.EditorFactoryListener
import com.intellij.openapi.project.Project
class VisualFormattingLayerNewEditorListener(val project: Project) : EditorFactoryListener {
override fun editorCreated(event: EditorFactoryEvent) {
val editor: Editor = event.editor
if (project == editor.project) {
editor.addVisualLayer()
}
}
override fun editorReleased(event: EditorFactoryEvent) {
val editor: Editor = event.editor
if (project == editor.project) {
editor.removeVisualLayer()
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
val that = other as VisualFormattingLayerNewEditorListener
return project == that.project
}
override fun hashCode(): Int {
return project.hashCode()
}
}
| platform/lang-impl/src/com/intellij/formatting/visualLayer/VisualFormattingLayerNewEditorListener.kt | 2191309256 |
package demo
internal class Test {
fun test(vararg args: Any?) {
var args = args
args = arrayOf<Int?>(1, 2, 3)
}
} | plugins/kotlin/j2k/new/tests/testData/partialConverter/function/varVararg.kt | 2420161582 |
import org.gradle.api.Project
import org.gradle.api.plugins.ExtraPropertiesExtension
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.SourceSetContainer
import org.gradle.kotlin.dsl.getByType
import org.gradle.kotlin.dsl.the
val Project.ext: ExtraPropertiesExtension
get() = extensions.getByType()
val Project.sourceSets: SourceSetContainer
get() = the<JavaPluginConvention>().sourceSets
| buildSrc/src/main/kotlin/GradleExtras.kt | 4084438409 |
package sample
fun <lineMarker descr="null" settings="runDebugExecutableLinux runDebugExecutableMacos">main</lineMarker>() {
} | plugins/kotlin/idea/tests/testData/gradle/nativeRunConfiguration/multiplatformNativeRunGutter/src/commonMain/kotlin/sample/SampleCommon.kt | 760888554 |
package zielu.gittoolbox.config
import com.intellij.openapi.project.Project
import com.intellij.util.xmlb.annotations.Transient
import kotlin.streams.toList
internal data class BoolConfigOverride(
var enabled: Boolean = false,
var value: Boolean = false,
var applied: MutableList<AppliedConfigOverride> = arrayListOf()
) {
@Transient
fun copy(): BoolConfigOverride {
return BoolConfigOverride(
enabled,
value,
applied.map { it.copy() }.toMutableList()
)
}
fun isNotApplied(project: Project): Boolean {
return project.presentableUrl?.let { path ->
applied.stream()
.map { it.projectPath }
.noneMatch { it == path }
} ?: false
}
fun applied(project: Project) {
project.presentableUrl?.run {
applied.add(AppliedConfigOverride(this))
}
}
@Transient
fun getAppliedPaths(): List<String> {
return applied.stream()
.map { it.projectPath }
.toList()
}
}
| src/main/kotlin/zielu/gittoolbox/config/BoolConfigOverride.kt | 2693016315 |
// SUGGESTED_NAMES: s, getA
// PARAM_TYPES: kotlin.String
// PARAM_TYPES: kotlin.String, kotlin.Comparable<kotlin.String>, kotlin.CharSequence, java.io.Serializable, kotlin.Any
// PARAM_TYPES: kotlin.String, kotlin.Comparable<kotlin.String>, kotlin.CharSequence, java.io.Serializable, kotlin.Any
// PARAM_DESCRIPTOR: local final fun kotlin.String.<anonymous>(): kotlin.Unit defined in Foo.foo.<anonymous>.<anonymous>, local final fun kotlin.String.<anonymous>(): kotlin.Unit defined in Foo.foo.<anonymous>, local final fun kotlin.String.<anonymous>(): kotlin.Unit defined in Foo.foo
class Foo {
fun foo() {
block("a") a@ {
block("b") b@ {
block("c") c@ {
val a = <selection>this@c + this@b + this@a + this + [email protected]()</selection>
}
}
}
}
}
private inline fun <T> block(t: T, block: T.() -> Unit) {
t.block()
} | plugins/kotlin/idea/tests/testData/refactoring/extractFunction/basic/sameParameterNames.kt | 420684647 |
package test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.MethodSource
import java.util.stream.Stream
object PrivateClassRule {
@ParameterizedTest
@MethodSource("squares")
fun foo() {}
companion object {
fun squares(): Stream<Int?>? {
return null
}
}
} | plugins/junit/testData/codeInsight/junit5malformed/StaticMethodSource.kt | 4232653344 |
package info.nightscout.androidaps.plugins.general.maintenance.activities
import android.os.Bundle
import android.view.View
import android.widget.CheckBox
import android.widget.LinearLayout
import android.widget.TextView
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity
import info.nightscout.androidaps.databinding.ActivityLogsettingBinding
import info.nightscout.androidaps.logging.L
import javax.inject.Inject
class LogSettingActivity : NoSplashAppCompatActivity() {
@Inject lateinit var l: L
private lateinit var binding: ActivityLogsettingBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLogsettingBinding.inflate(layoutInflater)
setContentView(binding.root)
createViewsForSettings()
binding.reset.setOnClickListener {
l.resetToDefaults()
createViewsForSettings()
}
binding.ok.setOnClickListener { finish() }
}
private fun createViewsForSettings() {
binding.placeholder.removeAllViews()
for (element in l.getLogElements()) {
val logViewHolder = LogViewHolder(element)
binding.placeholder.addView(logViewHolder.baseView)
}
}
internal inner class LogViewHolder(element: L.LogElement) {
@Suppress("InflateParams")
var baseView = layoutInflater.inflate(R.layout.logsettings_item, null) as LinearLayout
init {
(baseView.findViewById<View>(R.id.logsettings_description) as TextView).text = element.name
val enabled = baseView.findViewById<CheckBox>(R.id.logsettings_visibility)
enabled.isChecked = element.enabled
enabled.setOnClickListener { element.enable(enabled.isChecked) }
}
}
}
| app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/LogSettingActivity.kt | 1836793863 |
package flank.scripts.ops.assemble.android
import flank.common.androidTestProjectsPath
import flank.common.flankFixturesTmpPath
import flank.scripts.utils.createGradleCommand
import flank.scripts.utils.runCommand
import java.nio.file.Paths
// TODO Design common abstraction for building apks and coping artifacts, add java doc.
private const val BENCHMARK = "benchmark"
fun AndroidBuildConfiguration.buildBenchmark() {
if (artifacts.canExecute(BENCHMARK).not()) return
createGradleCommand(
workingDir = androidTestProjectsPath,
options = listOf(
"-p",
androidTestProjectsPath,
"$BENCHMARK:assembleDebugAndroidTest"
)
).runCommand()
if (copy) copyApks()
}
private fun copyApks() {
val outputDir = Paths.get(flankFixturesTmpPath, "apk", BENCHMARK).toString()
Paths.get(androidTestProjectsPath, BENCHMARK).toFile().findApks().copyApksToPath(outputDir)
}
| flank-scripts/src/main/kotlin/flank/scripts/ops/assemble/android/BuildBenchmark.kt | 1023013549 |
package ftl.run.model
import com.google.gson.annotations.SerializedName
data class AndroidTestShards(
val app: String,
val test: String,
val shards: Map<String, List<String>> = emptyMap(),
@SerializedName("junit-ignored")
val junitIgnored: List<String> = emptyList()
)
| test_runner/src/main/kotlin/ftl/run/model/AndroidTestShards.kt | 2319773955 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.psi
import com.google.common.collect.HashMultimap
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget
import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.JvmNames
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.annotations.JVM_STATIC_ANNOTATION_FQ_NAME
import org.jetbrains.kotlin.resolve.jvm.JvmClassName
import org.jetbrains.kotlin.resolve.jvm.annotations.JVM_OVERLOADS_FQ_NAME
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
object KotlinPsiHeuristics {
@JvmStatic
fun unwrapImportAlias(file: KtFile, aliasName: String): Collection<String> {
return file.aliasImportMap[aliasName]
}
@JvmStatic
fun unwrapImportAlias(type: KtUserType, aliasName: String): Collection<String> {
val file = type.containingKotlinFileStub?.psi as? KtFile ?: return emptyList()
return unwrapImportAlias(file, aliasName)
}
@JvmStatic
fun getImportAliases(file: KtFile, names: Set<String>): Set<String> {
val result = LinkedHashSet<String>()
for ((aliasName, name) in file.aliasImportMap.entries()) {
if (name in names) {
result += aliasName
}
}
return result
}
private val KtFile.aliasImportMap by userDataCached("ALIAS_IMPORT_MAP_KEY") { file ->
HashMultimap.create<String, String>().apply {
for (import in file.importList?.imports.orEmpty()) {
val aliasName = import.aliasName ?: continue
val name = import.importPath?.fqName?.shortName()?.asString() ?: continue
put(aliasName, name)
}
}
}
@JvmStatic
fun isProbablyNothing(typeReference: KtTypeReference): Boolean {
val userType = typeReference.typeElement as? KtUserType ?: return false
return isProbablyNothing(userType)
}
@JvmStatic
fun isProbablyNothing(type: KtUserType): Boolean {
val referencedName = type.referencedName
if (referencedName == "Nothing") {
return true
}
// TODO: why don't use PSI-less stub for calculating aliases?
val file = type.containingKotlinFileStub?.psi as? KtFile ?: return false
// TODO: support type aliases
return file.aliasImportMap[referencedName].contains("Nothing")
}
@JvmStatic
fun getJvmName(fqName: FqName): String {
val asString = fqName.asString()
var startIndex = 0
while (startIndex != -1) { // always true
val dotIndex = asString.indexOf('.', startIndex)
if (dotIndex == -1) return asString
startIndex = dotIndex + 1
val charAfterDot = asString.getOrNull(startIndex) ?: return asString
if (!charAfterDot.isLetter()) return asString
if (charAfterDot.isUpperCase()) return buildString {
append(asString.subSequence(0, startIndex))
append(asString.substring(startIndex).replace('.', '$'))
}
}
return asString
}
@JvmStatic
fun getPackageName(file: KtFile): FqName? {
val entry = JvmFileClassUtil.findAnnotationEntryOnFileNoResolve(file, JvmNames.JVM_PACKAGE_NAME_SHORT) ?: return null
val customPackageName = JvmFileClassUtil.getLiteralStringFromAnnotation(entry)
if (customPackageName != null) {
return FqName(customPackageName)
}
return file.packageFqName
}
@JvmStatic
fun getJvmName(declaration: KtClassOrObject): String? {
val classId = declaration.classIdIfNonLocal ?: return null
val jvmClassName = JvmClassName.byClassId(classId)
return jvmClassName.fqNameForTopLevelClassMaybeWithDollars.asString()
}
private fun checkAnnotationUseSiteTarget(annotationEntry: KtAnnotationEntry, useSiteTarget: AnnotationUseSiteTarget?): Boolean {
return useSiteTarget == null || annotationEntry.useSiteTarget?.getAnnotationUseSiteTarget() == useSiteTarget
}
@JvmStatic
fun findAnnotation(declaration: KtAnnotated, shortName: String, useSiteTarget: AnnotationUseSiteTarget? = null): KtAnnotationEntry? {
return declaration.annotationEntries
.firstOrNull { checkAnnotationUseSiteTarget(it, useSiteTarget) && it.shortName?.asString() == shortName }
}
@JvmStatic
fun findAnnotation(declaration: KtAnnotated, fqName: FqName, useSiteTarget: AnnotationUseSiteTarget? = null): KtAnnotationEntry? {
val targetShortName = fqName.shortName().asString()
val targetAliasName = declaration.containingKtFile.findAliasByFqName(fqName)?.name
for (annotationEntry in declaration.annotationEntries) {
if (!checkAnnotationUseSiteTarget(annotationEntry, useSiteTarget)) {
continue
}
val annotationShortName = annotationEntry.shortName?.asString() ?: continue
if (annotationShortName == targetShortName || annotationShortName == targetAliasName) {
return annotationEntry
}
}
return null
}
@JvmStatic
fun hasAnnotation(declaration: KtAnnotated, shortName: String, useSiteTarget: AnnotationUseSiteTarget? = null): Boolean {
return findAnnotation(declaration, shortName, useSiteTarget) != null
}
@JvmStatic
fun hasAnnotation(declaration: KtAnnotated, shortName: Name, useSiteTarget: AnnotationUseSiteTarget? = null): Boolean {
return findAnnotation(declaration, shortName.asString(), useSiteTarget) != null
}
@JvmStatic
fun hasAnnotation(declaration: KtAnnotated, fqName: FqName, useSiteTarget: AnnotationUseSiteTarget? = null): Boolean {
return findAnnotation(declaration, fqName, useSiteTarget) != null
}
@JvmStatic
fun findJvmName(declaration: KtAnnotated, useSiteTarget: AnnotationUseSiteTarget? = null): String? {
val annotation = findAnnotation(declaration, JvmFileClassUtil.JVM_NAME, useSiteTarget) ?: return null
return JvmFileClassUtil.getLiteralStringFromAnnotation(annotation)
}
@JvmStatic
fun findJvmGetterName(declaration: KtValVarKeywordOwner): String? {
return when (declaration) {
is KtProperty -> declaration.getter?.let(::findJvmName) ?: findJvmName(declaration, AnnotationUseSiteTarget.PROPERTY_GETTER)
is KtParameter -> findJvmName(declaration, AnnotationUseSiteTarget.PROPERTY_GETTER)
else -> null
}
}
@JvmStatic
fun findJvmSetterName(declaration: KtValVarKeywordOwner): String? {
return when (declaration) {
is KtProperty -> declaration.setter?.let(::findJvmName) ?: findJvmName(declaration, AnnotationUseSiteTarget.PROPERTY_SETTER)
is KtParameter -> findJvmName(declaration, AnnotationUseSiteTarget.PROPERTY_SETTER)
else -> null
}
}
@JvmStatic
fun findSuppressAnnotation(declaration: KtAnnotated): KtAnnotationEntry? {
return findAnnotation(declaration, StandardNames.FqNames.suppress)
}
@JvmStatic
fun hasSuppressAnnotation(declaration: KtAnnotated): Boolean {
return findSuppressAnnotation(declaration) != null
}
@JvmStatic
fun hasNonSuppressAnnotations(declaration: KtAnnotated): Boolean {
val annotationEntries = declaration.annotationEntries
return annotationEntries.size > 1 || annotationEntries.size == 1 && !hasSuppressAnnotation(declaration)
}
@JvmStatic
fun hasJvmFieldAnnotation(declaration: KtAnnotated): Boolean {
return hasAnnotation(declaration, JvmAbi.JVM_FIELD_ANNOTATION_FQ_NAME)
}
@JvmStatic
fun hasJvmOverloadsAnnotation(declaration: KtAnnotated): Boolean {
return hasAnnotation(declaration, JVM_OVERLOADS_FQ_NAME)
}
@JvmStatic
fun hasJvmStaticAnnotation(declaration: KtAnnotated): Boolean {
return hasAnnotation(declaration, JVM_STATIC_ANNOTATION_FQ_NAME)
}
@JvmStatic
fun getStringValue(argument: ValueArgument): String? {
return argument.getArgumentExpression()
?.safeAs<KtStringTemplateExpression>()
?.entries
?.singleOrNull()
?.safeAs<KtLiteralStringTemplateEntry>()
?.text
}
@JvmStatic
fun findSuppressedEntities(declaration: KtAnnotated): List<String>? {
val entry = findSuppressAnnotation(declaration) ?: return null
return entry.valueArguments.mapNotNull(::getStringValue)
}
@JvmStatic
fun isPossibleOperator(declaration: KtNamedFunction): Boolean {
if (declaration.hasModifier(KtTokens.OPERATOR_KEYWORD)) {
return true
} else if (!declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) {
// Operator modifier could be omitted only for overridden function
return false
}
val name = declaration.name ?: return false
if (!OperatorConventions.isConventionName(Name.identifier(name))) {
return false
}
return true
}
} | plugins/kotlin/base/psi/src/org/jetbrains/kotlin/idea/base/psi/KotlinPsiHeuristics.kt | 630332397 |
// 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.caches.trackers
import com.intellij.lang.ASTNode
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.ModificationTracker
import com.intellij.openapi.util.SimpleModificationTracker
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.pom.PomManager
import com.intellij.pom.PomModelAspect
import com.intellij.pom.event.PomModelEvent
import com.intellij.pom.event.PomModelListener
import com.intellij.pom.tree.TreeAspect
import com.intellij.pom.tree.events.TreeChangeEvent
import com.intellij.pom.tree.events.impl.ChangeInfoImpl
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.findTopmostParentInFile
import com.intellij.psi.util.findTopmostParentOfType
import com.intellij.psi.util.parentOfTypes
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.kotlin.kdoc.psi.api.KDoc
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.isAncestor
interface PureKotlinOutOfCodeBlockModificationListener {
fun kotlinFileOutOfCodeBlockChanged(file: KtFile, physical: Boolean)
}
class PureKotlinCodeBlockModificationListener(project: Project) : Disposable {
companion object {
fun getInstance(project: Project): PureKotlinCodeBlockModificationListener = project.service()
private fun isReplLine(file: VirtualFile): Boolean = file.getUserData(KOTLIN_CONSOLE_KEY) == true
private fun incFileModificationCount(file: KtFile) {
val tracker = file.getUserData(PER_FILE_MODIFICATION_TRACKER)
?: file.putUserDataIfAbsent(PER_FILE_MODIFICATION_TRACKER, SimpleModificationTracker())
tracker.incModificationCount()
}
private fun inBlockModifications(elements: Array<ASTNode>): List<KtElement> {
if (elements.any { !it.psi.isValid }) return emptyList()
// When a code fragment is reparsed, Intellij doesn't do an AST diff and considers the entire
// contents to be replaced, which is represented in a POM event as an empty list of changed elements
return elements.map { element ->
val modificationScope = getInsideCodeBlockModificationScope(element.psi) ?: return emptyList()
modificationScope.blockDeclaration
}
}
private fun isSpecificChange(changeSet: TreeChangeEvent, precondition: (ASTNode?) -> Boolean): Boolean =
changeSet.changedElements.all { changedElement ->
val changesByElement = changeSet.getChangesByElement(changedElement)
changesByElement.affectedChildren.all { affectedChild ->
precondition(affectedChild) && changesByElement.getChangeByChild(affectedChild).let { changeByChild ->
if (changeByChild is ChangeInfoImpl) {
val oldChild = changeByChild.oldChildNode
precondition(oldChild)
} else false
}
}
}
private inline fun isCommentChange(changeSet: TreeChangeEvent): Boolean = isSpecificChange(changeSet) { it is PsiComment || it is KDoc }
private inline fun isFormattingChange(changeSet: TreeChangeEvent): Boolean = isSpecificChange(changeSet) { it is PsiWhiteSpace }
private inline fun isStringLiteralChange(changeSet: TreeChangeEvent): Boolean = isSpecificChange(changeSet) {
it?.elementType == KtTokens.REGULAR_STRING_PART &&
it?.psi?.parentOfTypes(KtAnnotationEntry::class, KtWhenCondition::class) == null
}
/**
* Has to be aligned with [getInsideCodeBlockModificationScope] :
*
* result of analysis has to be reflected in dirty scope,
* the only difference is whitespaces and comments
*/
fun getInsideCodeBlockModificationDirtyScope(element: PsiElement): PsiElement? {
if (!element.isPhysical) return null
// dirty scope for whitespaces and comments is the element itself
if (element is PsiWhiteSpace || element is PsiComment || element is KDoc) return element
return getInsideCodeBlockModificationScope(element)?.blockDeclaration
}
fun getInsideCodeBlockModificationScope(element: PsiElement): BlockModificationScopeElement? {
val lambda = element.findTopmostParentOfType<KtLambdaExpression>()
if (lambda is KtLambdaExpression) {
lambda.findTopmostParentOfType<KtSuperTypeCallEntry>()?.findTopmostParentOfType<KtClassOrObject>()?.let {
return BlockModificationScopeElement(it, it)
}
}
val blockDeclaration = element.findTopmostParentInFile { isBlockDeclaration(it) } as? KtDeclaration ?: return null
// KtPsiUtil.getTopmostParentOfType<KtClassOrObject>(element) as? KtDeclaration ?: return null
// should not be local declaration
if (KtPsiUtil.isLocal(blockDeclaration))
return null
val directParentClassOrObject = PsiTreeUtil.getParentOfType(blockDeclaration, KtClassOrObject::class.java)
val parentClassOrObject = directParentClassOrObject
?.takeIf { !it.isTopLevel() && it.hasModifier(KtTokens.INNER_KEYWORD) }?.let {
var e: KtClassOrObject? = it
while (e != null) {
e = PsiTreeUtil.getParentOfType(e, KtClassOrObject::class.java)
if (e?.hasModifier(KtTokens.INNER_KEYWORD) == false) {
break
}
}
e
} ?: directParentClassOrObject
when (blockDeclaration) {
is KtNamedFunction -> {
// if (blockDeclaration.visibilityModifierType()?.toVisibility() == Visibilities.PRIVATE) {
// topClassLikeDeclaration(blockDeclaration)?.let {
// return BlockModificationScopeElement(it, it)
// }
// }
if (blockDeclaration.hasBlockBody()) {
// case like `fun foo(): String {...<caret>...}`
return blockDeclaration.bodyExpression
?.takeIf { it.isAncestor(element) }
?.let {
if (parentClassOrObject == directParentClassOrObject) {
BlockModificationScopeElement(blockDeclaration, it)
} else if (parentClassOrObject != null) {
BlockModificationScopeElement(parentClassOrObject, it)
} else null
}
} else if (blockDeclaration.hasDeclaredReturnType()) {
// case like `fun foo(): String = b<caret>labla`
return blockDeclaration.initializer
?.takeIf { it.isAncestor(element) }
?.let {
if (parentClassOrObject == directParentClassOrObject) {
BlockModificationScopeElement(blockDeclaration, it)
} else if (parentClassOrObject != null) {
BlockModificationScopeElement(parentClassOrObject, it)
} else null
}
}
}
is KtProperty -> {
// if (blockDeclaration.visibilityModifierType()?.toVisibility() == Visibilities.PRIVATE) {
// topClassLikeDeclaration(blockDeclaration)?.let {
// return BlockModificationScopeElement(it, it)
// }
// }
if (blockDeclaration.typeReference != null &&
// TODO: it's a workaround for KTIJ-20240 :
// FE does not report CONSTANT_EXPECTED_TYPE_MISMATCH within a property within a class
(parentClassOrObject == null || element !is KtConstantExpression)
) {
// adding annotations to accessor is the same as change contract of property
if (element !is KtAnnotated || element.annotationEntries.isEmpty()) {
val properExpression = blockDeclaration.accessors
.firstOrNull { (it.initializer ?: it.bodyExpression).isAncestor(element) }
?: blockDeclaration.initializer?.takeIf {
// name references changes in property initializer are OCB, see KT-38443, KT-38762
it.isAncestor(element) && !it.anyDescendantOfType<KtNameReferenceExpression>()
}
if (properExpression != null) {
val declaration =
blockDeclaration.findTopmostParentOfType<KtClassOrObject>() as? KtElement
if (declaration != null) {
return if (parentClassOrObject == directParentClassOrObject) {
BlockModificationScopeElement(declaration, properExpression)
} else if (parentClassOrObject != null) {
BlockModificationScopeElement(parentClassOrObject, properExpression)
} else null
}
}
}
}
}
is KtScriptInitializer -> {
return (blockDeclaration.body as? KtCallExpression)
?.lambdaArguments
?.lastOrNull()
?.getLambdaExpression()
?.takeIf { it.isAncestor(element) }
?.let { BlockModificationScopeElement(blockDeclaration, it) }
}
is KtClassInitializer -> {
blockDeclaration
.takeIf { it.isAncestor(element) }
?.let { ktClassInitializer ->
parentClassOrObject?.let {
return if (parentClassOrObject == directParentClassOrObject) {
BlockModificationScopeElement(it, ktClassInitializer)
} else {
BlockModificationScopeElement(parentClassOrObject, ktClassInitializer)
}
}
}
}
is KtSecondaryConstructor -> {
blockDeclaration.takeIf {
it.bodyExpression?.isAncestor(element) ?: false || it.getDelegationCallOrNull()?.isAncestor(element) ?: false
}?.let { ktConstructor ->
parentClassOrObject?.let {
return if (parentClassOrObject == directParentClassOrObject) {
BlockModificationScopeElement(it, ktConstructor)
} else {
BlockModificationScopeElement(parentClassOrObject, ktConstructor)
}
}
}
}
// is KtClassOrObject -> {
// return when (element) {
// is KtProperty, is KtNamedFunction -> {
// if ((element as? KtModifierListOwner)?.visibilityModifierType()?.toVisibility() == Visibilities.PRIVATE)
// BlockModificationScopeElement(blockDeclaration, blockDeclaration) else null
// }
// else -> null
// }
// }
else -> throw IllegalStateException()
}
return null
}
data class BlockModificationScopeElement(val blockDeclaration: KtElement, val element: KtElement)
fun isBlockDeclaration(declaration: PsiElement): Boolean {
return declaration is KtProperty ||
declaration is KtNamedFunction ||
declaration is KtClassInitializer ||
declaration is KtSecondaryConstructor ||
declaration is KtScriptInitializer
}
}
private val listeners: MutableList<PureKotlinOutOfCodeBlockModificationListener> = ContainerUtil.createLockFreeCopyOnWriteList()
private val outOfCodeBlockModificationTrackerImpl = SimpleModificationTracker()
val outOfCodeBlockModificationTracker = ModificationTracker { outOfCodeBlockModificationTrackerImpl.modificationCount }
init {
val treeAspect: TreeAspect = TreeAspect.getInstance(project)
val model = PomManager.getModel(project)
model.addModelListener(
object : PomModelListener {
override fun isAspectChangeInteresting(aspect: PomModelAspect): Boolean = aspect == treeAspect
override fun modelChanged(event: PomModelEvent) {
val changeSet = event.getChangeSet(treeAspect) as TreeChangeEvent? ?: return
val ktFile = changeSet.rootElement.psi.containingFile as? KtFile ?: return
incFileModificationCount(ktFile)
val changedElements = changeSet.changedElements
// skip change if it contains only virtual/fake change
if (changedElements.isNotEmpty()) {
// ignore formatting (whitespaces etc)
if (isFormattingChange(changeSet) ||
isCommentChange(changeSet) ||
isStringLiteralChange(changeSet)
) return
}
val inBlockElements = inBlockModifications(changedElements)
val physicalFile = ktFile.isPhysical
if (inBlockElements.isEmpty()) {
val physical = physicalFile && !isReplLine(ktFile.virtualFile)
if (physical) {
outOfCodeBlockModificationTrackerImpl.incModificationCount()
}
ktFile.incOutOfBlockModificationCount()
didChangeKotlinCode(ktFile, physical)
} else if (physicalFile) {
inBlockElements.forEach { it.containingKtFile.addInBlockModifiedItem(it) }
}
}
},
this,
)
}
fun addListener(listener: PureKotlinOutOfCodeBlockModificationListener, parentDisposable: Disposable) {
listeners.add(listener)
Disposer.register(parentDisposable) { removeModelListener(listener) }
}
fun removeModelListener(listener: PureKotlinOutOfCodeBlockModificationListener) {
listeners.remove(listener)
}
private fun didChangeKotlinCode(ktFile: KtFile, physical: Boolean) {
listeners.forEach {
it.kotlinFileOutOfCodeBlockChanged(ktFile, physical)
}
}
override fun dispose() = Unit
}
private val PER_FILE_MODIFICATION_TRACKER = Key<SimpleModificationTracker>("FILE_OUT_OF_BLOCK_MODIFICATION_COUNT")
val KtFile.perFileModificationTracker: ModificationTracker
get() = putUserDataIfAbsent(PER_FILE_MODIFICATION_TRACKER, SimpleModificationTracker())
private val FILE_OUT_OF_BLOCK_MODIFICATION_COUNT = Key<Long>("FILE_OUT_OF_BLOCK_MODIFICATION_COUNT")
val KtFile.outOfBlockModificationCount: Long by NotNullableUserDataProperty(FILE_OUT_OF_BLOCK_MODIFICATION_COUNT, 0)
private fun KtFile.incOutOfBlockModificationCount() {
clearInBlockModifications()
val count = getUserData(FILE_OUT_OF_BLOCK_MODIFICATION_COUNT) ?: 0
putUserData(FILE_OUT_OF_BLOCK_MODIFICATION_COUNT, count + 1)
}
/**
* inBlockModifications is a collection of block elements those have in-block modifications
*/
private val IN_BLOCK_MODIFICATIONS = Key<MutableCollection<KtElement>>("IN_BLOCK_MODIFICATIONS")
private val FILE_IN_BLOCK_MODIFICATION_COUNT = Key<Long>("FILE_IN_BLOCK_MODIFICATION_COUNT")
val KtFile.inBlockModificationCount: Long by NotNullableUserDataProperty(FILE_IN_BLOCK_MODIFICATION_COUNT, 0)
val KtFile.inBlockModifications: Collection<KtElement>
get() {
val collection = getUserData(IN_BLOCK_MODIFICATIONS)
return collection ?: emptySet()
}
private fun KtFile.addInBlockModifiedItem(element: KtElement) {
val collection = putUserDataIfAbsent(IN_BLOCK_MODIFICATIONS, mutableSetOf())
synchronized(collection) {
val needToAddBlock = collection.none { it.isAncestor(element, strict = false) }
if (needToAddBlock) {
collection.removeIf { element.isAncestor(it, strict = false) }
collection.add(element)
}
}
val count = getUserData(FILE_IN_BLOCK_MODIFICATION_COUNT) ?: 0
putUserData(FILE_IN_BLOCK_MODIFICATION_COUNT, count + 1)
}
fun KtFile.clearInBlockModifications() {
val collection = getUserData(IN_BLOCK_MODIFICATIONS)
collection?.let {
synchronized(it) {
it.clear()
}
}
} | plugins/kotlin/base/analysis/src/org/jetbrains/kotlin/idea/caches/trackers/PureKotlinCodeBlockModificationListener.kt | 1580153831 |
// 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.intellij.build.images.sync
import java.io.File
import java.io.IOException
import java.util.stream.Collectors
import java.util.stream.Stream
import kotlin.math.max
internal val GIT = (System.getenv("TEAMCITY_GIT_PATH") ?: System.getenv("GIT") ?: "git").also {
val noGitFound = "Git is not found, please specify path to git executable in TEAMCITY_GIT_PATH or GIT or add it to PATH"
try {
val gitVersion = execute(null, it, "--version")
if (gitVersion.isBlank()) error(noGitFound)
log(gitVersion)
}
catch (e: IOException) {
throw IllegalStateException(noGitFound, e)
}
}
internal fun gitPull(repo: File) = try {
execute(repo, GIT, "pull", "--rebase")
}
catch (e: Exception) {
callSafely(printStackTrace = false) {
execute(repo, GIT, "rebase", "--abort")
}
log("Unable to pull changes for $repo: ${e.message}")
}
/**
* @param dirToList optional dir in [repo] from which to list files
* @return map of file paths (relative to [dirToList]) to [GitObject]
*/
internal fun listGitObjects(
repo: File, dirToList: File?,
fileFilter: (File) -> Boolean = { true }
): Map<String, GitObject> = listGitTree(repo, dirToList, fileFilter)
.collect(Collectors.toMap({ it.first }, { it.second }))
private fun listGitTree(
repo: File, dirToList: File?,
fileFilter: (File) -> Boolean
): Stream<Pair<String, GitObject>> {
val relativeDirToList = dirToList?.relativeTo(repo)?.path ?: ""
log("Inspecting $repo/$relativeDirToList")
if (!isUnderTeamCity()) gitPull(repo)
return execute(repo, GIT, "ls-tree", "HEAD", "-r", relativeDirToList)
.trim().lines().stream()
.filter(String::isNotBlank).map { line ->
// format: <mode> SP <type> SP <object> TAB <file>
line.splitWithTab()
.also { if (it.size != 2) error(line) }
.let { it[0].splitWithSpace() + it[1] }
.also { if (it.size != 4) error(line) }
}
.filter { fileFilter(repo.resolve(it[3].removeSuffix("\"").removePrefix("\""))) }
// <file>, <object>, repo
.map { GitObject(it[3], it[2], repo) }
.map { it.path.removePrefix("$relativeDirToList/") to it }
}
/**
* @param repos multiple git repos from which to list files
* @param root root repo
* @return map of file paths (relative to [root]) to [GitObject]
*/
internal fun listGitObjects(
root: File, repos: List<File>,
fileFilter: (File) -> Boolean = { true }
): Map<String, GitObject> = repos.parallelStream().flatMap { repo ->
listGitTree(repo, null, fileFilter).map {
// root relative <file> path to git object
val rootRelativePath = repo.relativeTo(root).path
if (rootRelativePath.isEmpty()) {
it.first
}
else {
"$rootRelativePath/${it.first}"
} to it.second
}
}.collect(Collectors.toMap({ it.first }, { it.second }))
/**
* @param path path relative to [repo]
*/
internal data class GitObject(val path: String, val hash: String, val repo: File) {
val file = File(repo, path)
}
/**
* @param dir path in repo
* @return root of repo
*/
internal fun findGitRepoRoot(dir: File, silent: Boolean = false): File = when {
dir.isDirectory && dir.listFiles()?.find { file ->
file.isDirectory && file.name == ".git"
} != null -> {
if (!silent) log("Git repo found in $dir")
dir
}
dir.parentFile != null -> {
if (!silent) log("No git repo found in $dir")
findGitRepoRoot(dir.parentFile, silent)
}
else -> error("No git repo found in $dir")
}
internal fun cleanup(repo: File) {
execute(repo, GIT, "reset", "--hard")
execute(repo, GIT, "clean", "-xfd")
}
internal fun stageFiles(files: List<String>, repo: File) {
// OS has argument length limit
splitAndTry(1000, files, repo) {
execute(repo, GIT, "add", "--no-ignore-removal", "--ignore-errors", *it.toTypedArray())
}
}
private fun splitAndTry(factor: Int, files: List<String>, repo: File, block: (files: List<String>) -> Unit) {
files.split(factor).forEach {
try {
block(it)
}
catch (e: Exception) {
if (e.message?.contains("did not match any files") == true) return
val finerFactor: Int = factor / 2
if (finerFactor < 1) throw e
log("Git add command failed with ${e.message}")
splitAndTry(finerFactor, files, repo, block)
}
}
}
internal fun commit(repo: File, message: String, user: String, email: String) {
execute(
repo, GIT,
"-c", "user.name=$user",
"-c", "user.email=$email",
"commit", "-m", message,
"--author=$user <$email>"
)
}
internal fun commitAndPush(repo: File, branch: String, message: String, user: String, email: String, force: Boolean = false): CommitInfo {
commit(repo, message, user, email)
push(repo, branch, user, email, force)
return commitInfo(repo) ?: error("Unable to read last commit")
}
internal fun checkout(repo: File, branch: String) = execute(repo, GIT, "checkout", branch)
internal fun push(repo: File, spec: String, user: String? = null, email: String? = null, force: Boolean = false) =
retry(doRetry = { beforePushRetry(it, repo, spec, user, email) }) {
var args = arrayOf("origin", spec)
if (force) args += "--force"
execute(repo, GIT, "push", *args, withTimer = true)
}
private fun beforePushRetry(e: Throwable, repo: File, spec: String, user: String?, email: String?): Boolean {
if (!isGitServerUnavailable(e)) {
val specParts = spec.split(':')
val identity = if (user != null && email != null) arrayOf(
"-c", "user.name=$user",
"-c", "user.email=$email"
)
else emptyArray()
execute(repo, GIT, *identity, "pull", "--rebase=true", "origin", if (specParts.count() == 2) {
"${specParts[1]}:${specParts[0]}"
}
else spec, withTimer = true)
}
return true
}
private fun isGitServerUnavailable(e: Throwable) = with(e.message ?: "") {
contains("remote end hung up unexpectedly")
|| contains("Service is in readonly mode")
|| contains("failed to lock")
|| contains("Connection timed out")
}
@Volatile
private var origins = emptyMap<File, String>()
private val originsGuard = Any()
internal fun getOriginUrl(repo: File): String {
if (!origins.containsKey(repo)) {
synchronized(originsGuard) {
if (!origins.containsKey(repo)) {
origins += repo to execute(repo, GIT, "ls-remote", "--get-url", "origin")
.removeSuffix(System.lineSeparator())
.trim()
}
}
}
return origins.getValue(repo)
}
@Volatile
private var latestChangeCommits = emptyMap<String, CommitInfo>()
private val latestChangeCommitsGuard = Any()
/**
* @param path path relative to [repo]
*/
internal fun latestChangeCommit(path: String, repo: File): CommitInfo? {
val file = repo.resolve(path).canonicalPath
if (!latestChangeCommits.containsKey(file)) {
synchronized(file) {
if (!latestChangeCommits.containsKey(file)) {
val commitInfo = monoRepoMergeAwareCommitInfo(repo, path)
if (commitInfo != null) {
synchronized(latestChangeCommitsGuard) {
latestChangeCommits += file to commitInfo
}
}
else return null
}
}
}
return latestChangeCommits.getValue(file)
}
private fun monoRepoMergeAwareCommitInfo(repo: File, path: String) =
pathInfo(repo, "--", path)?.let { commitInfo ->
if (commitInfo.parents.size == 6 && commitInfo.subject.contains("Merge all repositories")) {
val strippedPath = path.stripMergedRepoPrefix()
commitInfo.parents.asSequence().mapNotNull {
pathInfo(repo, it, "--", strippedPath)
}.firstOrNull()
}
else commitInfo
}
private fun String.stripMergedRepoPrefix(): String = when {
startsWith("community/android/tools-base/") -> removePrefix("community/android/tools-base/")
startsWith("community/android/") -> removePrefix("community/android/")
startsWith("community/") -> removePrefix("community/")
startsWith("contrib/") -> removePrefix("contrib/")
startsWith("CIDR/") -> removePrefix("CIDR/")
else -> this
}
/**
* @return latest commit (or merge) time
*/
internal fun latestChangeTime(path: String, repo: File): Long {
// latest commit for file
val commit = latestChangeCommit(path, repo)
if (commit == null) return -1
val mergeCommit = findMergeCommit(repo, commit.hash)
return max(commit.timestamp, mergeCommit?.timestamp ?: -1)
}
/**
* see [https://stackoverflow.com/questions/8475448/find-merge-commit-which-include-a-specific-commit]
*/
private fun findMergeCommit(repo: File, commit: String, searchUntil: String = "HEAD"): CommitInfo? {
// list commits that are both descendants of commit hash and ancestors of HEAD
val ancestryPathList = execute(repo, GIT, "rev-list", "$commit..$searchUntil", "--ancestry-path")
.lineSequence().filter { it.isNotBlank() }
// follow only the first parent commit upon seeing a merge commit
val firstParentList = execute(repo, GIT, "rev-list", "$commit..$searchUntil", "--first-parent")
.lineSequence().filter { it.isNotBlank() }.toSet()
// last common commit may be the latest merge
return ancestryPathList
.lastOrNull(firstParentList::contains)
?.let { commitInfo(repo, it) }
?.takeIf {
// should be merge
it.parents.size > 1 &&
// but not some branch merge right after [commit]
it.parents.first() != commit
}?.let {
when {
// if it's a merge of master into master then all parents belong to master but the first one doesn't lead to [commit]
isMergeOfMasterIntoMaster(repo, it) -> findMergeCommit(repo, commit, it.parents[1])
it.parents.size > 2 -> {
log("WARNING: Merge commit ${it.hash} for $commit in $repo is found but it has more than two parents (one of them could be master), skipping")
null
}
// merge is found
else -> it
}
}
}
/**
* Inspecting commit subject which isn't reliable criteria, may need to be adjusted
*
* @param merge merge commit
*/
private fun isMergeOfMasterIntoMaster(repo: File, merge: CommitInfo) =
merge.parents.size == 2 && with(merge.subject) {
val head = head(repo)
(contains("Merge branch $head") ||
contains("Merge branch '$head'") ||
contains("origin/$head")) &&
(!contains(" into ") ||
endsWith("into $head") ||
endsWith("into '$head'"))
}
@Volatile
private var heads = emptyMap<File, String>()
private val headsGuard = Any()
internal fun head(repo: File): String {
if (!heads.containsKey(repo)) {
synchronized(headsGuard) {
if (!heads.containsKey(repo)) {
heads += repo to execute(repo, GIT, "rev-parse", "--abbrev-ref", "HEAD").removeSuffix(System.lineSeparator())
}
}
}
return heads.getValue(repo)
}
internal fun commitInfo(repo: File, vararg args: String) = gitLog(repo, *args).singleOrNull()
private fun pathInfo(repo: File, vararg args: String) = gitLog(repo, "--follow", *args).singleOrNull()
private fun gitLog(repo: File, vararg args: String): List<CommitInfo> =
execute(
repo, GIT, "log",
"--max-count", "1",
"--format=%H/%cd/%P/%cn/%ce/%s",
"--date=raw", *args
).lineSequence().mapNotNull {
val output = it.splitNotBlank("/")
// <hash>/<timestamp> <timezone>/<parent hashes>/committer email/<subject>
if (output.size >= 6) {
CommitInfo(
repo = repo,
hash = output[0],
timestamp = output[1].splitWithSpace()[0].toLong(),
parents = output[2].splitWithSpace(),
committer = Committer(name = output[3], email = output[4]),
subject = output.subList(5, output.size)
.joinToString(separator = "/")
.removeSuffix(System.lineSeparator())
)
}
else null
}.toList()
internal data class CommitInfo(
val hash: String,
val timestamp: Long,
val subject: String,
val committer: Committer,
val parents: List<String>,
val repo: File
)
internal data class Committer(val name: String, val email: String)
internal fun gitStatus(repo: File, includeUntracked: Boolean = false) = Changes().apply {
execute(repo, GIT, "status", "--short", "--untracked-files=${if (includeUntracked) "all" else "no"}", "--ignored=no")
.lineSequence()
.filter(String::isNotBlank)
.forEach {
val (status, path) = it.splitToSequence("->", " ")
.filter(String::isNotBlank)
.map(String::trim)
.toList()
val type = when(status) {
"A", "??" -> Changes.Type.ADDED
"M" -> Changes.Type.MODIFIED
"D" -> Changes.Type.DELETED
else -> error("Unknown change type: $status. Git status line: $it")
}
register(type, listOf(path))
}
}
internal fun gitStage(repo: File) = execute(repo, GIT, "diff", "--cached", "--name-status")
internal fun changesFromCommit(repo: File, hash: String) =
execute(repo, GIT, "show", "--pretty=format:none", "--name-status", "--no-renames", hash)
.lineSequence().map { it.trim() }
.filter { it.isNotEmpty() && it != "none" }
.map { it.splitWithTab() }
.onEach { if (it.size != 2) error(it.joinToString(" ")) }
.map {
val (type, path) = it
when (type) {
"A" -> Changes.Type.ADDED
"D" -> Changes.Type.DELETED
"M" -> Changes.Type.MODIFIED
"T" -> Changes.Type.MODIFIED
else -> return@map null
} to path
}.filterNotNull().groupBy({ it.first }, { it.second })
internal fun gitClone(uri: String, dir: File): File {
val filesBeforeClone = dir.listFiles()?.toList() ?: emptyList()
execute(dir, GIT, "clone", uri)
return ((dir.listFiles()?.toList() ?: emptyList()) - filesBeforeClone).first {
uri.contains(it.name)
}
}
| platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/gitUtils.kt | 3309640877 |
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.time.Duration
import java.util.regex.Pattern
fun readPage(client: HttpClient, uri: URI): String {
val request = HttpRequest.newBuilder()
.GET()
.uri(uri)
.timeout(Duration.ofSeconds(5))
.setHeader("accept", "text/html")
.build()
val response = client.send(request, HttpResponse.BodyHandlers.ofString())
return response.body()
}
fun main() {
var re = Pattern.compile("<li><a href=\"/wiki/(.*?)\"", Pattern.DOTALL + Pattern.MULTILINE)
val client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.followRedirects(HttpClient.Redirect.NORMAL)
.connectTimeout(Duration.ofSeconds(5))
.build()
val uri = URI("http", "rosettacode.org", "/wiki/Category:Programming_Tasks", "")
var body = readPage(client, uri)
var matcher = re.matcher(body)
val tasks = mutableListOf<String>()
while (matcher.find()) {
tasks.add(matcher.group(1))
}
val base = "http://rosettacode.org/wiki/"
val limit = 3L
re = Pattern.compile(".*using any language you may know.</div>(.*?)<div id=\"toc\".*", Pattern.DOTALL + Pattern.MULTILINE)
val re2 = Pattern.compile("</?[^>]*>")
for (task in tasks.stream().limit(limit)) {
val page = base + task
body = readPage(client, URI(page))
matcher = re.matcher(body)
if (matcher.matches()) {
val group = matcher.group(1)
val m2 = re2.matcher(group)
val text = m2.replaceAll("")
println(text)
}
}
}
| Rosetta_Code/Tasks_without_examples/Kotlin/TasksWithoutExamples/src/main/kotlin/main.kt | 3992464302 |
/**
* Copyright 2010 - 2022 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
*
* 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 jetbrains.exodus.core.dataStructures
import jetbrains.exodus.core.execution.SharedTimer
class NonAdjustableConcurrentObjectCache<K, V> @JvmOverloads constructor(size: Int = DEFAULT_SIZE,
numberOfGenerations: Int = DEFAULT_NUMBER_OF_GENERATIONS)
: ConcurrentObjectCache<K, V>(size, numberOfGenerations) {
override fun getCacheAdjuster(): SharedTimer.ExpirablePeriodicTask? = null
}
class NonAdjustableConcurrentLongObjectCache<V> @JvmOverloads constructor(size: Int = DEFAULT_SIZE,
numberOfGenerations: Int = DEFAULT_NUMBER_OF_GENERATIONS)
: ConcurrentLongObjectCache<V>(size, numberOfGenerations) {
override fun getCacheAdjuster(): SharedTimer.ExpirablePeriodicTask? = null
}
class NonAdjustableConcurrentIntObjectCache<V> @JvmOverloads constructor(size: Int = DEFAULT_SIZE,
numberOfGenerations: Int = DEFAULT_NUMBER_OF_GENERATIONS)
: ConcurrentIntObjectCache<V>(size, numberOfGenerations) {
override fun getCacheAdjuster(): SharedTimer.ExpirablePeriodicTask? = null
} | utils/src/main/kotlin/jetbrains/exodus/core/dataStructures/NonAdjustableCaches.kt | 109478491 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.