repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
53 values
size
stringlengths
2
6
content
stringlengths
73
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
977
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Code-Tome/hexameter
mixite.benchmarks/src/commonMain/kotlin/org/hexworks/mixite/core/api/HexagonPerfTest.kt
1
1144
package org.hexworks.mixite.core.api import kotlinx.benchmark.* import org.hexworks.mixite.core.api.contract.HexagonDataStorage import org.hexworks.mixite.core.api.defaults.DefaultHexagonDataStorage import org.hexworks.mixite.core.api.defaults.DefaultSatelliteData import org.hexworks.mixite.core.internal.GridData @State(Scope.Benchmark) @Warmup(iterations = 5) @Measurement(iterations = 5) @Suppress("Unused") open class HexagonPerfTest { private lateinit var gridData: GridData private lateinit var cc: CubeCoordinate private lateinit var store: HexagonDataStorage<DefaultSatelliteData> @Setup fun setUp() { gridData = HexagonalGridBuilder<DefaultSatelliteData>() .setGridLayout(HexagonalGridLayout.RECTANGULAR) .setGridHeight(1) .setGridWidth(1) .setRadius(10.0) .build() .gridData cc = CubeCoordinate.fromCoordinates(-49, 0) store = DefaultHexagonDataStorage() } // @Benchmark fun constructHexagon(bh: Blackhole) { // bh.consume(HexagonImpl(gridData, cc, store)) } }
mit
1ff568613222d384456ac9e0f6b58e86
29.918919
72
0.692308
4.34981
false
false
false
false
AndroidX/androidx
compose/ui/ui/src/androidMain/kotlin/androidx/compose/ui/text/input/RecordingInputConnection.android.kt
3
15989
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.text.input import android.os.Bundle import android.os.Handler import android.text.TextUtils import android.util.Log import android.view.KeyEvent import android.view.inputmethod.CompletionInfo import android.view.inputmethod.CorrectionInfo import android.view.inputmethod.EditorInfo import android.view.inputmethod.ExtractedText import android.view.inputmethod.ExtractedTextRequest import android.view.inputmethod.InputConnection import android.view.inputmethod.InputContentInfo internal const val DEBUG = false internal const val TAG = "RecordingIC" private const val DEBUG_CLASS = "RecordingInputConnection" /** * [InputConnection] implementation that binds Android IME to Compose. * * @param initState The initial input state. * @param eventCallback An input event listener. * @param autoCorrect Whether autoCorrect is enabled. */ internal class RecordingInputConnection( initState: TextFieldValue, val eventCallback: InputEventCallback2, val autoCorrect: Boolean ) : InputConnection { // The depth of the batch session. 0 means no session. private var batchDepth: Int = 0 // The input state. internal var mTextFieldValue: TextFieldValue = initState set(value) { if (DEBUG) { logDebug("mTextFieldValue : $field -> $value") } field = value } /** * The token to be used for reporting updateExtractedText API. * * 0 if no token was specified from IME. */ private var currentExtractedTextRequestToken = 0 /** * True if IME requested extracted text monitor mode. * * If extracted text monitor mode is ON, need to call updateExtractedText API whenever the text * is changed. */ private var extractedTextMonitorMode = false // The recoding editing ops. private val editCommands = mutableListOf<EditCommand>() private var isActive: Boolean = true private inline fun ensureActive(block: () -> Unit): Boolean { return isActive.also { applying -> if (applying) { block() } } } /** * Updates the input state and tells it to the IME. * * This function may emits updateSelection and updateExtractedText to notify IMEs that the text * contents has changed if needed. */ fun updateInputState( state: TextFieldValue, inputMethodManager: InputMethodManager, ) { if (!isActive) return if (DEBUG) { logDebug("RecordingInputConnection.updateInputState: $state") } mTextFieldValue = state if (extractedTextMonitorMode) { inputMethodManager.updateExtractedText( currentExtractedTextRequestToken, state.toExtractedText() ) } // updateSelection API requires -1 if there is no composition val compositionStart = state.composition?.min ?: -1 val compositionEnd = state.composition?.max ?: -1 if (DEBUG) { logDebug( "updateSelection(" + "selection = (${state.selection.min},${state.selection.max}), " + "composition = ($compositionStart, $compositionEnd))" ) } inputMethodManager.updateSelection( state.selection.min, state.selection.max, compositionStart, compositionEnd ) } // Add edit op to internal list with wrapping batch edit. private fun addEditCommandWithBatch(editCommand: EditCommand) { beginBatchEditInternal() try { editCommands.add(editCommand) } finally { endBatchEditInternal() } } // ///////////////////////////////////////////////////////////////////////////////////////////// // Callbacks for text editing session // ///////////////////////////////////////////////////////////////////////////////////////////// override fun beginBatchEdit(): Boolean = ensureActive { if (DEBUG) { logDebug("beginBatchEdit()") } return beginBatchEditInternal() } private fun beginBatchEditInternal(): Boolean { batchDepth++ return true } override fun endBatchEdit(): Boolean { if (DEBUG) { logDebug("endBatchEdit()") } return endBatchEditInternal() } private fun endBatchEditInternal(): Boolean { batchDepth-- if (batchDepth == 0 && editCommands.isNotEmpty()) { eventCallback.onEditCommands(editCommands.toMutableList()) editCommands.clear() } return batchDepth > 0 } override fun closeConnection() { if (DEBUG) { logDebug("closeConnection()") } editCommands.clear() batchDepth = 0 isActive = false eventCallback.onConnectionClosed(this) } // ///////////////////////////////////////////////////////////////////////////////////////////// // Callbacks for text editing // ///////////////////////////////////////////////////////////////////////////////////////////// override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean = ensureActive { if (DEBUG) { logDebug("commitText(\"$text\", $newCursorPosition)") } addEditCommandWithBatch(CommitTextCommand(text.toString(), newCursorPosition)) } override fun setComposingRegion(start: Int, end: Int): Boolean = ensureActive { if (DEBUG) { logDebug("setComposingRegion($start, $end)") } addEditCommandWithBatch(SetComposingRegionCommand(start, end)) } override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean = ensureActive { if (DEBUG) { logDebug("setComposingText(\"$text\", $newCursorPosition)") } addEditCommandWithBatch(SetComposingTextCommand(text.toString(), newCursorPosition)) } override fun deleteSurroundingTextInCodePoints(beforeLength: Int, afterLength: Int): Boolean = ensureActive { if (DEBUG) { logDebug("deleteSurroundingTextInCodePoints($beforeLength, $afterLength)") } addEditCommandWithBatch( DeleteSurroundingTextInCodePointsCommand(beforeLength, afterLength) ) return true } override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean = ensureActive { if (DEBUG) { logDebug("deleteSurroundingText($beforeLength, $afterLength)") } addEditCommandWithBatch(DeleteSurroundingTextCommand(beforeLength, afterLength)) return true } override fun setSelection(start: Int, end: Int): Boolean = ensureActive { if (DEBUG) { logDebug("setSelection($start, $end)") } addEditCommandWithBatch(SetSelectionCommand(start, end)) return true } override fun finishComposingText(): Boolean = ensureActive { if (DEBUG) { logDebug("finishComposingText()") } addEditCommandWithBatch(FinishComposingTextCommand()) return true } override fun sendKeyEvent(event: KeyEvent): Boolean = ensureActive { if (DEBUG) { logDebug("sendKeyEvent($event)") } eventCallback.onKeyEvent(event) return true } // ///////////////////////////////////////////////////////////////////////////////////////////// // Callbacks for retrieving editing buffers // ///////////////////////////////////////////////////////////////////////////////////////////// override fun getTextBeforeCursor(maxChars: Int, flags: Int): CharSequence { // TODO(b/135556699) should return styled text val result = mTextFieldValue.getTextBeforeSelection(maxChars).toString() if (DEBUG) { logDebug("getTextBeforeCursor($maxChars, $flags): $result") } return result } override fun getTextAfterCursor(maxChars: Int, flags: Int): CharSequence { // TODO(b/135556699) should return styled text val result = mTextFieldValue.getTextAfterSelection(maxChars).toString() if (DEBUG) { logDebug("getTextAfterCursor($maxChars, $flags): $result") } return result } override fun getSelectedText(flags: Int): CharSequence? { // https://source.chromium.org/chromium/chromium/src/+/master:content/public/android/java/src/org/chromium/content/browser/input/TextInputState.java;l=56;drc=0e20d1eb38227949805a4c0e9d5cdeddc8d23637 val result: CharSequence? = if (mTextFieldValue.selection.collapsed) { null } else { // TODO(b/135556699) should return styled text mTextFieldValue.getSelectedText().toString() } if (DEBUG) { logDebug("getSelectedText($flags): $result") } return result } override fun requestCursorUpdates(cursorUpdateMode: Int): Boolean = ensureActive { if (DEBUG) { logDebug("requestCursorUpdates($cursorUpdateMode)") } Log.w(TAG, "requestCursorUpdates is not supported") return false } override fun getExtractedText(request: ExtractedTextRequest?, flags: Int): ExtractedText { if (DEBUG) { logDebug("getExtractedText($request, $flags)") } extractedTextMonitorMode = (flags and InputConnection.GET_EXTRACTED_TEXT_MONITOR) != 0 if (extractedTextMonitorMode) { currentExtractedTextRequestToken = request?.token ?: 0 } // TODO(b/135556699) should return styled text val extractedText = mTextFieldValue.toExtractedText() if (DEBUG) { with(extractedText) { logDebug( "getExtractedText() return: text: \"$text\"" + ",partialStartOffset $partialStartOffset" + ",partialEndOffset $partialEndOffset" + ",selectionStart $selectionStart" + ",selectionEnd $selectionEnd" + ",flags $flags" ) } } return extractedText } // ///////////////////////////////////////////////////////////////////////////////////////////// // Editor action and Key events. // ///////////////////////////////////////////////////////////////////////////////////////////// override fun performContextMenuAction(id: Int): Boolean = ensureActive { if (DEBUG) { logDebug("performContextMenuAction($id)") } when (id) { android.R.id.selectAll -> { addEditCommandWithBatch(SetSelectionCommand(0, mTextFieldValue.text.length)) } // TODO(siyamed): Need proper connection to cut/copy/paste android.R.id.cut -> sendSynthesizedKeyEvent(KeyEvent.KEYCODE_CUT) android.R.id.copy -> sendSynthesizedKeyEvent(KeyEvent.KEYCODE_COPY) android.R.id.paste -> sendSynthesizedKeyEvent(KeyEvent.KEYCODE_PASTE) android.R.id.startSelectingText -> {} // not supported android.R.id.stopSelectingText -> {} // not supported android.R.id.copyUrl -> {} // not supported android.R.id.switchInputMethod -> {} // not supported else -> { // not supported } } return false } private fun sendSynthesizedKeyEvent(code: Int) { sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, code)) sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, code)) } override fun performEditorAction(editorAction: Int): Boolean = ensureActive { if (DEBUG) { logDebug("performEditorAction($editorAction)") } val imeAction = when (editorAction) { EditorInfo.IME_ACTION_UNSPECIFIED -> ImeAction.Default EditorInfo.IME_ACTION_DONE -> ImeAction.Done EditorInfo.IME_ACTION_SEND -> ImeAction.Send EditorInfo.IME_ACTION_SEARCH -> ImeAction.Search EditorInfo.IME_ACTION_PREVIOUS -> ImeAction.Previous EditorInfo.IME_ACTION_NEXT -> ImeAction.Next EditorInfo.IME_ACTION_GO -> ImeAction.Go else -> { Log.w(TAG, "IME sends unsupported Editor Action: $editorAction") ImeAction.Default } } eventCallback.onImeAction(imeAction) return true } // ///////////////////////////////////////////////////////////////////////////////////////////// // Unsupported callbacks // ///////////////////////////////////////////////////////////////////////////////////////////// override fun commitCompletion(text: CompletionInfo?): Boolean = ensureActive { if (DEBUG) { logDebug("commitCompletion(${text?.text})") } // We don't support this callback. // The API documents says this should return if the input connection is no longer valid, but // The Chromium implementation already returning false, so assuming it is safe to return // false if not supported. // see https://cs.chromium.org/chromium/src/content/public/android/java/src/org/chromium/content/browser/input/ThreadedInputConnection.java return false } override fun commitCorrection(correctionInfo: CorrectionInfo?): Boolean = ensureActive { if (DEBUG) { logDebug("commitCorrection($correctionInfo),autoCorrect:$autoCorrect") } // Should add an event here so that we can implement the autocorrect highlight // Bug: 170647219 return autoCorrect } override fun getHandler(): Handler? { if (DEBUG) { logDebug("getHandler()") } return null // Returns null means using default Handler } override fun clearMetaKeyStates(states: Int): Boolean = ensureActive { if (DEBUG) { logDebug("clearMetaKeyStates($states)") } // We don't support this callback. // The API documents says this should return if the input connection is no longer valid, but // The Chromium implementation already returning false, so assuming it is safe to return // false if not supported. // see https://cs.chromium.org/chromium/src/content/public/android/java/src/org/chromium/content/browser/input/ThreadedInputConnection.java return false } override fun reportFullscreenMode(enabled: Boolean): Boolean { if (DEBUG) { logDebug("reportFullscreenMode($enabled)") } return false // This value is ignored according to the API docs. } override fun getCursorCapsMode(reqModes: Int): Int { if (DEBUG) { logDebug("getCursorCapsMode($reqModes)") } return TextUtils.getCapsMode(mTextFieldValue.text, mTextFieldValue.selection.min, reqModes) } override fun performPrivateCommand(action: String?, data: Bundle?): Boolean = ensureActive { if (DEBUG) { logDebug("performPrivateCommand($action, $data)") } return true // API doc says we should return true even if we didn't understand the command. } override fun commitContent( inputContentInfo: InputContentInfo, flags: Int, opts: Bundle? ): Boolean = ensureActive { if (DEBUG) { logDebug("commitContent($inputContentInfo, $flags, $opts)") } return false // We don't accept any contents. } private fun logDebug(message: String) { if (DEBUG) { Log.d(TAG, "$DEBUG_CLASS.$message, $isActive") } } }
apache-2.0
b08678b599920127d6d3c70ed8271034
38.677419
206
0.609544
5.308433
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/openapi/ui/FrameWrapper.kt
1
14057
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.ui import com.intellij.application.options.RegistryManager import com.intellij.ide.ui.UISettings.Companion.setupAntialiasing import com.intellij.jdkEx.JdkEx import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.CommonShortcuts import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.impl.MouseGestureManager import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.options.advanced.AdvancedSettings import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.ProjectManagerListener import com.intellij.openapi.ui.popup.util.PopupUtil import com.intellij.openapi.util.* import com.intellij.openapi.wm.* import com.intellij.openapi.wm.ex.IdeFocusTraversalPolicy import com.intellij.openapi.wm.ex.IdeFrameEx import com.intellij.openapi.wm.ex.WindowManagerEx import com.intellij.openapi.wm.impl.GlobalMenuLinux import com.intellij.openapi.wm.impl.IdeFrameDecorator import com.intellij.openapi.wm.impl.IdeGlassPaneImpl import com.intellij.openapi.wm.impl.IdeMenuBar import com.intellij.openapi.wm.impl.LinuxIdeMenuBar.Companion.doBindAppMenuOfParent import com.intellij.openapi.wm.impl.ProjectFrameHelper.appendTitlePart import com.intellij.openapi.wm.impl.customFrameDecorations.header.CustomFrameDialogContent import com.intellij.ui.* import com.intellij.ui.mac.touchbar.TouchbarSupport import com.intellij.util.ui.ImageUtil import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.NonNls import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.resolvedPromise import java.awt.* import java.awt.event.ActionListener import java.awt.event.KeyEvent import java.awt.event.WindowAdapter import java.awt.event.WindowEvent import java.nio.file.Path import javax.swing.* open class FrameWrapper @JvmOverloads constructor(project: Project?, @param:NonNls protected open val dimensionKey: String? = null, private val isDialog: Boolean = false, @NlsContexts.DialogTitle var title: String = "", open var component: JComponent? = null) : Disposable, DataProvider { open var preferredFocusedComponent: JComponent? = null private var images: List<Image> = emptyList() private var isCloseOnEsc = false private var onCloseHandler: BooleanGetter? = null private var frame: Window? = null private var project: Project? = null private var isDisposing = false var isDisposed = false private set protected var statusBar: StatusBar? = null set(value) { field?.let { Disposer.dispose(it) } field = value } init { project?.let { setProject(it) } } fun setProject(project: Project) { this.project = project ApplicationManager.getApplication().messageBus.connect(this).subscribe(ProjectManager.TOPIC, object : ProjectManagerListener { override fun projectClosing(project: Project) { if (project === [email protected]) { close() } } }) } open fun show() { show(true) } fun createContents() { val frame = getFrame() if (frame is JFrame) { frame.defaultCloseOperation = WindowConstants.DO_NOTHING_ON_CLOSE } else { (frame as JDialog).defaultCloseOperation = WindowConstants.DO_NOTHING_ON_CLOSE } frame.addWindowListener(object : WindowAdapter() { override fun windowClosing(e: WindowEvent) { close() } }) UIUtil.decorateWindowHeader((frame as RootPaneContainer).rootPane) if (frame is JFrame) { ToolbarUtil.setTransparentTitleBar(frame, frame.rootPane) { runnable -> Disposer.register(this, Disposable { runnable.run() }) } } val focusListener = object : WindowAdapter() { override fun windowOpened(e: WindowEvent) { val focusManager = IdeFocusManager.getInstance(project) val toFocus = focusManager.getLastFocusedFor(e.window) ?: preferredFocusedComponent ?: focusManager.getFocusTargetFor(component!!) if (toFocus != null) { focusManager.requestFocus(toFocus, true) } } } frame.addWindowListener(focusListener) if (RegistryManager.getInstance().`is`("ide.perProjectModality")) { frame.isAlwaysOnTop = true } Disposer.register(this, Disposable { frame.removeWindowListener(focusListener) }) if (isCloseOnEsc) { addCloseOnEsc(frame as RootPaneContainer) } if (IdeFrameDecorator.isCustomDecorationActive()) { component?.let { component = /*UIUtil.findComponentOfType(it, EditorsSplitters::class.java)?.let { if(frame !is JFrame) null else { val header = CustomHeader.createMainFrameHeader(frame, IdeMenuBar.createMenuBar()) getCustomContentHolder(frame, it, header) } } ?:*/ CustomFrameDialogContent.getCustomContentHolder(frame, it) } } frame.contentPane.add(component!!, BorderLayout.CENTER) if (frame is JFrame) { frame.title = title } else { (frame as JDialog).title = title } if (images.isEmpty()) { AppUIUtil.updateWindowIcon(frame) } else { // unwrap the image before setting as frame's icon frame.iconImages = images.map { ImageUtil.toBufferedImage(it) } } if (SystemInfoRt.isLinux && frame is JFrame && GlobalMenuLinux.isAvailable()) { val parentFrame = WindowManager.getInstance().getFrame(project) if (parentFrame != null) { doBindAppMenuOfParent(frame, parentFrame) } } } fun show(restoreBounds: Boolean) { createContents() val frame = getFrame() val state = dimensionKey?.let { getWindowStateService(project).getState(it, frame) } if (restoreBounds) { loadFrameState(state) } if (SystemInfoRt.isMac) { TouchbarSupport.showWindowActions(this, frame) } frame.isVisible = true } fun close() { if (isDisposed || (onCloseHandler != null && !onCloseHandler!!.get())) { return } // if you remove this line problems will start happen on Mac OS X // 2 projects opened, call Cmd+D on the second opened project and then Esc. // Weird situation: 2nd IdeFrame will be active, but focus will be somewhere inside the 1st IdeFrame // App is unusable until Cmd+Tab, Cmd+tab frame?.isVisible = false Disposer.dispose(this) } override fun dispose() { if (isDisposed) { return } val frame = frame val statusBar = statusBar this.frame = null preferredFocusedComponent = null project = null component = null images = emptyList() isDisposed = true if (statusBar != null) { Disposer.dispose(statusBar) } if (frame != null) { frame.isVisible = false val rootPane = (frame as RootPaneContainer).rootPane frame.removeAll() DialogWrapper.cleanupRootPane(rootPane) if (frame is IdeFrame) { MouseGestureManager.getInstance().remove(frame) } frame.dispose() DialogWrapper.cleanupWindowListeners(frame) } } private fun addCloseOnEsc(frame: RootPaneContainer) { val rootPane = frame.rootPane val closeAction = ActionListener { if (!PopupUtil.handleEscKeyEvent()) { close() } } rootPane.registerKeyboardAction(closeAction, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW) ActionUtil.registerForEveryKeyboardShortcut(rootPane, closeAction, CommonShortcuts.getCloseActiveWindow()) } fun getFrame(): Window { assert(!isDisposed) { "Already disposed!" } var result = frame if (result == null) { val parent = WindowManager.getInstance().getIdeFrame(project)!! result = if (isDialog) createJDialog(parent) else createJFrame(parent) frame = result } return result } val isActive: Boolean get() = frame?.isActive == true protected open fun createJFrame(parent: IdeFrame): JFrame = MyJFrame(this, parent) protected open fun createJDialog(parent: IdeFrame): JDialog = MyJDialog(this, parent) protected open fun getNorthExtension(key: String?): IdeRootPaneNorthExtension? = null override fun getData(@NonNls dataId: String): Any? { return if (CommonDataKeys.PROJECT.`is`(dataId)) project else null } private fun getDataInner(@NonNls dataId: String): Any? { return when { CommonDataKeys.PROJECT.`is`(dataId) -> project else -> getData(dataId) } } fun closeOnEsc() { isCloseOnEsc = true } fun setImage(image: Image?) { setImages(listOfNotNull(image)) } fun setImages(value: List<Image>?) { images = value ?: emptyList() } fun setOnCloseHandler(value: BooleanGetter?) { onCloseHandler = value } protected open fun loadFrameState(state: WindowState?) { val frame = getFrame() if (state == null) { val ideFrame = WindowManagerEx.getInstanceEx().getIdeFrame(project) if (ideFrame != null) { frame.bounds = ideFrame.suggestChildFrameBounds() } } else { state.applyTo(frame) } (frame as RootPaneContainer).rootPane.revalidate() } private class MyJFrame(private var owner: FrameWrapper, private val parent: IdeFrame) : JFrame(), DataProvider, IdeFrame.Child, IdeFrameEx { private var frameTitle: String? = null private var fileTitle: String? = null private var file: Path? = null init { FrameState.setFrameStateListener(this) glassPane = IdeGlassPaneImpl(getRootPane(), true) if (SystemInfoRt.isMac && !(SystemInfo.isMacSystemMenu && java.lang.Boolean.getBoolean("mac.system.menu.singleton"))) { jMenuBar = IdeMenuBar.createMenuBar().setFrame(this) } MouseGestureManager.getInstance().add(this) focusTraversalPolicy = IdeFocusTraversalPolicy() } override fun isInFullScreen() = false override fun toggleFullScreen(state: Boolean): Promise<*> = resolvedPromise<Any>() override fun addNotify() { if (IdeFrameDecorator.isCustomDecorationActive()) { JdkEx.setHasCustomDecoration(this) } super.addNotify() } override fun getComponent(): JComponent = getRootPane() override fun getStatusBar(): StatusBar? { return (if (owner.isDisposing) null else owner.statusBar) ?: parent.statusBar } override fun suggestChildFrameBounds(): Rectangle = parent.suggestChildFrameBounds() override fun getProject() = parent.project override fun setFrameTitle(title: String) { frameTitle = title updateTitle() } override fun setFileTitle(fileTitle: String?, ioFile: Path?) { this.fileTitle = fileTitle file = ioFile updateTitle() } override fun getNorthExtension(key: String): IdeRootPaneNorthExtension? { return owner.getNorthExtension(key) } override fun getBalloonLayout(): BalloonLayout? { return null } private fun updateTitle() { if (AdvancedSettings.getBoolean("ide.show.fileType.icon.in.titleBar")) { // this property requires java.io.File rootPane.putClientProperty("Window.documentFile", file?.toFile()) } val builder = StringBuilder() appendTitlePart(builder, frameTitle) appendTitlePart(builder, fileTitle) title = builder.toString() } override fun dispose() { val owner = owner if (owner.isDisposing) { return } owner.isDisposing = true Disposer.dispose(owner) super.dispose() rootPane = null menuBar = null } override fun getData(dataId: String): Any? { return when { IdeFrame.KEY.`is`(dataId) -> this owner.isDisposing -> null else -> owner.getDataInner(dataId) } } override fun paint(g: Graphics) { setupAntialiasing(g) super.paint(g) } } fun setLocation(location: Point) { getFrame().location = location } fun setSize(size: Dimension?) { getFrame().size = size } private class MyJDialog(private val owner: FrameWrapper, private val parent: IdeFrame) : JDialog(ComponentUtil.getWindow(parent.component)), DataProvider, IdeFrame.Child { override fun getComponent(): JComponent = getRootPane() override fun getStatusBar(): StatusBar? = null override fun getBalloonLayout(): BalloonLayout? = null override fun suggestChildFrameBounds(): Rectangle = parent.suggestChildFrameBounds() override fun getProject(): Project? = parent.project init { glassPane = IdeGlassPaneImpl(getRootPane()) getRootPane().putClientProperty("Window.style", "small") background = UIUtil.getPanelBackground() MouseGestureManager.getInstance().add(this) focusTraversalPolicy = IdeFocusTraversalPolicy() } override fun setFrameTitle(title: String) { setTitle(title) } override fun dispose() { if (owner.isDisposing) { return } owner.isDisposing = true Disposer.dispose(owner) super.dispose() rootPane = null } override fun getData(dataId: String): Any? { return when { IdeFrame.KEY.`is`(dataId) -> this owner.isDisposing -> null else -> owner.getDataInner(dataId) } } override fun paint(g: Graphics) { setupAntialiasing(g) super.paint(g) } } } private fun getWindowStateService(project: Project?): WindowStateService { return if (project == null) WindowStateService.getInstance() else WindowStateService.getInstance(project) }
apache-2.0
dcde76cb276d4eb7926d9f15ca62b708
29.69214
173
0.68457
4.792704
false
false
false
false
google/intellij-community
notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/NotebookCellLinesContext.kt
3
4373
package org.jetbrains.plugins.notebooks.visualization import com.intellij.ide.IdeEventQueue import com.intellij.ide.impl.dataRules.GetDataRule import com.intellij.openapi.actionSystem.* import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ex.EditorGutterComponentEx import com.intellij.openapi.editor.impl.EditorComponentImpl import com.intellij.util.castSafelyTo import com.intellij.util.containers.addIfNotNull import java.awt.Component import java.awt.event.MouseEvent import javax.swing.SwingUtilities /** * A list of editors and offsets inside them. Editors are ordered according to their conformity to the UI event and context, * and offsets represent the places in the editors closest to the place where the event happened. * The event and the context are extracted from the focused component, the mouse cursor position, and the caret position. */ val EDITORS_WITH_OFFSETS_DATA_KEY: DataKey<List<Pair<Editor, Int>>> = DataKey.create("EDITORS_WITH_OFFSETS_DATA_KEY") private class NotebookCellLinesIntervalDataRule : GetDataRule { override fun getData(dataProvider: DataProvider): NotebookCellLines.Interval? = EDITORS_WITH_OFFSETS_DATA_KEY.getData(dataProvider) ?.firstOrNull { (editor, _) -> editor.notebookCellLinesProvider != null } ?.let { (editor, offset) -> NotebookCellLines.get(editor).intervalsIterator(editor.document.getLineNumber(offset)).takeIf { it.hasNext() }?.next() } } private class EditorsWithOffsetsDataRule : GetDataRule { override fun getData(dataProvider: DataProvider): List<Pair<Editor, Int>>? { val contextComponent = PlatformCoreDataKeys.CONTEXT_COMPONENT.getData(dataProvider) val editor = PlatformDataKeys.EDITOR.getData(dataProvider) val result = mutableListOf<Pair<Editor, Int>>() // If the focused component is the editor, it's assumed that the current cell is the cell under the caret. result.addIfNotNull( contextComponent ?.castSafelyTo<EditorComponentImpl>() ?.editor ?.let { contextEditor -> contextEditor to contextEditor.getOffsetFromCaretImpl() }) // Otherwise, some component inside an editor can be focused. In that case it's assumed that the current cell is the cell closest // to the focused component. result.addIfNotNull(getOffsetInEditorByComponentHierarchy(contextComponent)) // When a user clicks on a gutter, it's the only focused component, and it's not connected to the editor. However, vertical offsets // in the gutter can be juxtaposed to the editor. if (contextComponent is EditorGutterComponentEx && editor != null) { val mouseEvent = IdeEventQueue.getInstance().trueCurrentEvent as? MouseEvent if (mouseEvent != null) { val point = SwingUtilities.convertMouseEvent(mouseEvent.component, mouseEvent, contextComponent).point result += editor to editor.logicalPositionToOffset(editor.xyToLogicalPosition(point)) } } // If the focused component is out of the notebook editor, there still can be other editors inside the required one. // If some of such editors is treated as the current editor, the current cell is the cell closest to the current editor. result.addIfNotNull(getOffsetInEditorByComponentHierarchy(editor?.contentComponent)) // When a user clicks on some toolbar on some menu component, it becomes the focused components. Usually, such components have an // assigned editor. In that case it's assumed that the current cell is the cell under the caret. if (editor != null) { result += editor to editor.getOffsetFromCaretImpl() } return result.takeIf(List<*>::isNotEmpty) } private fun Editor.getOffsetFromCaretImpl(): Int = caretModel.offset.coerceAtMost(document.textLength - 1).coerceAtLeast(0) private fun getOffsetInEditorByComponentHierarchy(component: Component?): Pair<Editor, Int>? = generateSequence(component, Component::getParent) .zipWithNext() .mapNotNull { (child, parent) -> if (parent is EditorComponentImpl) child to parent.editor else null } .firstOrNull() ?.let { (child, editor) -> val point = SwingUtilities.convertPoint(child, 0, 0, editor.contentComponent) editor to editor.logicalPositionToOffset(editor.xyToLogicalPosition(point)) } }
apache-2.0
7fcd1a9da136dcecf527399118f001f5
47.065934
135
0.745484
4.758433
false
false
false
false
kickstarter/android-oss
app/src/main/java/com/kickstarter/mock/factories/ConfigFactory.kt
1
2687
package com.kickstarter.mock.factories import com.kickstarter.libs.Config import com.kickstarter.libs.Config.LaunchedCountry object ConfigFactory { @JvmStatic fun config(): Config { val US = LaunchedCountry.builder() .name("US") .currencyCode("USD") .currencySymbol("$") .trailingCode(true) .build() val GB = LaunchedCountry.builder() .name("GB") .currencyCode("GBP") .currencySymbol("£") .trailingCode(false) .build() val CA = LaunchedCountry.builder() .name("CA") .currencyCode("CAD") .currencySymbol("$") .trailingCode(true) .build() val JP = LaunchedCountry.builder() .name("JP") .currencyCode("JPY") .currencySymbol("¥") .trailingCode(false) .build() return Config.builder() .countryCode("US") .features(mutableMapOf()) .launchedCountries(listOf(US, GB, CA, JP)) .build() } fun configForUSUser(): Config { return config() } fun configForCA(): Config { return config().toBuilder() .countryCode("CA") .build() } fun configForITUser(): Config { return config().toBuilder() .countryCode("IT") .build() } fun configWithExperiment(experiment: String, variant: String): Config { return config().toBuilder() .abExperiments( mutableMapOf<String, String>().apply { this[experiment] = variant } ) .build() } fun configWithExperiments(abExperiments: Map<String, String>): Config { return config().toBuilder() .abExperiments(abExperiments) .build() } fun configWithFeatureEnabled(featureKey: String): Config { return config().toBuilder() .features( mutableMapOf<String, Boolean>().apply { this[featureKey] = true } ) .build() } fun configWithFeatureDisabled(featureKey: String): Config { return config().toBuilder() .features( mutableMapOf<String, Boolean>().apply { this[featureKey] = false } ) .build() } fun configWithFeaturesEnabled(features: Map<String, Boolean>): Config { return config().toBuilder() .features(features.toMutableMap()) .build() } }
apache-2.0
7811101400818e5d31b9f4a9a5977cfc
26.680412
75
0.50838
5.104563
false
true
false
false
leafclick/intellij-community
python/src/com/jetbrains/python/console/PythonConsoleClientUtil.kt
1
3805
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("PythonConsoleClientUtil") package com.jetbrains.python.console import com.intellij.util.concurrency.SequentialTaskExecutor import com.jetbrains.python.PyBundle import com.jetbrains.python.console.protocol.PythonConsoleBackendService import java.lang.reflect.InvocationHandler import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method import java.lang.reflect.Proxy import java.util.concurrent.Callable import java.util.concurrent.ExecutionException import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException fun synchronizedPythonConsoleClient(loader: ClassLoader, delegate: PythonConsoleBackendService.Iface, pythonConsoleProcess: Process): PythonConsoleBackendServiceDisposable { val executorService = SequentialTaskExecutor.createSequentialApplicationPoolExecutor(PyBundle.message("console.command.executor")) // make the `PythonConsoleBackendService.Iface` process-aware and thread-safe val proxy = Proxy.newProxyInstance(loader, arrayOf<Class<*>>( PythonConsoleBackendService.Iface::class.java), InvocationHandler { _, method, args -> // we evaluate the original method in the other thread in order to control it val future = executorService.submit(Callable { return@Callable invokeOriginalMethod(args, method, delegate) }) while (true) { try { return@InvocationHandler future.get(10L, TimeUnit.MILLISECONDS) } catch (e: TimeoutException) { if (!pythonConsoleProcess.isAlive) { val exitValue = pythonConsoleProcess.exitValue() throw PyConsoleProcessFinishedException(exitValue) } // continue waiting for the end of the operation execution } catch (e: ExecutionException) { if (!pythonConsoleProcess.isAlive) { val exitValue = pythonConsoleProcess.exitValue() throw PyConsoleProcessFinishedException(exitValue) } throw e.cause ?: e } } }) as PythonConsoleBackendService.Iface // make the `proxy` disposable return object : PythonConsoleBackendServiceDisposable, PythonConsoleBackendService.Iface by proxy { override fun dispose() { executorService.shutdownNow() try { while (!executorService.awaitTermination(1L, TimeUnit.SECONDS)) Unit } catch (e: InterruptedException) { Thread.currentThread().interrupt() } } } } private fun invokeOriginalMethod(args: Array<out Any>?, method: Method, delegate: Any): Any? { return try { if (args != null) { method.invoke(delegate, *args) } else { method.invoke(delegate) } } catch (e: InvocationTargetException) { throw e.cause ?: e } }
apache-2.0
962e7cfc31cf9aa83bd3422b917b36dd
48.428571
140
0.551643
6.493174
false
false
false
false
siosio/intellij-community
plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/handlers/KotlinCallableInsertHandler.kt
1
3271
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.completion.handlers import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.LookupElement import com.intellij.psi.PsiDocumentManager import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.idea.completion.isArtificialImportAliasedDescriptor import org.jetbrains.kotlin.idea.completion.shortenReferences import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject import org.jetbrains.kotlin.idea.core.withRootPrefixIfNeeded import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.util.CallType import org.jetbrains.kotlin.idea.util.ImportInsertHelper import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.renderer.render import org.jetbrains.kotlin.resolve.DescriptorUtils abstract class KotlinCallableInsertHandler(val callType: CallType<*>) : BaseDeclarationInsertHandler() { companion object { val SHORTEN_REFERENCES = ShortenReferences { ShortenReferences.Options.DEFAULT.copy(dropBracesInStringTemplates = false) } } override fun handleInsert(context: InsertionContext, item: LookupElement) { super.handleInsert(context, item) addImport(context, item) } private fun addImport(context: InsertionContext, item: LookupElement) { val psiDocumentManager = PsiDocumentManager.getInstance(context.project) psiDocumentManager.commitAllDocuments() val file = context.file val o = item.`object` if (file is KtFile && o is DeclarationLookupObject) { val descriptor = o.descriptor as? CallableDescriptor ?: return if (descriptor.extensionReceiverParameter != null || callType == CallType.CALLABLE_REFERENCE) { if (DescriptorUtils.isTopLevelDeclaration(descriptor) && !descriptor.isArtificialImportAliasedDescriptor) { ImportInsertHelper.getInstance(context.project).importDescriptor(file, descriptor) } } else if (callType == CallType.DEFAULT) { if (descriptor.isArtificialImportAliasedDescriptor) return val fqName = descriptor.importableFqName ?: return context.document.replaceString( context.startOffset, context.tailOffset, fqName.withRootPrefixIfNeeded().render() + " " ) // insert space after for correct parsing psiDocumentManager.commitAllDocuments() shortenReferences(context, context.startOffset, context.tailOffset - 1, SHORTEN_REFERENCES) psiDocumentManager.doPostponedOperationsAndUnblockDocument(context.document) // delete space if (context.document.isTextAt(context.tailOffset - 1, " ")) { // sometimes space can be lost because of reformatting context.document.deleteString(context.tailOffset - 1, context.tailOffset) } } } } }
apache-2.0
b95f7b99c4266f3045d18422d3e2f975
47.820896
158
0.719352
5.28433
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/tests/testData/script/definition/loading/async/template/template.kt
4
1458
package custom.scriptDefinition import kotlin.script.dependencies.* import kotlin.script.experimental.dependencies.* import kotlin.script.templates.* import java.io.File import kotlin.script.experimental.location.* class TestDependenciesResolver : AsyncDependenciesResolver { suspend override fun resolveAsync(scriptContents: ScriptContents, environment: Environment): DependenciesResolver.ResolveResult { val text = scriptContents.text as String val result = when { text.startsWith("#BAD:") -> DependenciesResolver.ResolveResult.Failure( reports = listOf(ScriptReport(text)) ) else -> DependenciesResolver.ResolveResult.Success( dependencies = ScriptDependencies( classpath = listOf(environment["template-classes"] as File), imports = listOf("x_" + text.replace(Regex("#IGNORE_IN_CONFIGURATION"), "")) ), reports = listOf(ScriptReport(text)) ) } javaClass.classLoader .loadClass("org.jetbrains.kotlin.idea.script.ScriptConfigurationLoadingTest") .methods.single { it.name == "loadingScriptConfigurationCallback" } .invoke(null) return result } } @ScriptExpectedLocations([ScriptExpectedLocation.Everywhere]) @ScriptTemplateDefinition(TestDependenciesResolver::class, scriptFilePattern = "script.kts") class Template
apache-2.0
f533708d28b1d750b72c3e839dd6243b
38.432432
133
0.679698
5.543726
false
true
false
false
siosio/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/extensibility/BuildSystemType.kt
1
582
package com.jetbrains.packagesearch.intellij.plugin.extensibility class BuildSystemType(val name: String, val language: String, val statisticsKey: String) { companion object { @JvmStatic val MAVEN = BuildSystemType(name = "MAVEN", language = "xml", statisticsKey = "maven") @JvmStatic val GRADLE_GROOVY = BuildSystemType(name = "GRADLE", language= "groovy", statisticsKey = "gradle-groovy") @JvmStatic val GRADLE_KOTLIN = BuildSystemType(name = "GRADLE", language= "kotlin", statisticsKey = "gradle-kts") } } class Build
apache-2.0
b7ec74c8ed701f96c2633a12595747b3
33.235294
113
0.685567
4.476923
false
false
false
false
siosio/intellij-community
plugins/grazie/src/main/kotlin/com/intellij/grazie/grammar/LanguageToolRule.kt
1
1875
package com.intellij.grazie.grammar import com.intellij.grazie.GrazieBundle import com.intellij.grazie.jlanguage.Lang import com.intellij.grazie.jlanguage.LangTool import com.intellij.grazie.text.Rule import com.intellij.grazie.utils.* import kotlinx.html.style import kotlinx.html.table import kotlinx.html.td import kotlinx.html.tr import org.apache.commons.text.similarity.LevenshteinDistance import org.languagetool.rules.IncorrectExample import java.net.URL internal class LanguageToolRule( private val lang: Lang, private val ltRule: org.languagetool.rules.Rule ) : Rule(LangTool.globalIdPrefix(lang) + ltRule.id, ltRule.description, ltRule.category.name) { override fun isEnabledByDefault(): Boolean = LangTool.isRuleEnabledByDefault(lang, ltRule.id) override fun getUrl(): URL? = ltRule.url override fun getDescription(): String = html { table { cellpading = "0" cellspacing = "0" style = "width:100%;" ltRule.incorrectExamples.forEach { example -> tr { td { valign = "top" style = "padding-bottom: 5px; padding-right: 5px; color: gray;" +GrazieBundle.message("grazie.settings.grammar.rule.incorrect") } td { style = "padding-bottom: 5px; width: 100%;" toIncorrectHtml(example) } } if (example.corrections.any { it.isNotBlank() }) { tr { td { valign = "top" style = "padding-bottom: 10px; padding-right: 5px; color: gray;" +GrazieBundle.message("grazie.settings.grammar.rule.correct") } td { style = "padding-bottom: 10px; width: 100%;" toCorrectHtml(example) } } } } } +GrazieBundle.message("grazie.tooltip.powered-by-language-tool") } }
apache-2.0
2827ef32346a35cc6d832b8b4633a1f6
30.266667
95
0.634667
4.093886
false
false
false
false
GunoH/intellij-community
platform/execution/src/com/intellij/execution/target/TargetedCommandLineBuilder.kt
1
3614
// 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.execution.target import com.intellij.execution.target.value.TargetValue import com.intellij.openapi.util.UserDataHolderBase import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.util.containers.ContainerUtil import java.io.File import java.nio.charset.Charset class TargetedCommandLineBuilder(val request: TargetEnvironmentRequest) : UserDataHolderBase() { var exePath: TargetValue<String> = TargetValue.empty() private var workingDirectory = TargetValue.empty<String>() private var inputFilePath = TargetValue.empty<String>() var charset: Charset = CharsetToolkit.getDefaultSystemCharset() private val parameters: MutableList<TargetValue<String>> = ArrayList() private val environment: MutableMap<String, TargetValue<String>> = HashMap() private val _filesToDeleteOnTermination: MutableSet<File> = HashSet() var redirectErrorStream: Boolean = false var ptyOptions: PtyOptions? = null fun build(): TargetedCommandLine { return TargetedCommandLine(exePath, workingDirectory, inputFilePath, charset, parameters.toList(), environment.toMap(), redirectErrorStream, ptyOptions) } fun setExePath(exePath: String) { this.exePath = TargetValue.fixed(exePath) } fun setWorkingDirectory(workingDirectory: TargetValue<String>) { this.workingDirectory = workingDirectory } fun setWorkingDirectory(workingDirectory: String) { this.workingDirectory = TargetValue.fixed(workingDirectory) } fun addParameter(parameter: TargetValue<String>) { parameters.add(parameter) } fun addParameter(parameter: String) { parameters.add(TargetValue.fixed(parameter)) } fun addParameters(parametersList: List<String>) { for (parameter in parametersList) { addParameter(parameter) } } fun addParameters(vararg parametersList: String) { for (parameter in parametersList) { addParameter(parameter) } } fun addParameterAt(index: Int, parameter: String) { addParameterAt(index, TargetValue.fixed(parameter)) } private fun addParameterAt(index: Int, parameter: TargetValue<String>) { parameters.add(index, parameter) } fun addFixedParametersAt(index: Int, parameters: List<String>) { addParametersAt(index, ContainerUtil.map(parameters) { p: String -> TargetValue.fixed(p) }) } fun addParametersAt(index: Int, parameters: List<TargetValue<String>>) { this.parameters.addAll(index, parameters) } fun addEnvironmentVariable(name: String, value: TargetValue<String>?) { if (value != null) { environment[name] = value } else { environment.remove(name) } } fun addEnvironmentVariable(name: String, value: String?) { addEnvironmentVariable(name, if (value != null) TargetValue.fixed(value) else null) } fun removeEnvironmentVariable(name: String) { environment.remove(name) } fun getEnvironmentVariable(name: String): TargetValue<String>? { return environment[name] } fun addFileToDeleteOnTermination(file: File) { _filesToDeleteOnTermination.add(file) } fun setInputFile(inputFilePath: TargetValue<String>) { this.inputFilePath = inputFilePath } val filesToDeleteOnTermination: Set<File> get() = _filesToDeleteOnTermination fun setRedirectErrorStreamFromRegistry() { redirectErrorStream = Registry.`is`("run.processes.with.redirectedErrorStream", false) } }
apache-2.0
d7032f4fb569dff1fd61bb5d9a131c4b
31.567568
140
0.744051
4.592122
false
false
false
false
GunoH/intellij-community
plugins/evaluation-plugin/core/src/com/intellij/cce/metric/MeanRankMetric.kt
8
866
package com.intellij.cce.metric import com.intellij.cce.core.Session import com.intellij.cce.metric.util.Sample class MeanRankMetric : Metric { private val sample = Sample() override val value: Double get() = sample.mean() override fun evaluate(sessions: List<Session>, comparator: SuggestionsComparator): Double { val completions = sessions.map { session -> Pair(session.lookups.last().suggestions, session.expectedText) } val fileSample = Sample() completions.forEach { (suggests, expectedText) -> val position = suggests.indexOfFirst { comparator.accept(it, expectedText) } if (position != -1) { fileSample.add(position.toDouble()) sample.add(position.toDouble()) } } return fileSample.mean() } override val name: String = "Mean Rank" override val valueType = MetricValueType.DOUBLE }
apache-2.0
2e667bb05212294bf5eb7c4dfbe9aceb
26.967742
112
0.702079
4.22439
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RemoveToStringInStringTemplateInspection.kt
1
2392
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInsight.FileModificationService import com.intellij.codeInspection.* import com.intellij.openapi.project.Project import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.intentions.isToString import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.canPlaceAfterSimpleNameEntry class RemoveToStringInStringTemplateInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) = dotQualifiedExpressionVisitor(fun(expression) { if (expression.parent !is KtBlockStringTemplateEntry) return if (expression.receiverExpression is KtSuperExpression) return val selectorExpression = expression.selectorExpression ?: return if (!expression.isToString()) return holder.registerProblem( selectorExpression, KotlinBundle.message("redundant.tostring.call.in.string.template"), ProblemHighlightType.LIKE_UNUSED_SYMBOL, RemoveToStringFix() ) }) } class RemoveToStringFix : LocalQuickFix { override fun getName() = KotlinBundle.message("remove.to.string.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val element = descriptor.psiElement.parent as? KtDotQualifiedExpression ?: return if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return val receiverExpression = element.receiverExpression if (receiverExpression is KtNameReferenceExpression) { val templateEntry = receiverExpression.parent.parent if (templateEntry is KtBlockStringTemplateEntry && canPlaceAfterSimpleNameEntry(templateEntry.nextSibling)) { val factory = KtPsiFactory(templateEntry) templateEntry.replace(factory.createSimpleNameStringTemplateEntry(receiverExpression.getReferencedName())) return } } element.replace(receiverExpression) } }
apache-2.0
33f135b6cc171ada55cd45bc7f66d88f
46.84
158
0.733696
5.891626
false
false
false
false
siosio/intellij-community
plugins/git4idea/src/git4idea/update/GitUpdateSession.kt
1
4581
// 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 git4idea.update import com.intellij.dvcs.DvcsUtil.getShortNames import com.intellij.dvcs.DvcsUtil.getShortRepositoryName import com.intellij.notification.Notification import com.intellij.notification.NotificationAction import com.intellij.notification.NotificationType import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.vcs.VcsException import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vcs.update.UpdateSession import com.intellij.util.containers.MultiMap import git4idea.i18n.GitBundle import git4idea.repo.GitRepository import java.util.function.Supplier /** * Ranges are null if update didn't start yet, in which case there are no new commits to display, * and the error notification is shown from the GitUpdateProcess itself. */ class GitUpdateSession(private val project: Project, private val notificationData: GitUpdateInfoAsLog.NotificationData?, private val result: Boolean, private val skippedRoots: Map<GitRepository, String>) : UpdateSession { override fun getExceptions(): List<VcsException> { return emptyList() } override fun onRefreshFilesCompleted() {} override fun isCanceled(): Boolean { return !result } override fun getAdditionalNotificationContent(): String? { if (skippedRoots.isEmpty()) return null if (skippedRoots.size == 1) { val repo = skippedRoots.keys.first() return GitBundle.message("git.update.repo.was.skipped", getShortRepositoryName(repo), skippedRoots[repo]) } val prefix = GitBundle.message("git.update.skipped.repositories", skippedRoots.size) + " <br/>" // NON-NLS val grouped = groupByReasons(skippedRoots) if (grouped.keySet().size == 1) { val reason = grouped.keySet().first() return prefix + getShortNames(grouped.get(reason)) + " (" + reason + ")" } return prefix + grouped.keySet().joinToString("<br/>") { reason -> getShortNames(grouped.get(reason)) + " (" + reason + ")" } // NON-NLS } private fun groupByReasons(skippedRoots: Map<GitRepository, String>): MultiMap<String, GitRepository> { val result = MultiMap.create<String, GitRepository>() skippedRoots.forEach { (file, s) -> result.putValue(s, file) } return result } override fun showNotification() { if (notificationData != null) { val notification = prepareNotification(notificationData.updatedFilesCount, notificationData.receivedCommitsCount, notificationData.filteredCommitsCount) notification.addAction(NotificationAction.createSimple(Supplier { GitBundle.message("action.NotificationAction.GitUpdateSession.text.view.commits") }, notificationData.viewCommitAction)) VcsNotifier.getInstance(project).notify(notification) } } private fun prepareNotification(updatedFilesNumber: Int, updatedCommitsNumber: Int, filteredCommitsNumber: Int?): Notification { val title: String var content: String? val type: NotificationType val mainMessage = getTitleForUpdateNotification(updatedFilesNumber, updatedCommitsNumber) if (isCanceled) { title = GitBundle.message("git.update.project.partially.updated.title") content = mainMessage type = NotificationType.WARNING } else { title = mainMessage content = getBodyForUpdateNotification(filteredCommitsNumber) type = NotificationType.INFORMATION } val additionalContent = additionalNotificationContent if (additionalContent != null) { if (content.isNotEmpty()) { content += "<br/>" // NON-NLS } content += additionalContent } return VcsNotifier.STANDARD_NOTIFICATION.createNotification(title, content, type) } } @NlsContexts.NotificationTitle fun getTitleForUpdateNotification(updatedFilesNumber: Int, updatedCommitsNumber: Int): String = GitBundle.message("git.update.files.updated.in.commits", updatedFilesNumber, updatedCommitsNumber) @NlsContexts.NotificationContent fun getBodyForUpdateNotification(filteredCommitsNumber: Int?): String { return when (filteredCommitsNumber) { null -> "" 0 -> GitBundle.message("git.update.no.commits.matching.filters") else -> GitBundle.message("git.update.commits.matching.filters", filteredCommitsNumber) } }
apache-2.0
c2f722a74c7059b5f232ebeda8b17b72
40.27027
156
0.725387
4.837381
false
false
false
false
zsmb13/MaterialDrawerKt
library/src/main/java/co/zsmb/materialdrawerkt/builders/DrawerBuilderKt.kt
1
48496
@file:Suppress("RedundantVisibilityModifier") package co.zsmb.materialdrawerkt.builders import android.app.Activity import android.content.SharedPreferences import android.graphics.drawable.Drawable import android.os.Bundle import android.view.View import android.view.ViewGroup import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import androidx.recyclerview.widget.RecyclerView import co.zsmb.materialdrawerkt.DrawerMarker import co.zsmb.materialdrawerkt.nonReadable import com.mikepenz.fastadapter.FastAdapter import com.mikepenz.materialdrawer.AccountHeader import com.mikepenz.materialdrawer.Drawer import com.mikepenz.materialdrawer.DrawerBuilder import com.mikepenz.materialdrawer.holder.DimenHolder import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem /** * Adds a navigation drawer to this Activity. * * @return The created Drawer instance */ public fun Activity.drawer(setup: DrawerBuilderKt.() -> Unit = {}): Drawer { val builder = DrawerBuilderKt(this) builder.setup() return builder.build() } /** * Adds a navigation drawer to this Fragment. * * @return The created Drawer instance */ public fun Fragment.drawer(setup: DrawerBuilderKt.() -> Unit = {}): Drawer { val fragmentActivity = activity ?: throw IllegalStateException("Fragment is not attached to an Activity") val builder = DrawerBuilderKt(fragmentActivity) builder.setup() return builder.buildForFragment() } @DrawerMarker public class DrawerBuilderKt(val activity: Activity) : Builder { //region Builder basics public val builder = DrawerBuilder(activity) internal fun build(): Drawer { if (onDrawerListener.isInitialized) { builder.withOnDrawerListener(onDrawerListener) } if (buildViewOnly) { return builder.buildView() } root?.let { val drawerResult = builder.buildView() it.addView(drawerResult.slider) return drawerResult } primaryDrawer?.let { return builder.append(it) } return builder.build() } internal fun buildForFragment(): Drawer { if (onDrawerListener.isInitialized) { builder.withOnDrawerListener(onDrawerListener) } return builder.buildForFragment() } /** * A shadowing method to prevent nesting [drawer][co.zsmb.materialdrawerkt.builders.drawer] calls. * ( Credits to hotkey for this solution http://stackoverflow.com/a/43470027/4465208 ) */ @Suppress("UNUSED_PARAMETER") @Deprecated(level = DeprecationLevel.ERROR, message = "Drawers can't be nested.") public fun drawer(param: () -> Unit = {}) { } @Suppress("OverridingDeprecatedMember") public override fun attachItem(item: IDrawerItem<*>) { builder.addDrawerItems(item) } internal fun attachHeader(header: AccountHeader) { builder.withAccountHeader(header) } //endregion //region Build helper private var root: ViewGroup? = null /** * Setting this to true will not attach the drawer to the Activity. Instead, you can call [Drawer.getSlider] to get * the root view of the created drawer, and add it to a ViewGroup yourself. * Default value is false. * * Wraps the [DrawerBuilder.buildView] method. */ public var buildViewOnly: Boolean = false /** * The ViewGroup which the DrawerLayout will be added to. * * This is equivalent to setting the [buildViewOnly] property, or, with the original library, using * [DrawerBuilder.buildView]. The difference is that you don't have to manually add the drawer to the ViewGroup. * * Non-readable property. */ public var parentView: ViewGroup @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { root = value } /** * The ViewGroup which the DrawerLayout will be added to, given by its layout ID. * * This is equivalent to setting the [buildViewOnly] property, or, with the original library, using * [DrawerBuilder.buildView]. The difference is that you don't have to manually add the drawer to the ViewGroup. * * Non-readable property. */ public var parentViewRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { root = activity.findViewById<ViewGroup>(value) } //endregion //region Listener helper private val onDrawerListener = object : Drawer.OnDrawerListener { internal var isInitialized = false internal var onSlide: ((View, Float) -> Unit)? = null set(value) { isInitialized = true field = value } override fun onDrawerSlide(drawerView: View, slideOffset: Float) { onSlide?.invoke(drawerView, slideOffset) } internal var onClosed: ((View) -> Unit)? = null set(value) { isInitialized = true field = value } override fun onDrawerClosed(drawerView: View) { onClosed?.invoke(drawerView) } internal var onOpened: ((View) -> Unit)? = null set(value) { isInitialized = true field = value } override fun onDrawerOpened(drawerView: View) { onOpened?.invoke(drawerView) } } //endregion //region DrawerBuilder methods /** * A custom ActionBarDrawerToggle to be used in with this drawer. * * Non-readable property. Wraps the [DrawerBuilder.withActionBarDrawerToggle] method. */ public var actionBarDrawerToggle: ActionBarDrawerToggle @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withActionBarDrawerToggle(value) } /** * Whether the toolbar toggle should be animated when the drawer opens/closes. * Default value is false. * * Non-readable property. Wraps the [DrawerBuilder.withActionBarDrawerToggleAnimated] method. */ public var actionBarDrawerToggleAnimated: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withActionBarDrawerToggleAnimated(value) } /** * Whether the toolbar should have a toggle on it. Note that this requires the toolbar property to be set. * Default value is true. * * Non-readable property. Wraps the [DrawerBuilder.withActionBarDrawerToggle] method. */ public var actionBarDrawerToggleEnabled: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(enabled) { builder.withActionBarDrawerToggle(enabled) } /** * A custom adapter for the drawer items. Not recommended. * * Non-readable property. Wraps the [DrawerBuilder.withAdapter] method. */ public var adapter: FastAdapter<IDrawerItem<out RecyclerView.ViewHolder>> @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withAdapter(value) } /** * An adapter which wraps the main adapter used in the RecyclerView to allow extended navigation. Can only be used * if the normal adapter property is set. Not recommended. * * Non-readable property. Wraps the [DrawerBuilder.withAdapterWrapper] method. */ public var adapterWrapper: RecyclerView.Adapter<out RecyclerView.ViewHolder> @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withAdapterWrapper(value) } /** * Whether the drawer should close if an item is clicked. * Default value is true. * * Non-readable property. Wraps the [DrawerBuilder.withCloseOnClick] method. */ public var closeOnClick: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withCloseOnClick(value) } /** * Override for the entire drawer view. * * Non-readable property. Wraps the [DrawerBuilder.withCustomView] method. */ public var customView: View @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withCustomView(value) } /** * Override for the entire drawer view, as a layout resource. * * Non-readable property. Wraps the [DrawerBuilder.withCustomView] method. */ public var customViewRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { val view = activity.layoutInflater.inflate(value, null) builder.withCustomView(view) } /** * The delay (in milliseconds) for the drawer click event after a click. * * This can be used to improve performance and prevent lag, especially when you switch fragments inside the * listener. This will ignore the Boolean value you can return in the listener, as the listener is called after the * drawer was closed. * Default value is -1, which disables this setting entirely. * * Non-readable property. Wraps the [DrawerBuilder.withDelayDrawerClickEvent] method. */ public var delayDrawerClickEvent: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withDelayDrawerClickEvent(value) } /** * The delay (in milliseconds) for the drawer close operation after a click. * * This is a small trick to improve performance and prevent lag if you open a new Activity after a drawer item was * selected. Set to -1 to disable this behavior entirely. * Default value is 50. * * Non-readable property. Wraps the [DrawerBuilder.withDelayOnDrawerClose] method. */ public var delayOnDrawerClose: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withDelayOnDrawerClose(value) } /** * Whether the drawer should be displayed below the status bar. * Default value is true. * * Non-readable property. Wraps the [DrawerBuilder.withDisplayBelowStatusBar] method. */ public var displayBelowStatusBar: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withDisplayBelowStatusBar(value) } /** * Sets the position of the drawer. Valid values are Gravity.START/LEFT and Gravity.END/RIGHT. * Default value is Gravity.START. * * See [gravity] as an alternative. * * Non-readable property. Wraps the [DrawerBuilder.withDrawerGravity] method. */ @Deprecated(level = DeprecationLevel.WARNING, message = "Alternatives are available, check the documentation.") public var drawerGravity: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withDrawerGravity(value) } /** * Override of the entire drawer's layout with a DrawerLayout. * * Non-readable property. Wraps the [DrawerBuilder.withDrawerLayout] method. */ public var drawerLayout: androidx.drawerlayout.widget.DrawerLayout @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withDrawerLayout(value) } /** * Override the entire drawer's layout with a DrawerLayout from a layout resource file. * * Non-readable property. Wraps the [DrawerBuilder.withDrawerLayout] method. */ public var drawerLayoutRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withDrawerLayout(value) } /** * The width of the drawer in dps. * * See [widthDp] as an alternative. * * Non-readable property. Wraps the [DrawerBuilder.withDrawerWidthDp] method. */ @Deprecated(level = DeprecationLevel.WARNING, message = "Alternatives are available, check the documentation.") public var drawerWidthDp: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withDrawerWidthDp(value) } /** * The width of the drawer in pixels. * * See [widthPx] as an alternative. * * Non-readable property. Wraps the [DrawerBuilder.withDrawerWidthPx] method. */ @Deprecated(level = DeprecationLevel.WARNING, message = "Alternatives are available, check the documentation.") public var drawerWidthPx: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withDrawerWidthPx(value) } /** * The width of the drawer as a dimension resource. * * See [widthRes] as an alternative. * * Non-readable property. Wraps the [DrawerBuilder.withDrawerWidthRes] method. */ @Deprecated(level = DeprecationLevel.WARNING, message = "Alternatives are available, check the documentation.") public var drawerWidthRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withDrawerWidthRes(value) } /** * If set to true, you'll receive a click event on the item that's selected by default when the drawer is created. * Default value is false. * * Non-readable property. Wraps the [DrawerBuilder.withFireOnInitialOnClick] method. */ public var fireOnInitialOnClick: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withFireOnInitialOnClick(value) } /** * Whether the footer of the drawer is clickable. * Default value is false. * * Non-readable property. Wraps the [DrawerBuilder.withFooterClickable] method. */ @Deprecated(level = DeprecationLevel.WARNING, message = "This has no effect as of Material Drawer version 5.9.0") public var footerClickable: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withFooterClickable(value) } /** * Whether there should be a divider above the footer. * Default value is true. * * Non-readable property. Wraps the [DrawerBuilder.withFooterDivider] method. */ public var footerDivider: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withFooterDivider(value) } /** * An arbitrary View to use as the scrolling footer of the drawer item list. * * Non-readable property. Wraps the [DrawerBuilder.withFooter] method. */ public var footerView: View @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withFooter(value) } /** * An arbitrary layout resource to use as the scrolling footer of the drawer item list. * * Non-readable property. Wraps the [DrawerBuilder.withFooter] method. */ public var footerViewRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withFooter(value) } /** * Set to true if the used theme has a translucent statusBar and navigationBar and you want to manage the padding * on your own. (Documentation inherited from original library. Not sure if it makes any difference.) * Default value is false. * * Non-readable property. Wraps the [DrawerBuilder.withFullscreen] method. */ public var fullscreen: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withFullscreen(value) } /** * Whether to generate a mini drawer for this drawer as well. * Default value is false. * * Non-readable property. Wraps the [DrawerBuilder.withGenerateMiniDrawer] method. */ public var generateMiniDrawer: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withGenerateMiniDrawer(value) } /** * Sets the position of the drawer. Valid values are Gravity.START/LEFT and Gravity.END/RIGHT. * Default value is Gravity.START. * * Convenience for [drawerGravity]. Non-readable property. Wraps the [DrawerBuilder.withDrawerGravity] * method. */ public var gravity: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withDrawerGravity(value) } /** * Whether the generated adapter should have its `hasStableIds` set to true. Only enable if you have set unique * identifiers for all of your items. * Default value is false. * * Non-readable property. Wraps the [DrawerBuilder.withHasStableIds] method. */ public var hasStableIds: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withHasStableIds(value) } /** * Whether there should be a divider below the header. * Default value is true. * * Non-readable property. Wraps the [DrawerBuilder.withHeaderDivider] method. */ public var headerDivider: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withHeaderDivider(value) } /** * The height of the header provided with the [headerView] or [headerViewRes] properties, as a DimenHolder. * * See [headerHeightDp], [headerHeightPx], and [headerHeightRes] as alternatives. * * Non-readable property. Wraps the [DrawerBuilder.withHeaderHeight] method. */ @Deprecated(level = DeprecationLevel.WARNING, message = "Use px, dp, or a dimension resource instead.") public var headerHeight: DimenHolder @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withHeaderHeight(value) } /** * The height of the header provided with the [headerView] or [headerViewRes] properties, in dps. * * Convenience for [headerHeight]. Non-readable property. Wraps the [DrawerBuilder.withHeaderHeight] method. */ public var headerHeightDp: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withHeaderHeight(DimenHolder.fromDp(value)) } /** * The height of the header provided with the [headerView] or [headerViewRes] properties, in pixels. * * Convenience for [headerHeight]. Non-readable property. Wraps the [DrawerBuilder.withHeaderHeight] method. */ public var headerHeightPx: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withHeaderHeight(DimenHolder.fromPixel(value)) } /** * The height of the header provided with the [headerView] or [headerViewRes] properties, as a dimension resource. * * Convenience for [headerHeight]. Non-readable property. Wraps the [DrawerBuilder.withHeaderHeight] method. */ public var headerHeightRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withHeaderHeight(DimenHolder.fromResource(value)) } /** * Whether there should be padding below the header of the drawer. * Default value is true. * * Non-readable property. Wraps the [DrawerBuilder.withHeaderPadding] method. */ public var headerPadding: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withHeaderPadding(value) } /** * An arbitrary View to use as the header of the drawer. * * Non-readable property. Wraps the [DrawerBuilder.withHeader] method. */ public var headerView: View @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withHeader(value) } /** * An arbitrary View to use as the header of the drawer, as a layout resource. * * Non-readable property. Wraps the [DrawerBuilder.withHeader] method. */ public var headerViewRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withHeader(value) } /** * Whether the drawer should have an inner shadow on its edge. Recommended to be used with mini drawer. * Default value is false. * * Non-readable property. Wraps the [DrawerBuilder.withInnerShadow] method. */ public var innerShadow: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withInnerShadow(value) } /** * The ItemAnimator of the internal RecyclerView. * * Non-readable property. Wraps the [DrawerBuilder.withItemAnimator] method. */ public var itemAnimator: RecyclerView.ItemAnimator @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withItemAnimator(value) } /** * Toggles if the sticky footer should stay visible upon switching to the profile list. Note that using this with * stickyDrawerItems can lead to the selection not being updated correctly. Use with care. * Default value is false. * * Non-readable property. Wraps the [DrawerBuilder.withKeepStickyItemsVisible] method. */ public var keepStickyItemsVisible: Boolean get() = nonReadable() set(value) { builder.withKeepStickyItemsVisible(value) } /** * The menu resource to inflate items from. These are added to the drawer. * * Non-readable property. Wraps the [DrawerBuilder.inflateMenu] method. */ public var menuItemsRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.inflateMenu(value) } /** * Enables multiple selections amongst drawer items. * Default value is false. * * Non-readable property. Wraps the [DrawerBuilder.withMultiSelect] method. */ public var multiSelect: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withMultiSelect(value) } /** * Adds an event [handler] to the drawer that's called when the drawer is closed. * * Wraps the [DrawerBuilder.withOnDrawerListener] method. * * @param drawerView The root View of the drawer */ public fun onClosed(handler: (drawerView: View) -> Unit) { onDrawerListener.onClosed = handler } /** * Adds an event [handler] to the drawer that's called when an item is clicked. The handler should return true if * the event has been completely handled. * * Convenience for the three parameter [onItemClick] method, to be used when you don't need all its parameters. * Wraps the [DrawerBuilder.withOnDrawerItemClickListener] method. * * @param position The position of the clicked item within the drawer */ public fun onItemClick(handler: (position: Int) -> Boolean) { builder.withOnDrawerItemClickListener(object : Drawer.OnDrawerItemClickListener { override fun onItemClick(view: View?, position: Int, drawerItem: IDrawerItem<*>): Boolean { return handler(position) } }) } /** * Adds an event [handler] to the drawer that's called when an item is clicked. The handler should return true if * the event has been completely handled. * * See the one parameter [onItemClick] as an alternative. * * Wraps the [DrawerBuilder.withOnDrawerItemClickListener] method. * * @param view The View that was clicked * @param position The position of the clicked item within the drawer * @param drawerItem The clicked drawer item */ public fun onItemClick(handler: (view: View?, position: Int, drawerItem: IDrawerItem<*>) -> Boolean) { builder.withOnDrawerItemClickListener(object : Drawer.OnDrawerItemClickListener { override fun onItemClick(view: View?, position: Int, drawerItem: IDrawerItem<*>): Boolean { return handler(view, position, drawerItem) } }) } /** * Adds an event [handler] to the drawer that's called when an item is long clicked. The handler should return true * if the event has been completely handled. * * Convenience for the three parameter [onItemLongClick] method, to be used when you don't need all its parameters. * Wraps the [DrawerBuilder.withOnDrawerItemLongClickListener] method. * * @param position The position of the clicked item within the drawer */ public fun onItemLongClick(handler: (position: Int) -> Boolean) { builder.withOnDrawerItemLongClickListener(object : Drawer.OnDrawerItemLongClickListener { override fun onItemLongClick(view: View, position: Int, drawerItem: IDrawerItem<*>): Boolean { return handler(position) } }) } /** * Adds an event [handler] to the drawer that's called when an item is long clicked. The handler should return true * if the event has been completely handled. * * See the one parameter [onItemLongClick] as an alternative. * * Wraps the [DrawerBuilder.withOnDrawerItemLongClickListener] method. * * @param view The View that was clicked * @param position The position of the clicked item within the drawer * @param drawerItem The clicked drawer item */ public fun onItemLongClick(handler: (view: View, position: Int, drawerItem: IDrawerItem<*>) -> Boolean) { builder.withOnDrawerItemLongClickListener(object : Drawer.OnDrawerItemLongClickListener { override fun onItemLongClick(view: View, position: Int, drawerItem: IDrawerItem<*>): Boolean { return handler(view, position, drawerItem) } }) } /** * Defines a navigation listener for the drawer. * * Wraps the [DrawerBuilder.withOnDrawerNavigationListener] method. * * @param handler the handler to call on navigation. Should return true if the event has been handled. */ public fun onNavigation(handler: (clickedView: View) -> Boolean) { builder.withOnDrawerNavigationListener(object : Drawer.OnDrawerNavigationListener { override fun onNavigationClickListener(clickedView: View): Boolean { return handler(clickedView) } }) } /** * Adds an event [handler] to the drawer that's called when the drawer is opened. * * Wraps the [DrawerBuilder.withOnDrawerListener] method. * * @param drawerView The root View of the drawer */ public fun onOpened(handler: (drawerView: View) -> Unit) { onDrawerListener.onOpened = handler } /** * Adds an event [handler] to the drawer that's called when the drawer is sliding. * * Wraps the [DrawerBuilder.withOnDrawerListener] method. * * @param drawerView The root View of the drawer * @param slideOffset The amount to which the drawer is open, as a number between 0 (closed) and 1 (open) */ public fun onSlide(handler: (drawerView: View, slideOffset: Float) -> Unit) { onDrawerListener.onSlide = handler } /** * Whether to use position based state management in the internal adapter. This allows high performance for very * long lists. If set to false, the new identifier based state management will be used, which provides more * flexibility, but has worse performance with long lists. * Default value is true. * * Non-readable property. Wraps the [DrawerBuilder.withPositionBasedStateManagement] method. */ @Deprecated(level = DeprecationLevel.ERROR, message = "FastAdapter no longer has this setting in its new versions. Please remove this call.") public var positionBasedStateManagement: Boolean get() = nonReadable() set(value) = Unit /** * The primary drawer that's already present in the Activity. This is to be set when the current drawer is the * second drawer in an Activity. * * Non-readable property. Wraps the [DrawerBuilder.append] method. */ public var primaryDrawer: Drawer? = null set(value) { if (value != null) { field = value } } /** * A custom RecyclerView for the drawer items. Not recommended. * * Non-readable property. Wraps the [DrawerBuilder.withRecyclerView] method. */ public var recyclerView: RecyclerView @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withRecyclerView(value) } /** * The ViewGroup which will host the DrawerLayout. The content of this view will be extracted and added as the new * content inside the DrawerLayout. * * Non-readable property. Wraps the [DrawerBuilder.withRootView] method. */ public var rootView: ViewGroup @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withRootView(value) } /** * The ViewGroup which will host the DrawerLayout, given by its layout id. The content of this view will be * extracted and added as the new content inside the DrawerLayout. * * Non-readable property. Wraps the [DrawerBuilder.withRootView] method. */ public var rootViewRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withRootView(value) } /** * The bundle to restore state from after a configuration change. * * Remember to store the Drawer instance and call its * [saveInstanceState][com.mikepenz.materialdrawer.Drawer.saveInstanceState] method in the Activity's * [onSaveInstanceState][Activity.onSaveInstanceState] method, before calling super, to store the current state of * the drawer. * * Non-readable property. Wraps the [DrawerBuilder.withSavedInstance] method. */ public var savedInstance: Bundle? @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withSavedInstance(value) } /** * Whether the drawer should scroll to the top after an item has been clicked. * Default value is false. * * Non-readable property. Wraps the [DrawerBuilder.withScrollToTopAfterClick] method. */ public var scrollToTopAfterClick: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withScrollToTopAfterClick(value) } /** * The identifier of the item that should be selected by default. * Default value is 0L. * * Non-readable property. Wraps the [DrawerBuilder.withSelectedItem] method. */ public var selectedItem: Long @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withSelectedItem(value) } /** * The position of the item that should be selected by default. * Default value is 0. * * Non-readable property. Wraps the [DrawerBuilder.withSelectedItemByPosition] method. */ public var selectedItemByPosition: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withSelectedItemByPosition(value) } /** * The [SharedPreferences] to use to store state about [DrawerBuilderKt.showOnFirstLaunch] and * [DrawerBuilderKt.showUntilDraggedOpened] functionality. * Default value is the one provided by [PreferenceManager.getDefaultSharedPreferences]. * * Non-readable property. Wraps the [DrawerBuilder.withSavedInstance] method. */ public var sharedPreferences: SharedPreferences @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withSharedPreferences(value) } /** * Whether to automatically open the drawer the first time the user opens this Activity. * Default value is false. * * See [showOnFirstLaunch] as an alternative. * * Non-readable property. Wraps the [DrawerBuilder.withShowDrawerOnFirstLaunch] method. */ @Deprecated(level = DeprecationLevel.WARNING, message = "Alternatives are available, check the documentation.") public var showDrawerOnFirstLaunch: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withShowDrawerOnFirstLaunch(value) } /** * Whether to automatically open the drawer every time the user opens this Activity, until they've opened it once * themselves. * Default value is false. * * See [showUntilDraggedOpened] as an alternative. * * Non-readable property. Wraps the [DrawerBuilder.withShowDrawerUntilDraggedOpened] method. */ @Deprecated(level = DeprecationLevel.WARNING, message = "Alternatives are available, check the documentation.") public var showDrawerUntilDraggedOpened: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withShowDrawerUntilDraggedOpened(value) } /** * Whether to automatically open the drawer the first time the user opens this Activity. * Default value is false. * * Convenience for the [showDrawerOnFirstLaunch] property. Non-readable property. Wraps the * [DrawerBuilder.withShowDrawerOnFirstLaunch] method. */ public var showOnFirstLaunch: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withShowDrawerOnFirstLaunch(value) } /** * Whether to automatically open the drawer every time the user opens this Activity, until they've opened it once * themselves. * Default value is false. * * Convenience for [showDrawerUntilDraggedOpened]. Non-readable property. Wraps the * [DrawerBuilder.withShowDrawerUntilDraggedOpened] method. */ public var showUntilDraggedOpened: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withShowDrawerUntilDraggedOpened(value) } /** * The background of the drawer item list, as a drawable resource. * * Convenience for [sliderBackgroundRes]. Non-readable property. Wraps the * [DrawerBuilder.withSliderBackgroundDrawableRes] method. */ public var sliderBackground: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withSliderBackgroundDrawableRes(value) } /** * The background color of the drawer item list, as an argb Long. * * Non-readable property. Wraps the [DrawerBuilder.withSliderBackgroundColor] method. */ public var sliderBackgroundColor: Long @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withSliderBackgroundColor(value.toInt()) } /** * The background color of the drawer item list, as a color resource. * * Non-readable property. Wraps the [DrawerBuilder.withSliderBackgroundColorRes] method. */ public var sliderBackgroundColorRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withSliderBackgroundColorRes(value) } /** * The background of the drawer item list, as a Drawable. * * Non-readable property. Wraps the [DrawerBuilder.withSliderBackgroundDrawable] method. */ public var sliderBackgroundDrawable: Drawable @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withSliderBackgroundDrawable(value) } /** * The background of the drawer item list, as a drawable resource. * * See [sliderBackground] as an alternative. * * Non-readable property. Wraps the [DrawerBuilder.withSliderBackgroundDrawableRes] method. */ @Deprecated(level = DeprecationLevel.WARNING, message = "Alternatives are available, check the documentation.") public var sliderBackgroundRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withSliderBackgroundDrawableRes(value) } /** * An arbitrary View to use as the always visible footer of the drawer itself. * * Non-readable property. Wraps the [DrawerBuilder.withStickyFooter] method. */ public var stickyFooter: ViewGroup @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withStickyFooter(value) } /** * Whether there should be a divider above the sticky footer. * Default value is false. * * Non-readable property. Wraps the [DrawerBuilder.withStickyFooterDivider] method. */ public var stickyFooterDivider: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withStickyFooterDivider(value) } /** * An arbitrary layout resource to use as the always visible footer of the drawer itself. * * Non-readable property. Wraps the [DrawerBuilder.withStickyFooter] method. */ public var stickyFooterRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withStickyFooter(value) } /** * Whether the sticky footer should cast a shadow on the drawer item list. * Default value is true. * * Non-readable property. Wraps the [DrawerBuilder.withStickyFooterShadow] method. */ public var stickyFooterShadow: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withStickyFooterShadow(value) } /** * An arbitrary View to use as the always visible header of the drawer itself. * * Non-readable property. Wraps the [DrawerBuilder.withStickyHeader] method. */ public var stickyHeader: ViewGroup @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withStickyHeader(value) } /** * An arbitrary layout resource to use as the always visible header of the drawer itself. * * Non-readable property. Wraps the [DrawerBuilder.withStickyHeader] method. */ public var stickyHeaderRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withStickyHeader(value) } /** * Whether the sticky header should cast a shadow on the drawer item list (or the account header, if present). * Default value is true. * * Non-readable property. Wraps the [DrawerBuilder.withStickyHeaderShadow] method. */ public var stickyHeaderShadow: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withStickyHeaderShadow(value) } /** * To be used when you have a translucent navigation bar. * Default value is false. * * Convenience for [translucentNavigationBar]. Non-readable property. Wraps the * [DrawerBuilder.withTranslucentNavigationBar] method. */ public var supportTranslucentNavBar: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withTranslucentNavigationBar(value) } /** * To be used when you run your Activity in full screen mode, with hidden status bar and toolbar. * Default value is false. * * Non-readable property. Wraps the [DrawerBuilder.withSystemUIHidden] method. */ public var systemUIHidden: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withSystemUIHidden(value) } /** * The Toolbar in the Activity that's to be used with the drawer. This will handle creating the toggle for opening * and closing the drawer. * * Non-readable property. Wraps the [DrawerBuilder.withToolbar] method. */ public var toolbar: Toolbar @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withToolbar(value) } /** * If set to true, it makes the navigation bar translucent programmatically. * Default value is false. * * Convenience for [translucentNavigationBarProgrammatically]. Non-readable property. Wraps the * [DrawerBuilder.withTranslucentNavigationBarProgrammatically] method. */ public var translucentNavBar: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withTranslucentNavigationBarProgrammatically(value) } /** * To be used when you have a translucent navigation bar. * Default value is false. * * See [supportTranslucentNavBar] as an alternative. * * Non-readable property. Wraps the [DrawerBuilder.withTranslucentNavigationBar] method. */ @Deprecated(level = DeprecationLevel.WARNING, message = "Alternatives are available, check the documentation.") public var translucentNavigationBar: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withTranslucentNavigationBar(value) } /** * If set to true, it makes the navigation bar translucent programmatically. * Default value is false. * * See [translucentNavBar] as an alternative. * * Non-readable property. Wraps the [DrawerBuilder.withTranslucentNavigationBarProgrammatically] method. */ @Deprecated(level = DeprecationLevel.WARNING, message = "Alternatives are available, check the documentation.") public var translucentNavigationBarProgrammatically: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withTranslucentNavigationBarProgrammatically(value) } /** * Whether the View hosting the DrawerLayout should have a translucent status bar. This enables displaying the * drawer under the status bar. * Default value is true. * * Non-readable property. Wraps the [DrawerBuilder.withTranslucentStatusBar] method. */ public var translucentStatusBar: Boolean @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withTranslucentStatusBar(value) } /** * The width of the drawer in dps. * * Convenience for [drawerWidthDp]. Non-readable property. Wraps the [DrawerBuilder.withDrawerWidthDp] method. */ public var widthDp: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withDrawerWidthDp(value) } /** * The width of the drawer in pixels. * * Convenience for [drawerWidthPx]. Non-readable property. Wraps the [DrawerBuilder.withDrawerWidthPx] method. */ public var widthPx: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withDrawerWidthPx(value) } /** * The width of the drawer as a dimension resource. * * Convenience for [drawerWidthRes]. Non-readable property. Wraps the [DrawerBuilder.withDrawerWidthRes] method. */ public var widthRes: Int @Deprecated(level = DeprecationLevel.ERROR, message = "Non-readable property.") get() = nonReadable() set(value) { builder.withDrawerWidthRes(value) } //endregion }
apache-2.0
cbc356c6316b552bdd93481688641c13
35.628399
120
0.649868
4.946048
false
false
false
false
kivensolo/UiUsingListView
module-Common/src/main/java/com/kingz/module/wanandroid/bean/CollectBean.kt
1
1692
package com.kingz.module.wanandroid.bean class CollectBean { /** * author : 小编 * chapterId : 352 * chapterName : 资讯 * courseId : 13 * desc : * envelopePic : * id : 15915 * link : http://www.wanandroid.com/blog/show/2 * niceDate : 刚刚 * origin : * originId : 2864 * publishTime : 1530849681000 * title : 玩Android API * userId : 3273 * visible : 0 * zan : 0 */ var author: String? = null var chapterId = 0 var chapterName: String? = null var courseId = 0 var desc: String? = null var envelopePic: String? = null var id = 0 var link: String? = null var niceDate: String? = null var origin: String? = null var originId = -1 var publishTime: Long = 0 var title: String? = null var userId = 0 var visible = 0 var zan = 0 override fun toString(): String { return "CollectBean{" + "author='" + author + '\'' + ", chapterId=" + chapterId + ", chapterName='" + chapterName + '\'' + ", courseId=" + courseId + ", desc='" + desc + '\'' + ", envelopePic='" + envelopePic + '\'' + ", id=" + id + ", link='" + link + '\'' + ", niceDate='" + niceDate + '\'' + ", origin='" + origin + '\'' + ", originId=" + originId + ", publishTime=" + publishTime + ", title='" + title + '\'' + ", userId=" + userId + ", visible=" + visible + ", zan=" + zan + '}' } }
gpl-2.0
3a53b428714ebabeab86f035fd62b5a8
27.457627
56
0.445769
4.302564
false
false
false
false
jwren/intellij-community
platform/configuration-store-impl/src/SaveAndSyncHandlerImpl.kt
3
12434
// 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.configurationStore import com.intellij.CommonBundle import com.intellij.codeWithMe.ClientId import com.intellij.conversion.ConversionService import com.intellij.ide.* import com.intellij.openapi.Disposable import com.intellij.openapi.application.AccessToken import com.intellij.openapi.application.Application import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.impl.LaterInvocator import com.intellij.openapi.components.ComponentManager import com.intellij.openapi.components.StorageScheme import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.project.processOpenedProjects import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.newvfs.ManagingFS import com.intellij.openapi.vfs.newvfs.NewVirtualFile import com.intellij.openapi.vfs.newvfs.RefreshQueue import com.intellij.project.stateStore import com.intellij.util.SingleAlarm import com.intellij.util.application import com.intellij.util.concurrency.EdtScheduledExecutorService import com.intellij.util.concurrency.annotations.RequiresEdt import kotlinx.coroutines.* import java.beans.PropertyChangeListener import java.util.* import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicReference private const val LISTEN_DELAY = 15 internal class SaveAndSyncHandlerImpl : SaveAndSyncHandler(), Disposable { private val refreshDelayAlarm = SingleAlarm(Runnable { doScheduledRefresh() }, delay = 300, parentDisposable = this) private val blockSaveOnFrameDeactivationCount = AtomicInteger() private val blockSyncOnFrameActivationCount = AtomicInteger() @Volatile private var refreshSessionId = -1L private val saveQueue = ArrayDeque<SaveTask>() private val currentJob = AtomicReference<Job?>() private val eventPublisher = application.messageBus.syncPublisher(SaveAndSyncHandlerListener.TOPIC) init { // add listeners after some delay - doesn't make sense to listen earlier EdtScheduledExecutorService.getInstance().schedule({ addListeners() }, LISTEN_DELAY.toLong(), TimeUnit.SECONDS) } /** * If there is already running job, it doesn't mean that queue is processed - maybe paused on delay. * But even if `forceExecuteImmediately = true` specified, job is not re-added. * That's ok - client doesn't expect that `forceExecuteImmediately` means "executes immediately", it means "do save without regular delay". */ private fun requestSave(forceExecuteImmediately: Boolean = false) { if (currentJob.get() != null) { return } val app = ApplicationManager.getApplication() if (app == null || app.isDisposed || blockSaveOnFrameDeactivationCount.get() != 0) { return } currentJob.getAndSet(GlobalScope.launch { if (!forceExecuteImmediately) { delay(300) } processTasks(forceExecuteImmediately) currentJob.set(null) })?.cancel(CancellationException("Superseded by another request")) } private suspend fun processTasks(forceExecuteImmediately: Boolean) { while (true) { val app = ApplicationManager.getApplication() if (app == null || app.isDisposed || blockSaveOnFrameDeactivationCount.get() != 0) { return } val task = synchronized(saveQueue) { saveQueue.pollFirst() ?: return } if (task.project?.isDisposed == true) { continue } if (blockSaveOnFrameDeactivationCount.get() > 0 || ProgressManager.getInstance().hasModalProgressIndicator()) { return } LOG.runAndLogException { eventPublisher.beforeSave(task, forceExecuteImmediately) saveProjectsAndApp(forceSavingAllSettings = task.forceSavingAllSettings, onlyProject = task.project) } } } @RequiresEdt private fun addListeners() { val settings = GeneralSettings.getInstance() val idleListener = Runnable { if (settings.isAutoSaveIfInactive && canSyncOrSave()) { ClientId.withClientId(ClientId.ownerId) { (FileDocumentManagerImpl.getInstance() as FileDocumentManagerImpl).saveAllDocuments(false) } } } var disposable: Disposable? = null fun addIdleListener() { IdeEventQueue.getInstance().addIdleListener(idleListener, settings.inactiveTimeout * 1000) disposable = Disposable { IdeEventQueue.getInstance().removeIdleListener(idleListener) } Disposer.register(this, disposable!!) } settings.addPropertyChangeListener(GeneralSettings.PROP_INACTIVE_TIMEOUT, this, PropertyChangeListener { disposable?.let { Disposer.dispose(it) } addIdleListener() }) addIdleListener() if (LISTEN_DELAY >= (settings.inactiveTimeout * 1000)) { idleListener.run() } val busConnection = ApplicationManager.getApplication().messageBus.connect(this) busConnection.subscribe(FrameStateListener.TOPIC, object : FrameStateListener { override fun onFrameDeactivated() { externalChangesModificationTracker.incModificationCount() if (!settings.isSaveOnFrameDeactivation || !canSyncOrSave()) { return } // for web development it is crucially important to save documents on frame deactivation as early as possible (FileDocumentManager.getInstance() as FileDocumentManagerImpl).saveAllDocuments(false) if (addToSaveQueue(saveAppAndProjectsSettingsTask)) { requestSave() } } override fun onFrameActivated() { if (!ApplicationManager.getApplication().isDisposed && settings.isSyncOnFrameActivation) { scheduleRefresh() } } }) } override fun scheduleSave(task: SaveTask, forceExecuteImmediately: Boolean) { if (addToSaveQueue(task) || forceExecuteImmediately) { requestSave(forceExecuteImmediately) } } private fun addToSaveQueue(task: SaveTask): Boolean { synchronized(saveQueue) { if (task.project == null) { if (saveQueue.any { it.project == null }) { return false } saveQueue.removeAll { it.project != null } } else if (saveQueue.any { it.project == null || it.project === task.project }) { return false } return when { saveQueue.contains(task) -> false else -> saveQueue.add(task) } } } /** * On app or project closing save is performed. In EDT. It means that if there is already running save in a pooled thread, * deadlock may be occurred because some save activities requires EDT with modality state "not modal" (by intention). */ @RequiresEdt override fun saveSettingsUnderModalProgress(componentManager: ComponentManager): Boolean { if (!ApplicationManager.getApplication().isDispatchThread) { throw IllegalStateException( "saveSettingsUnderModalProgress is intended to be called only in EDT because otherwise wrapping into modal progress task is not required" + " and `saveSettings` should be called directly") } var isSavedSuccessfully = true var isAutoSaveCancelled = false disableAutoSave().use { currentJob.getAndSet(null)?.let { it.cancel(CancellationException("Superseded by explicit save")) isAutoSaveCancelled = true } synchronized(saveQueue) { if (componentManager is Application) { saveQueue.removeAll { it.project == null } } else { saveQueue.removeAll { it.project === componentManager } } } val project = (componentManager as? Project)?.takeIf { !it.isDefault } ProgressManager.getInstance().run(object : Task.Modal(project, getProgressTitle(componentManager), /* canBeCancelled = */ false) { override fun run(indicator: ProgressIndicator) { indicator.isIndeterminate = true runBlocking { isSavedSuccessfully = saveSettings(componentManager, forceSavingAllSettings = true) } if (project != null && !ApplicationManager.getApplication().isUnitTestMode) { val stateStore = project.stateStore val path = if (stateStore.storageScheme == StorageScheme.DIRECTORY_BASED) stateStore.projectBasePath else stateStore.projectFilePath // update last modified for all project files that were modified between project open and close ConversionService.getInstance()?.saveConversionResult(path) } } }) } if (isAutoSaveCancelled) { requestSave() } return isSavedSuccessfully } override fun dispose() { if (refreshSessionId != -1L) { RefreshQueue.getInstance().cancelSession(refreshSessionId) } } private fun canSyncOrSave(): Boolean { return !LaterInvocator.isInModalContext() && !ProgressManager.getInstance().hasModalProgressIndicator() } override fun scheduleRefresh() { externalChangesModificationTracker.incModificationCount() refreshDelayAlarm.cancelAndRequest() } private fun doScheduledRefresh() { eventPublisher.beforeRefresh() if (canSyncOrSave()) { refreshOpenFiles() } maybeRefresh(ModalityState.NON_MODAL) } override fun maybeRefresh(modalityState: ModalityState) { if (blockSyncOnFrameActivationCount.get() == 0 && GeneralSettings.getInstance().isSyncOnFrameActivation) { val queue = RefreshQueue.getInstance() queue.cancelSession(refreshSessionId) val session = queue.createSession(true, true, null, modalityState) session.addAllFiles(*ManagingFS.getInstance().localRoots) refreshSessionId = session.id session.launch() LOG.debug("vfs refreshed") } else { LOG.debug { "vfs refresh rejected, blocked: ${blockSyncOnFrameActivationCount.get() != 0}, isSyncOnFrameActivation: ${GeneralSettings.getInstance().isSyncOnFrameActivation}" } } } override fun refreshOpenFiles() { val files = ArrayList<VirtualFile>() processOpenedProjects { project -> FileEditorManager.getInstance(project).selectedEditors .flatMap { it.filesToRefresh } .filterTo(files) { it is NewVirtualFile } } if (files.isNotEmpty()) { // refresh open files synchronously so it doesn't wait for potentially longish refresh request in the queue to finish RefreshQueue.getInstance().refresh(false, false, null, files) } } override fun disableAutoSave(): AccessToken { blockSaveOnFrameDeactivation() return object : AccessToken() { override fun finish() { unblockSaveOnFrameDeactivation() } } } override fun blockSaveOnFrameDeactivation() { LOG.debug("save blocked") currentJob.getAndSet(null)?.cancel(CancellationException("Save on frame deactivation is disabled")) blockSaveOnFrameDeactivationCount.incrementAndGet() } override fun unblockSaveOnFrameDeactivation() { blockSaveOnFrameDeactivationCount.decrementAndGet() LOG.debug("save unblocked") } override fun blockSyncOnFrameActivation() { LOG.debug("sync blocked") blockSyncOnFrameActivationCount.incrementAndGet() } override fun unblockSyncOnFrameActivation() { blockSyncOnFrameActivationCount.decrementAndGet() LOG.debug("sync unblocked") } } private val saveAppAndProjectsSettingsTask = SaveAndSyncHandler.SaveTask() @NlsContexts.DialogTitle private fun getProgressTitle(componentManager: ComponentManager): String { return when { componentManager is Application -> CommonBundle.message("title.save.app") (componentManager as Project).isDefault -> CommonBundle.message("title.save.default.project") else -> CommonBundle.message("title.save.project") } }
apache-2.0
daff76ad83f662d0c6a3006c7766b920
35.466276
181
0.725993
5.133774
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReplaceUntilWithRangeToIntention.kt
5
1425
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe internal fun KtExpression.getArguments() = when (this) { is KtBinaryExpression -> this.left to this.right is KtDotQualifiedExpression -> this.receiverExpression to this.callExpression?.valueArguments?.singleOrNull()?.getArgumentExpression() else -> null } class ReplaceUntilWithRangeToIntention : SelfTargetingIntention<KtExpression>( KtExpression::class.java, KotlinBundle.lazyMessage("replace.with.0.operator", "..") ) { override fun isApplicableTo(element: KtExpression, caretOffset: Int): Boolean { if (element !is KtBinaryExpression && element !is KtDotQualifiedExpression) return false val fqName = element.getCallableDescriptor()?.fqNameUnsafe?.asString() ?: return false return fqName == "kotlin.ranges.until" } override fun applyTo(element: KtExpression, editor: Editor?) { val args = element.getArguments() ?: return element.replace(KtPsiFactory(element).createExpressionByPattern("$0..$1 - 1", args.first ?: return, args.second ?: return)) } }
apache-2.0
d8c1afae700a93be91c40dd16a430a75
46.533333
158
0.750877
4.79798
false
false
false
false
android/compose-samples
Owl/app/src/androidTest/java/com/example/owl/ui/NavigationTest.kt
1
4401
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.owl.ui import androidx.activity.ComponentActivity import androidx.activity.compose.LocalOnBackPressedDispatcherOwner import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.test.hasContentDescription import androidx.compose.ui.test.hasText import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import com.example.owl.R import com.example.owl.model.courses import com.example.owl.ui.fakes.installTestImageLoader import org.junit.Rule import org.junit.Test /** * Checks that the navigation flows in the app are correct. */ class NavigationTest { /** * Using an empty activity to have control of the content that is set. */ @get:Rule val composeTestRule = createAndroidComposeRule<ComponentActivity>() private fun startActivity(startDestination: String? = null) { installTestImageLoader() composeTestRule.setContent { CompositionLocalProvider( LocalOnBackPressedDispatcherOwner provides composeTestRule.activity ) { if (startDestination == null) { NavGraph() } else { NavGraph( startDestination = startDestination, showOnboardingInitially = false ) } } } } @Test fun firstScreenIsOnboarding() { // When the app is open startActivity() // The first screen should be the onboarding screen. // Assert that the FAB label for the onboarding screen exists: composeTestRule.onNodeWithContentDescription(getOnboardingFabLabel()).assertExists() } @Test fun onboardingToCourses() { // Given the app in the onboarding screen startActivity() // Navigate to the next screen by clicking on the FAB val fabLabel = getOnboardingFabLabel() composeTestRule.onNodeWithContentDescription(fabLabel).performClick() // The first course should be shown composeTestRule.onNodeWithText( text = courses.first().name, substring = true ).assertExists() } @Test fun coursesToDetail() { // Given the app in the courses screen startActivity(MainDestinations.COURSES_ROUTE) // Navigate to the first course composeTestRule.onNode( hasContentDescription(getFeaturedCourseLabel()).and( hasText( text = courses.first().name, substring = true ) ) ).performClick() // Assert navigated to the course details composeTestRule.onNodeWithText( text = getCourseDesc().take(15), substring = true ).assertExists() } @Test fun coursesToDetailAndBack() { coursesToDetail() composeTestRule.runOnUiThread { composeTestRule.activity.onBackPressed() } // The first course should be shown composeTestRule.onNodeWithText( text = courses.first().name, substring = true ).assertExists() } private fun getOnboardingFabLabel(): String { return composeTestRule.activity.resources.getString(R.string.label_continue_to_courses) } private fun getFeaturedCourseLabel(): String { return composeTestRule.activity.resources.getString(R.string.featured) } private fun getCourseDesc(): String { return composeTestRule.activity.resources.getString(R.string.course_desc) } }
apache-2.0
9e04e149dcdbbcd3cc249a485f404eda
31.6
95
0.660077
5.264354
false
true
false
false
smmribeiro/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/indexedProperty/impl.kt
5
1582
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.groovy.transformations.indexedProperty import com.intellij.psi.CommonClassNames.JAVA_UTIL_LIST import com.intellij.psi.PsiArrayType import com.intellij.psi.PsiClassType import com.intellij.psi.PsiType import com.intellij.psi.util.CachedValueProvider.Result import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiUtil import org.jetbrains.annotations.NonNls import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder internal const val indexedPropertyFqn = "groovy.transform.IndexedProperty" @NonNls internal const val indexedPropertyOriginInfo = "by @IndexedProperty" const val indexedMethodKind: String = "groovy.transform.IndexedProperty.kind" internal fun GrField.getIndexedComponentType() = CachedValuesManager.getCachedValue(this) { Result.create(doGetIndexedComponentType(this), containingFile) } private fun doGetIndexedComponentType(field: GrField): PsiType? { val fieldType = field.type return when (fieldType) { is PsiArrayType -> fieldType.componentType is PsiClassType -> PsiUtil.substituteTypeParameter(fieldType, JAVA_UTIL_LIST, 0, true) else -> null } } internal fun findIndexedPropertyMethods(field: GrField) = field.containingClass?.methods?.filter { it is GrLightMethodBuilder && it.methodKind == indexedMethodKind && it.navigationElement == field }
apache-2.0
53118511d724e93143fd8141f6e4f487
44.2
140
0.814791
4.334247
false
false
false
false
smmribeiro/intellij-community
platform/ide-core/src/com/intellij/openapi/ui/MessageDialogBuilder.kt
1
10622
// 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.openapi.ui import com.intellij.CommonBundle import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageConstants.* import com.intellij.openapi.ui.messages.MessagesService import com.intellij.openapi.ui.messages.MessagesService.Companion.getInstance import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsContexts.DialogMessage import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.WindowManager import com.intellij.ui.ComponentUtil import com.intellij.ui.mac.MacMessages import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.NonNls import java.awt.Component import java.awt.Window import javax.swing.Icon sealed class MessageDialogBuilder<T : MessageDialogBuilder<T>>(protected val title: @NlsContexts.DialogTitle String, protected val message: @DialogMessage String) { protected var yesText: String? = null protected var noText: String? = null protected var project: Project? = null protected var parentComponent: Component? = null protected var icon: Icon? = null protected var doNotAskOption: DoNotAskOption? = null @NonNls protected var helpId: String? = null protected abstract fun getThis(): T companion object { @JvmStatic fun yesNo(title: @NlsContexts.DialogTitle String, message: @DialogMessage String): YesNo { return YesNo(title, message).icon(UIUtil.getQuestionIcon()) } @JvmStatic fun okCancel(title: @NlsContexts.DialogTitle String, message: @DialogMessage String): OkCancelDialogBuilder { return OkCancelDialogBuilder(title, message).icon(UIUtil.getQuestionIcon()) } @JvmStatic fun yesNoCancel(title: @NlsContexts.DialogTitle String, message: @DialogMessage String): YesNoCancel { return YesNoCancel(title, message).icon(UIUtil.getQuestionIcon()) } } /** * @see asWarning * @see UIUtil.getInformationIcon * @see UIUtil.getWarningIcon * @see UIUtil.getErrorIcon * @see UIUtil.getQuestionIcon */ fun icon(icon: Icon?): T { this.icon = icon return getThis() } fun asWarning(): T { icon = UIUtil.getWarningIcon() return getThis() } fun doNotAsk(doNotAskOption: DoNotAskOption?): T { this.doNotAskOption = doNotAskOption return getThis() } fun yesText(yesText: @NlsContexts.Button String): T { this.yesText = yesText return getThis() } fun noText(noText: @NlsContexts.Button String): T { this.noText = noText return getThis() } fun help(@NonNls helpId: String): T { this.helpId = helpId return getThis() } class YesNo internal constructor(title: String, message: String) : MessageDialogBuilder<YesNo>(title, message) { override fun getThis() = this fun ask(project: Project?) = show(project = project, parentComponent = null) fun ask(parentComponent: Component?) = show(project = null, parentComponent = parentComponent) /** * Use this method only if you know neither project nor component. */ fun guessWindowAndAsk() = show(project = null, parentComponent = null) @Deprecated(message = "Use ask(project)", level = DeprecationLevel.ERROR) fun isYes(): Boolean = show(project = null, parentComponent = null) @Deprecated(message = "Use ask(project)", level = DeprecationLevel.ERROR) fun show(): Int = if (show(project = project, parentComponent = parentComponent)) YES else NO @YesNoResult private fun show(project: Project?, parentComponent: Component?): Boolean { val yesText = yesText ?: CommonBundle.getYesButtonText() val noText = noText ?: CommonBundle.getNoButtonText() return showMessage( project, parentComponent, mac = { MacMessages.getInstance().showYesNoDialog(title, message, yesText, noText, it, doNotAskOption, icon, helpId) }, other = { MessagesService.getInstance().showMessageDialog( project = project, parentComponent = parentComponent, message = message, title = title, icon = icon, options = arrayOf(yesText, noText), doNotAskOption = doNotAskOption, helpId = helpId, alwaysUseIdeaUI = true ) == YES } ) } } class YesNoCancel internal constructor(title: String, message: String) : MessageDialogBuilder<YesNoCancel>(title, message) { @NlsContexts.Button private var cancelText: String? = null fun cancelText(cancelText: @NlsContexts.Button String): YesNoCancel { this.cancelText = cancelText return getThis() } override fun getThis() = this @YesNoCancelResult fun show(project: Project?) = show(project = project, parentComponent = null) @YesNoCancelResult fun show(parentComponent: Component?) = show(project = null, parentComponent = parentComponent) @YesNoCancelResult fun guessWindowAndAsk() = show(project = null, parentComponent = null) @YesNoCancelResult private fun show(project: Project?, parentComponent: Component?): Int { val yesText = yesText ?: CommonBundle.getYesButtonText() val noText = noText ?: CommonBundle.getNoButtonText() val cancelText = cancelText ?: CommonBundle.getCancelButtonText() return showMessage(project, parentComponent, mac = { window -> MacMessages.getInstance().showYesNoCancelDialog(title, message, yesText, noText, cancelText, window, doNotAskOption, icon, helpId) }, other = { val options = arrayOf(yesText, noText, cancelText) when (MessagesService.getInstance().showMessageDialog(project = project, parentComponent = parentComponent, message = message, title = title, options = options, icon = icon, doNotAskOption = doNotAskOption, helpId = helpId, alwaysUseIdeaUI = true)) { 0 -> YES 1 -> NO else -> CANCEL } }) } } @ApiStatus.Experimental class Message(title: String, message: String) : MessageDialogBuilder<Message>(title, message) { private lateinit var buttons: List<String> private var defaultButton: String? = null private var focusedButton: String? = null override fun getThis() = this fun buttons(vararg buttonNames: String): Message { buttons = buttonNames.toList() return this } fun defaultButton(defaultButtonName: String): Message { defaultButton = defaultButtonName return this } fun focusedButton(focusedButtonName: String): Message { focusedButton = focusedButtonName return this } fun show(project: Project? = null, parentComponent: Component? = null): String? { val options = buttons.toTypedArray() val defaultOptionIndex = buttons.indexOf(defaultButton) val focusedOptionIndex = buttons.indexOf(focusedButton) val result = showMessage(project, parentComponent, mac = { window -> MacMessages.getInstance().showMessageDialog(title, message, options, window, defaultOptionIndex, focusedOptionIndex, doNotAskOption, icon, helpId) }, other = { MessagesService.getInstance().showMessageDialog(project = project, parentComponent = parentComponent, message = message, title = title, options = options, defaultOptionIndex = defaultOptionIndex, focusedOptionIndex = focusedOptionIndex, icon = icon, doNotAskOption = doNotAskOption, helpId = helpId, alwaysUseIdeaUI = true) }) return if (result < 0) null else buttons[result] } } } class OkCancelDialogBuilder internal constructor(title: String, message: String) : MessageDialogBuilder<OkCancelDialogBuilder>(title, message) { override fun getThis() = this fun ask(project: Project?) = show(project = project, parentComponent = null) fun ask(parentComponent: Component?) = show(project = null, parentComponent = parentComponent) /** * Use this method only if you know neither project nor component. */ fun guessWindowAndAsk() = show(project = null, parentComponent = null) private fun show(project: Project?, parentComponent: Component?): Boolean { val yesText = yesText ?: CommonBundle.getOkButtonText() val noText = noText ?: CommonBundle.getCancelButtonText() return showMessage(project, parentComponent, mac = { window -> MacMessages.getInstance().showYesNoDialog(title, message, yesText, noText, window, doNotAskOption, icon, helpId) }, other = { MessagesService.getInstance().showMessageDialog(project = project, parentComponent = parentComponent, message = message, title = title, options = arrayOf(yesText, noText), icon = icon, doNotAskOption = doNotAskOption, alwaysUseIdeaUI = true) == 0 }) } } private inline fun <T> showMessage(project: Project?, parentComponent: Component?, mac: (Window?) -> T, other: () -> T): T { if (canShowMacSheetPanel() || (SystemInfoRt.isMac && MessagesService.getInstance().isAlertEnabled())) { try { val window = if (parentComponent == null) { WindowManager.getInstance().suggestParentWindow(project) } else { ComponentUtil.getWindow(parentComponent) } return mac(window) } catch (e: Exception) { if (e.message != "Cannot find any window") { logger<MessagesService>().error(e) } } } return other() } fun canShowMacSheetPanel(): Boolean { if (!SystemInfoRt.isMac || getInstance().isAlertEnabled()) { return false } val app = ApplicationManager.getApplication() return app != null && !app.isUnitTestMode && !app.isHeadlessEnvironment && Registry.`is`("ide.mac.message.dialogs.as.sheets", true) }
apache-2.0
ca39249d1815f44a8fe5dce39206c64b
39.234848
158
0.663717
5.058095
false
false
false
false
ifabijanovic/swtor-holonet
android/app/src/main/java/com/ifabijanovic/holonet/helper/StringHelper.kt
1
1030
package com.ifabijanovic.holonet.helper /** * Created by feb on 19/03/2017. */ class StringHelper(private var string: String) { val value: String get() = this.string fun stripNewLinesAndTabs(): StringHelper { this.string = this.string.replace("\n", "").replace("\t", "") return this } fun trimSpaces(): StringHelper { this.string = this.string.trim(' ', '\n') return this } fun stripSpaces(): StringHelper { this.string = this.string.replace(" ", "") return this } fun collapseMultipleSpaces(): StringHelper { this.string = this.string.replace(Regex("[ ]+"), " ") return this } fun formatPostDate(): StringHelper { var value = this.collapseMultipleSpaces().string val separatorIndex = value.indexOf("| #") if (separatorIndex > 0) { value = value.substring(0, separatorIndex) } value = value.replace(" ,", ",") return StringHelper(value).trimSpaces() } }
gpl-3.0
817fd5c6c1e5fe76dec6c573f8067405
26.105263
69
0.587379
4.309623
false
false
false
false
kelemen/JTrim
buildSrc/src/main/kotlin/org/jtrim2/build/ProjectUtils.kt
1
5473
package org.jtrim2.build import java.nio.file.Path import java.util.Collections import java.util.Locale import java.util.function.Supplier import java.util.stream.Collectors import java.util.stream.Stream import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.artifacts.ExternalModuleDependencyBundle import org.gradle.api.artifacts.VersionCatalog import org.gradle.api.artifacts.VersionCatalogsExtension import org.gradle.api.model.ObjectFactory import org.gradle.api.plugins.JavaPluginExtension import org.gradle.api.provider.Provider import org.gradle.api.provider.ProviderFactory import org.gradle.jvm.toolchain.JavaLanguageVersion import org.gradle.jvm.toolchain.JavaToolchainService import org.gradle.jvm.toolchain.JavadocTool import org.gradle.kotlin.dsl.getByType import org.gradle.kotlin.dsl.listProperty import org.gradle.kotlin.dsl.the import org.gradle.kotlin.dsl.typeOf object ProjectUtils { fun runningWithSupervision(project: Project): Provider<Boolean> { return project.providers .gradleProperty("runningWithSupervision") .map { when (it.toLowerCase(Locale.ROOT)) { "false" -> false "true" -> true else -> throw IllegalArgumentException("Invalid boolean value: $it") } } .orElse(true) } fun getCompileJavaVersion(project: Project): JavaLanguageVersion { return JavaLanguageVersion.of(getVersion(project, "java")) } fun javadocTool(project: Project, toolchainService: JavaToolchainService): Provider<JavadocTool> { return toolchainService.javadocToolFor { languageVersion.set(JavaLanguageVersion.of(getVersion(project, "javadocVersion"))) } } fun scriptFile(project: Project, vararg subPaths: String): Path { val allPaths = ArrayList<String>(subPaths.size + 1) allPaths.add("gradle") allPaths.addAll(subPaths.asList()) return project.rootDir.withChildren(allPaths) } fun applyScript(project: Project, name: String) { project.apply(Collections.singletonMap("from", scriptFile(project, name))) } private fun libs(project: Project): VersionCatalog { return project.the<VersionCatalogsExtension>().named("libs") } fun getVersion(project: Project, name: String): String { val version = libs(project) .findVersion(name) .orElseThrow { NoSuchElementException("Missing version for $name") } val requiredVersion = version.requiredVersion if (requiredVersion.isNotEmpty()) { return requiredVersion } val strictVersion = version.strictVersion return if (strictVersion.isNotEmpty()) strictVersion else version.preferredVersion } fun getBundle(project: Project, name: String): Provider<ExternalModuleDependencyBundle> { return libs(project) .findBundle(name) .orElseThrow { NoSuchElementException("Missing bundle for $name") } } fun applyPlugin(project: Project, pluginName: String) { project.pluginManager.apply(pluginName) } inline fun <reified T : Plugin<*>> applyPlugin(project: Project) { project.pluginManager.apply(typeOf<T>().concreteClass) } fun getProjectInfo(project: Project): JTrimProjectInfo { return project.extensions.getByType() } private inline fun <reified T> getRootExtension(project: Project): T { return project.rootProject.extensions.getByType() } fun getLicenseInfo(project: Project): LicenseInfo { return getRootExtension(project) } fun getDevelopmentInfo(project: Project): JTrimDevelopment { return getRootExtension(project) } fun java(project: Project): JavaPluginExtension { return tryGetJava(project) ?: throw IllegalArgumentException("${project.path} does not have the java plugin applied.") } fun getModuleName(project: Project): String { return "${project.group}.${project.name.replace("jtrim-", "")}" } fun tryGetJava(project: Project): JavaPluginExtension? { return project.extensions.findByType(JavaPluginExtension::class.java) } fun getStringProperty(project: Project, name: String, defaultValue: String?): String? { if (!project.hasProperty(name)) { return defaultValue } val result = project.property(name) ?: return defaultValue val resultStr = result.toString() return resultStr.trim() } fun isReleasedProject(project: Project): Boolean { return project.plugins.findPlugin(JTrimJavaPlugin::class.java) != null } fun releasedSubprojects(parent: Project): Provider<List<Project>> { return releasedProjects(parent.objects, parent.providers) { parent.subprojects.stream() } } fun releasedProjects( objects: ObjectFactory, providers: ProviderFactory, projectsProviders: Supplier<out Stream<out Project>>): Provider<List<Project>> { val result = objects.listProperty<Project>() result.set(providers.provider { projectsProviders .get() .filter { isReleasedProject(it) } .collect(Collectors.toList()) }) return result } }
apache-2.0
f2525336ca8c7a407ee4a8ace0d6a60e
34.538961
107
0.672574
4.830538
false
false
false
false
ThiagoGarciaAlves/intellij-community
platform/lang-impl/src/com/intellij/codeInspection/ex/VisibleTreeStateComponent.kt
4
831
/* * 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.codeInspection.ex import com.intellij.codeInspection.InspectionProfile import com.intellij.openapi.components.BaseState import com.intellij.util.xmlb.annotations.MapAnnotation import com.intellij.util.xmlb.annotations.Property internal class VisibleTreeStateComponent : BaseState() { @get:Property(surroundWithTag = false) @get:MapAnnotation(surroundWithTag = false, surroundKeyWithTag = false, surroundValueWithTag = false) private var profileNameToState by map<String, VisibleTreeState>() fun getVisibleTreeState(profile: InspectionProfile) = profileNameToState.getOrPut(profile.name) { incrementModificationCount() VisibleTreeState() } }
apache-2.0
3b14360f5ae734296d289202ac1d83db
40.55
140
0.803851
4.540984
false
false
false
false
spinnaker/clouddriver
clouddriver-sql/src/main/kotlin/com/netflix/spinnaker/clouddriver/sql/event/dsl.kt
2
3743
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.clouddriver.sql.event import com.fasterxml.jackson.core.JsonProcessingException import com.fasterxml.jackson.databind.ObjectMapper import com.netflix.spinnaker.clouddriver.event.Aggregate import com.netflix.spinnaker.clouddriver.event.CompositeSpinnakerEvent import com.netflix.spinnaker.clouddriver.event.EventMetadata import com.netflix.spinnaker.clouddriver.event.SpinnakerEvent import com.netflix.spinnaker.clouddriver.event.exceptions.InvalidEventTypeException import org.jooq.Condition import org.jooq.Record import org.jooq.Select import org.jooq.SelectConditionStep import org.jooq.SelectJoinStep import org.jooq.impl.DSL.currentTimestamp /** * Adds an arbitrary number of [conditions] to a query joined by `AND` operator. */ internal fun <R : Record> SelectJoinStep<R>.withConditions(conditions: List<Condition>): SelectConditionStep<R> { return if (conditions.isNotEmpty()) this.where( conditions.reduce { acc, condition -> acc.and(condition) } ) else { where("1=1") } } /** * Internal model of [Aggregate]. */ internal class SqlAggregate( val model: Aggregate, val token: String ) /** * Runs [this] as a "select one" query and returns a single [SqlAggregate]. * It is assumed the underlying [Aggregate] exists. */ internal fun Select<out Record>.fetchAggregates(): List<SqlAggregate> = fetch().intoResultSet().let { rs -> mutableListOf<SqlAggregate>().apply { while (rs.next()) { add( SqlAggregate( model = Aggregate( type = rs.getString("aggregate_type"), id = rs.getString("aggregate_id"), version = rs.getLong("version") ), token = rs.getString("token") ) ) } } } /** * Converts a [SpinnakerEvent] to a SQL event row. The values are ordered the same as the schema's columns. */ internal fun SpinnakerEvent.toSqlValues(objectMapper: ObjectMapper): Collection<Any> = listOf( getMetadata().id, getMetadata().aggregateType, getMetadata().aggregateId, getMetadata().sequence, getMetadata().originatingVersion, currentTimestamp(), objectMapper.writeValueAsString(getMetadata()), // TODO(rz): optimize objectMapper.writeValueAsString(this) ) /** * Executes a SQL select query and converts the ResultSet into a list of [SpinnakerEvent]. */ internal fun Select<out Record>.fetchEvents(objectMapper: ObjectMapper): List<SpinnakerEvent> = fetch().intoResultSet().let { rs -> mutableListOf<SpinnakerEvent>().apply { while (rs.next()) { try { val event = objectMapper.readValue(rs.getString("data"), SpinnakerEvent::class.java).apply { setMetadata(objectMapper.readValue(rs.getString("metadata"), EventMetadata::class.java)) } if (event is CompositeSpinnakerEvent) { event.getComposedEvents().forEach { it.setMetadata(event.getMetadata().copy(id = "N/A", sequence = -1)) } } add(event) } catch (e: JsonProcessingException) { throw InvalidEventTypeException(e) } } } }
apache-2.0
9e0d3f7f0710d78100c93bce2f312ef3
33.027273
113
0.6965
4.342227
false
false
false
false
Softmotions/ncms
ncms-engine/ncms-engine-core/src/main/java/com/softmotions/ncms/mtt/http/MttRouteAction.kt
1
1797
package com.softmotions.ncms.mtt.http import com.google.inject.Inject import com.google.inject.Singleton import com.softmotions.ncms.NcmsEnvironment import org.slf4j.LoggerFactory import javax.annotation.concurrent.ThreadSafe import javax.servlet.http.HttpServletResponse /** * Route rule handler */ @Singleton @ThreadSafe @JvmSuppressWildcards open class MttRouteAction @Inject constructor(val env: NcmsEnvironment) : MttActionHandler { companion object { private val log = LoggerFactory.getLogger(MttRouteAction::class.java) } private val PAGEREF_REGEXP = Regex("page:\\s*([0-9a-f]{32})(\\s*\\|.*)?", RegexOption.IGNORE_CASE) override val type: String = "route" override fun execute(ctx: MttActionHandlerContext, rmc: MttRequestModificationContext, resp: HttpServletResponse): Boolean { val req = rmc.req val target = ctx.spec.path("target").asText("") if (target.isEmpty()) { if (log.isWarnEnabled) { log.warn("No target in spec") } return false } val appPrefix = env.appRoot + "/" val mres = PAGEREF_REGEXP.matchEntire(target) if (mres != null) { // Forward to internal page val guid = mres.groupValues[1] rmc.forward(appPrefix + guid, resp) } else { if ("://" in target) { rmc.redirect(target, resp) } else if (target.startsWith("//")) { rmc.redirect(req.scheme + ":" + target, resp) } else if (!target.startsWith(appPrefix)) { rmc.forward(appPrefix + target, resp) } else { rmc.forward(target, resp) } } return true } }
apache-2.0
c176d532e959a76d3be58527399b6c1a
30.54386
102
0.592654
4.299043
false
false
false
false
koma-im/koma
src/main/kotlin/link/continuum/desktop/database/roomDataStorage.kt
1
7660
package link.continuum.desktop.database import io.requery.kotlin.asc import io.requery.kotlin.desc import io.requery.kotlin.eq import io.requery.kotlin.isNull import javafx.scene.paint.Color import koma.gui.element.icon.placeholder.generator.hashStringColorDark import koma.koma_app.AppData import koma.matrix.UserId import koma.matrix.room.naming.RoomId import koma.network.media.MHUrl import koma.network.media.parseMxc import kotlinx.coroutines.Deferred import kotlinx.coroutines.async import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.* import kotlinx.serialization.builtins.ListSerializer import kotlinx.serialization.builtins.serializer import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonConfiguration import kotlinx.serialization.parse import link.continuum.database.models.* import link.continuum.desktop.Room import link.continuum.desktop.database.models.loadRoom import link.continuum.desktop.gui.list.user.UserDataStore import link.continuum.desktop.util.Account import link.continuum.desktop.util.getOrNull import link.continuum.desktop.util.toOption import mu.KotlinLogging import java.util.* import java.util.concurrent.ConcurrentHashMap private val logger = KotlinLogging.logger {} private val json = Json { allowStructuredMapKeys = true } fun RoomId.hashColor(): Color { return hashStringColorDark(this.full) } class RoomDataStorage( val data: KDataStore, val appData: AppData, private val userDatas: UserDataStore ) { private val store = ConcurrentHashMap<RoomId, Deferred<Room>>() suspend fun getOrCreate(roomId: RoomId, account: Account): Room { return coroutineScope { store.computeIfAbsent(roomId) { async { loadRoom(this@RoomDataStorage, roomId, account) } }.await() } } val latestName = LatestFlowMap<RoomId, Optional<String>>( save = { roomId: RoomId, s: Optional<String>, l: Long -> data.runOp { saveRoomName(this, roomId, s.getOrNull(), l) } }, init = { data.runOp { getLatestRoomName(this, it)} ?: run { 0L to Optional.empty<String>() } }) val latestCanonAlias = LatestFlowMap( save = { roomId: RoomId, s: Optional<String>, l: Long -> val rec: RoomCanonicalAlias = RoomCanonicalAliasEntity() rec.roomId = roomId.full rec.alias = s.getOrNull() rec.since = l data.runOp { upsert(rec) } }, init = { data.runOp { val c = RoomCanonicalAlias::roomId.eq(it.full) select(RoomCanonicalAlias::class).where(c) .get().firstOrNull() ?.let { it.since to it.alias.toOption() } }?: 0L to Optional.empty<String>() }) val latestAliasList = LatestFlowMap( save = { roomId: RoomId, s: List<String>, l: Long -> val ser = try { json.encodeToString(ListSerializer(String.serializer()), s) } catch (e: Exception) { return@LatestFlowMap } val rec = RoomAliasListEntity() rec.roomId = roomId.full rec.aliases = ser rec.since = l data.runOp { upsert(rec) } }, init = {roomId -> val c = RoomAliasList::roomId.eq(roomId.full) val rec = data.runOp {select(RoomAliasList::class) .where(c) .get().firstOrNull() } ?: return@LatestFlowMap 0L to listOf() val aliases = try { json.decodeFromString(ListSerializer(String.serializer()), rec.aliases) } catch (e: Exception) { return@LatestFlowMap 0L to listOf() } rec.since to aliases }) val latestAvatarUrl = LatestFlowMap( save = { RoomId: RoomId, url: Optional<MHUrl>, l: Long -> data.runOp { saveRoomAvatar(this, RoomId, url.getOrNull()?.toString(), l) } }, init = { id -> val rec = data.runOp {getLatestAvatar(this, id) } if (rec != null) { if (rec.second.isEmpty) { return@LatestFlowMap rec.first to Optional.empty<MHUrl>() } val s = rec.second.get() val mxc = s.parseMxc() if (mxc == null) { logger.warn { "invalid url $s"} return@LatestFlowMap rec.first to Optional.empty<MHUrl>() } rec.first to Optional.of(mxc) } else { 0L to Optional.empty() } }) val heroes = LatestFlowMap(save = { room: RoomId, heroes: List<UserId>, l: Long -> data.runOp { saveHeroes(room, heroes, l) } }, init = { room: RoomId -> val c = RoomHero::room.eq(room.id) val records = data.runOp { select(RoomHero::class) .where(c) .orderBy(RoomHero::since.desc()) .limit(5).get().toList() } val first = records.firstOrNull() if (first != null) { (first.since ?: 0L) to records.map { UserId(it.hero) } } else { val mems = data.runOp { val c1 = Membership::joiningRoom.isNull() val c2 = Membership::joiningRoom.eq(true) select(Membership::class).where( Membership::room.eq(room.id).and(c2.or(c1)) ).orderBy(Membership::since.asc()).limit(5).get().map { it.person } } logger.info { "no known heros in $room, using $mems"} 0L to mems.map {UserId(it)} } }) fun latestDisplayName(id: RoomId): Flow<String> { return latestName.receiveUpdates(id).flatMapLatest { val name = it?.getOrNull() if (name != null) { flowOf(name) } else { latestCanonAlias.receiveUpdates(id).flatMapLatest { val canon = it?.getOrNull() if (canon != null) { flowOf(canon) } else { latestAliasList.receiveUpdates(id).flatMapLatest { val first = it?.firstOrNull() if (first != null) { flowOf(first) } else { roomDisplayName(id, heroes, userDatas) } } } } } } } } private fun roomDisplayName( room: RoomId, heroes: LatestFlowMap<RoomId, List<UserId>>, userDatas: UserDataStore ): Flow<String> { return flow { emit(room.localstr) emitAll(heroes.receiveUpdates(room).filterNotNull().flatMapLatest { logger.info { "generating room name from heros $it" } combine(it.map { userDatas.getNameUpdates(it) }) { val n = it.filterNotNull().joinToString(", ") logger.info { "generated name $n"} n } }) } }
gpl-3.0
d00e96671d4b814bbecbef8fa06ec8eb
37.305
91
0.527807
4.737168
false
true
false
false
koma-im/koma
src/main/kotlin/koma/gui/view/window/auth/registration.kt
1
8287
package koma.gui.view.window.auth import javafx.geometry.Insets import javafx.scene.Parent import javafx.scene.control.* import javafx.scene.layout.BorderPane import javafx.scene.layout.GridPane import javafx.scene.layout.Priority import javafx.util.StringConverter import koma.AuthFailure import koma.Failure import koma.matrix.user.auth.AuthType import koma.matrix.user.auth.Register import koma.matrix.user.auth.RegisterdUser import koma.matrix.user.auth.Unauthorized import koma.util.KResult import koma.util.testFailure import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.javafx.JavaFx import kotlinx.coroutines.launch import link.continuum.database.models.KDataStore import link.continuum.desktop.database.KeyValueStore import link.continuum.desktop.gui.* import link.continuum.desktop.util.gui.alert import mu.KotlinLogging import okhttp3.HttpUrl import koma.util.KResult as Result private val logger = KotlinLogging.logger {} class RegistrationWizard( data: KDataStore, private val keyValueStore: KeyValueStore ) { val root = BorderPane() private var state: WizardState = Start(data) lateinit var register: Register init { with(root) { center = state.root bottom = BorderPane().apply { right = Button("OK").apply { action { GlobalScope.launch { nextStage() } } } } } } fun close() { } private suspend fun nextStage() { val cur = state if (cur is Start) { val (r, u) = cur.start()?:return register = r GlobalScope.launch(Dispatchers.JavaFx) { val a = Stage(r, u) state = a root.center = a.root } } else if (cur is Stage) { val (newUser, ex, res) = cur.submit()?: return if (!res.testFailure(newUser, ex)) { println("Successfully registered ${newUser.user_id}") keyValueStore.userToToken.put(newUser.user_id.full, newUser.access_token) val s = Success(newUser, register.server, this) state = s uilaunch { root.center = s.root } } else { when (ex) { is AuthFailure -> { GlobalScope.launch(Dispatchers.JavaFx) { val a = Stage(register, ex.fail) state = a root.center = a.root } } else -> { GlobalScope.launch(Dispatchers.JavaFx) { alert(Alert.AlertType.ERROR, "Registration failed", "Error $ex") [email protected]() } } } } } } } sealed class WizardState() { abstract val root: Parent } class Stage( private val register: Register, private val unauthorized: Unauthorized): WizardState() { override val root = BorderPane() private var authView: AuthView? = null suspend fun submit(): Result<RegisterdUser, Failure>? { return authView?.finish() } init { val options: List<AuthType> = unauthorized.flows .mapNotNull { flow -> flow.stages.firstOrNull() } .map { AuthType.parse(it) } with(root) { top = HBox().apply { label("Next step, continue with: ") add(HBox().apply { HBox.setHgrow(this, Priority.ALWAYS) }) add(ComboBox<AuthType>().apply { itemsProperty()?.value?.addAll(options) converter = object : StringConverter<AuthType>() { // This is not going to be called // because the ComboBox is editable override fun fromString(string: String?): AuthType { return AuthType.parse(string ?: "error") } override fun toString(item: AuthType): String { return item.toDisplay() } } selectionModel.selectedItemProperty().addListener { observable, oldValue, item -> if (item != null) { switchAuthType(item) } } selectionModel.select(0) }) } } } private fun switchAuthType(type: AuthType) { println("Switching to auth type $type") val a: AuthView = when (type) { is AuthType.Dummy -> PasswordAuthView(register, unauthorized) else -> FallbackWebviewAuth(register, unauthorized, type.type) } authView = a root.center = a.root } } private class Success(user: RegisterdUser, server: HttpUrl, window: RegistrationWizard): WizardState() { override val root = HBox() init { with(root) { vbox { label("Registration Success!") label(user.user_id.toString()) button("Login Now") { action { window.close() } } } } } } abstract class AuthView { abstract val root: Parent /** * if it returns non-null value, the stage is none * if the result is ok, registration is finished * if it is Unauthorized, more stages are needed * if it's other exceptions, registration has failed */ abstract suspend fun finish(): KResult<RegisterdUser, Failure>? } /** * Register by setting a password */ class PasswordAuthView( private val register: Register, private val unauthorized: Unauthorized ): AuthView() { /** * if it returns non-null value, the stage is none * if the result is ok, registration is finished * if it is Unauthorized, more stages are needed * if it's other exceptions, registration has failed */ override suspend fun finish(): KResult<RegisterdUser, Failure>? { TODO() } override val root = GridPane() val user = TextField() val pass = PasswordField() init { with(root) { padding = Insets(5.0) } } } class FallbackWebviewAuth( private val register: Register, private val unauthorized: Unauthorized, private val type: String ): AuthView() { override val root = Label("under construction") private var webAuthDone = false override suspend fun finish(): KResult<RegisterdUser, Failure>? { if (webAuthDone) { TODO("not sure whether there is a fallback method for registration") } else { uilaunch { alert(Alert.AlertType.ERROR, "Step not done yet", "Please complete the step in the displayed web page") } return null } } init { val url = register.server.newBuilder() .addPathSegments("_matrix/media/r0/download") .addEncodedPathSegment("auth") .addEncodedPathSegment(type) .addEncodedPathSegment("fallback") .addEncodedPathSegment("web") .addQueryParameter("session", unauthorized.session) .build() println("Using fallback webpage authentication: $url") } } private class Start(private val data: KDataStore): WizardState() { suspend fun start(): Pair<Register, Unauthorized>? { TODO() } private val serverCombo: ComboBox<String> override val root = VBox() init { with(root) { serverCombo = ComboBox<String>().apply { isEditable = true selectionModel.select(0) } add(serverCombo) } } } fun uilaunch(eval: suspend CoroutineScope.()->Unit) { GlobalScope.launch(Dispatchers.JavaFx, block = eval) }
gpl-3.0
71c301070ef8aa3c39a77e87cf3fd475
30.996139
104
0.554242
5.010278
false
false
false
false
addonovan/ftc-ext
ftc-ext/src/main/java/com/addonovan/ftcext/control/OpModeRegistrar.kt
1
3812
package com.addonovan.ftcext.control import com.addonovan.ftcext.* import com.addonovan.ftcext.config.* import com.addonovan.ftcext.reflection.ClassFinder import com.qualcomm.robotcore.eventloop.opmode.OpModeManager import com.qualcomm.robotcore.eventloop.opmode.OpModeRegister import java.util.* /** * The class responsible for finding all the OpModes that * are meant to be registered and actually register them * with the OpModeManager so that they may be selected. * * In order to be a valid OpMode, the class must: * * inherit from [AbstractOpMode] in some way * * be instantiable (i.e. not abstract) * * have the @[Register] annotation with a valid name * * Valid names for OpModes must: * * not consist entirely of whitespace * * not be "Stop Robot" * * contain an equals sign * * @see OpModeWrapper * @see LinearOpModeWrapper * * @author addonovan * @since 6/12/16 */ class OpModeRegistrar() : OpModeRegister, ILog by getLog( OpModeRegistrar::class ) { /** * Searches for all instantiable classes which inherit from [AbstractOpMode] * and have the [Register] annotation and will then verify the name of the * prospective OpMode and then create the correct OpModeWrapper for the * class and register it with Qualcomm's [OpModeManager]. * * @see AbstractOpMode * @see OpMode * @see LinearOpMode * @see OpModeWrapper * @see LinearOpModeWrapper */ @Suppress( "unchecked_cast" ) // the cast is check via reflections override fun register( manager: OpModeManager ) { i( "Discovering OpModes" ); // OpModes must be // instantiable // subclasses of ftcext's OpMode // and have the @Register annotation val opModeClasses = ClassFinder().inheritsFrom( AbstractOpMode::class.java ).with( Register::class.java ).get(); i( "Discovered ${opModeClasses.size} correctly formed OpMode classes!" ); for ( opMode in opModeClasses ) { val name = getRegisterName( opMode ); if ( name.isBlank() || name == "Stop Robot" || name.contains( "=" ) ) { e( "$name is NOT a valid OpMode name! Change it to something that is!" ); e( "OpMode names cannot be blank, null, \"Stop Robot\", or contain a '='" ); continue; // skip this one } // if it's a regular OpMode if ( OpMode::class.java.isAssignableFrom( opMode ) ) { getOpModeConfig( name, "default" ); // create a configuration for it manager.register( name, OpModeWrapper( opMode as Class< out OpMode > ) ); i( "Registered OpMode class ${opMode.simpleName} as $name" ); OpModes[ name ] = opMode; } // if it's a LinearOpMode else if ( LinearOpMode::class.java.isAssignableFrom( opMode ) ) { getOpModeConfig( name, "default" ); // create a configuration for it manager.register( name, LinearOpModeWrapper( opMode as Class< out LinearOpMode > ) ); i( "Registered LinearOpMode class ${opMode.simpleName} as $name" ); OpModes[ name ] = opMode; } // an unknown subclass of AbstractOpMode else { e( "Tried to register an unknown type of OpMode (class: ${opMode.name}) as $name" ); e( "OpModes must inherit from either com.addonovan.ftcext.control.OpMode or com.addonovan.ftcext.control.LinearOpMode!" ); } } attachRobotIconListener(); loadConfigs( CONFIG_FILE ); } } /** A map of OpModes and their registered names. */ val OpModes = HashMap< String, Class< out AbstractOpMode > >();
mit
2d45da106bae5d593de37f5f5d9da334
35.314286
138
0.621721
4.4637
false
true
false
false
fuzhouch/qbranch
compiler/src/test/kotlin/net/dummydigit/qbranch/compiler/parser/SourceFileLoaderTest.kt
1
3698
// Licensed under the MIT license. See LICENSE file in the project root // for full license information. package net.dummydigit.qbranch.compiler.parser import net.dummydigit.qbranch.compiler.SourceCodeFileLoader import java.io.FileNotFoundException import java.nio.file.Path import java.nio.file.Paths import net.dummydigit.qbranch.compiler.Settings import org.junit.Assert import org.junit.Test class SourceFileLoaderTest { private fun isMicrosoftWindows() : Boolean { return System.getProperty("os.name").toLowerCase().indexOf("win") >= 0 } private fun getAbsoluteHomePath() : Path { // ref: https://stackoverflow.com/questions/585534/what-is-the-best-way-to-find-the-users-home-directory-in-java // Note that USERPROFILE doesn't always work on bash.exe val homePath = Paths.get(System.getProperty("user.home")).toRealPath() Assert.assertTrue(homePath.isAbsolute) return homePath } private fun getTestAbsolutePath(parentPath : Path, createFile : Boolean) : Path { val milli = System.currentTimeMillis() val fileName = "qbranch_compiler_ut_$milli.bond" val filePath = parentPath.resolve(fileName) if (createFile) { Assert.assertEquals(true, filePath.toFile().createNewFile()) } return filePath } private fun getTestAbsolutePath(createFile : Boolean) : Path { return getTestAbsolutePath(getAbsoluteHomePath(), createFile) } @Test fun testLoadExistingFileWithoutInclude() { val testPath = getTestAbsolutePath(createFile = true) val settings = Settings() val loader = SourceCodeFileLoader(settings) try { val stream = loader.openStream(testPath.toString()) stream.close() } finally { testPath.toFile().delete() } } @Test(expected = FileNotFoundException::class) fun testLoadNonExistFileWithoutInclude() { val testPath = getTestAbsolutePath(createFile = false) val settings = Settings() val loader = SourceCodeFileLoader(settings) loader.openStream(testPath.toString()) } @Test(expected = FileNotFoundException::class) fun testThrowExceptionIfFileNotFoundInPath() { val homePath = getAbsoluteHomePath() val testPath = getTestAbsolutePath(homePath, createFile = false) val relativePath = homePath.relativize(testPath) val settings = Settings(includePaths = listOf(homePath.toString())) val loader = SourceCodeFileLoader(settings) loader.openStream(relativePath.toString()) } @Test fun testReturnFileWhenIncludePathExists() { val homePath = getAbsoluteHomePath() val testPath = getTestAbsolutePath(homePath, createFile = true) val relativePath = homePath.relativize(testPath) val settings = Settings(includePaths = listOf(homePath.toString())) val loader = SourceCodeFileLoader(settings) try { val stream = loader.openStream(relativePath.toString()) stream.close() } finally { testPath.toFile().delete() } } @Test fun testOpenFileUnderCurrentFolder() { val currentPath = Paths.get(".") val testPath = getTestAbsolutePath(currentPath, createFile = true) val relativePath = currentPath.relativize(testPath) val settings = Settings(includePaths = listOf()) val loader = SourceCodeFileLoader(settings) try { val stream = loader.openStream(relativePath.toString()) stream.close() } finally { testPath.toFile().delete() } } }
mit
e673817f6db74e4ac22404b260086bbf
35.264706
120
0.669551
5.051913
false
true
false
false
androidx/media
demos/session/src/main/java/androidx/media3/demo/session/MainActivity.kt
1
5959
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.media3.demo.session import android.content.ComponentName import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.ListView import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.media3.common.MediaItem import androidx.media3.session.LibraryResult import androidx.media3.session.MediaBrowser import androidx.media3.session.SessionToken import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton import com.google.common.util.concurrent.ListenableFuture class MainActivity : AppCompatActivity() { private lateinit var browserFuture: ListenableFuture<MediaBrowser> private val browser: MediaBrowser? get() = if (browserFuture.isDone) browserFuture.get() else null private lateinit var mediaListAdapter: FolderMediaItemArrayAdapter private lateinit var mediaListView: ListView private val treePathStack: ArrayDeque<MediaItem> = ArrayDeque() private var subItemMediaList: MutableList<MediaItem> = mutableListOf() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // setting up the layout setContentView(R.layout.activity_main) mediaListView = findViewById(R.id.media_list_view) mediaListAdapter = FolderMediaItemArrayAdapter(this, R.layout.folder_items, subItemMediaList) mediaListView.adapter = mediaListAdapter // setting up on click. When user click on an item, try to display it mediaListView.setOnItemClickListener { _, _, position, _ -> run { val selectedMediaItem = mediaListAdapter.getItem(position)!! // TODO(b/192235359): handle the case where the item is playable but it is not a folder if (selectedMediaItem.mediaMetadata.isPlayable == true) { val intent = PlayableFolderActivity.createIntent(this, selectedMediaItem.mediaId) startActivity(intent) } else { pushPathStack(selectedMediaItem) } } } findViewById<ExtendedFloatingActionButton>(R.id.open_player_floating_button) .setOnClickListener { // display the playing media items val intent = Intent(this, PlayerActivity::class.java) startActivity(intent) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { onBackPressed() return true } return super.onOptionsItemSelected(item) } override fun onBackPressed() { popPathStack() } override fun onStart() { super.onStart() initializeBrowser() } override fun onStop() { releaseBrowser() super.onStop() } private fun initializeBrowser() { browserFuture = MediaBrowser.Builder( this, SessionToken(this, ComponentName(this, PlaybackService::class.java)) ) .buildAsync() browserFuture.addListener({ pushRoot() }, ContextCompat.getMainExecutor(this)) } private fun releaseBrowser() { MediaBrowser.releaseFuture(browserFuture) } private fun displayChildrenList(mediaItem: MediaItem) { val browser = this.browser ?: return supportActionBar!!.setDisplayHomeAsUpEnabled(treePathStack.size != 1) val childrenFuture = browser.getChildren( mediaItem.mediaId, /* page= */ 0, /* pageSize= */ Int.MAX_VALUE, /* params= */ null ) subItemMediaList.clear() childrenFuture.addListener( { val result = childrenFuture.get()!! val children = result.value!! subItemMediaList.addAll(children) mediaListAdapter.notifyDataSetChanged() }, ContextCompat.getMainExecutor(this) ) } private fun pushPathStack(mediaItem: MediaItem) { treePathStack.addLast(mediaItem) displayChildrenList(treePathStack.last()) } private fun popPathStack() { treePathStack.removeLast() if (treePathStack.size == 0) { finish() return } displayChildrenList(treePathStack.last()) } private fun pushRoot() { // browser can be initialized many times // only push root at the first initialization if (!treePathStack.isEmpty()) { return } val browser = this.browser ?: return val rootFuture = browser.getLibraryRoot(/* params= */ null) rootFuture.addListener( { val result: LibraryResult<MediaItem> = rootFuture.get()!! val root: MediaItem = result.value!! pushPathStack(root) }, ContextCompat.getMainExecutor(this) ) } private class FolderMediaItemArrayAdapter( context: Context, viewID: Int, mediaItemList: List<MediaItem> ) : ArrayAdapter<MediaItem>(context, viewID, mediaItemList) { override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val mediaItem = getItem(position)!! val returnConvertView = convertView ?: LayoutInflater.from(context).inflate(R.layout.folder_items, parent, false) returnConvertView.findViewById<TextView>(R.id.media_item).text = mediaItem.mediaMetadata.title return returnConvertView } } }
apache-2.0
861d681f829fed738937a47ce54c31ea
31.210811
100
0.714717
4.710672
false
false
false
false
javiyt/nftweets
app/src/main/java/yt/javi/nftweets/ui/teams/DivisionFragment.kt
1
2716
package yt.javi.nftweets.ui import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import yt.javi.nftweets.R import yt.javi.nftweets.domain.model.Conference import yt.javi.nftweets.domain.model.Conference.valueOf import yt.javi.nftweets.domain.service.team.GetTeamsByConferenceService import yt.javi.nftweets.ui.teams.TeamAdapter import yt.javi.nftweets.ui.twitter.TwitterTimeLineActivity class DivisionFragment : Fragment() { private lateinit var recyclerView: RecyclerView lateinit var getTeamsByConferenceService: GetTeamsByConferenceService companion object { private val CONFERENCES = "conferences" fun newInstance(getTeamsByConferenceService: GetTeamsByConferenceService, conference: Conference): DivisionFragment { val divisionFragment = DivisionFragment() divisionFragment.getTeamsByConferenceService = getTeamsByConferenceService val bundle = Bundle() bundle.putString(CONFERENCES, conference.name) divisionFragment.arguments = bundle return divisionFragment } } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val viewGroup = inflater?.inflate(R.layout.division_fragment, container, false) as ViewGroup recyclerView = viewGroup.findViewById(R.id.teams_list) return viewGroup } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val teamAdapter = TeamAdapter( getTeamsByConferenceService, valueOf(arguments.getString(CONFERENCES)), onGoToTimelineClickListener() ) recyclerView.layoutManager = LinearLayoutManager(activity) recyclerView.adapter = teamAdapter } private fun onGoToTimelineClickListener(): (String, String, TwitterTimeLineActivity.TimelineType) -> Unit { return fun(twitterAccount: String, teamName: String, timelineType: TwitterTimeLineActivity.TimelineType) { val intent = Intent(activity, TwitterTimeLineActivity::class.java) intent.putExtra(TwitterTimeLineActivity.EXTRA_TWITTER_ACCOUNT, twitterAccount) intent.putExtra(TwitterTimeLineActivity.EXTRA_TEAM_NAME, teamName) intent.putExtra(TwitterTimeLineActivity.EXTRA_TWITTER_TIMELINE_TYPE, timelineType.name) startActivity(intent) } } }
apache-2.0
cc15978538b4489206716d50d3539249
36.736111
125
0.739323
5.223077
false
false
false
false
gradle/gradle
subprojects/kotlin-dsl-integ-tests/src/integTest/kotlin/org/gradle/kotlin/dsl/integration/GradleApiExtensionsIntegrationTest.kt
3
9288
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.integration import org.gradle.api.DomainObjectCollection import org.gradle.api.NamedDomainObjectCollection import org.gradle.api.NamedDomainObjectContainer import org.gradle.api.Task import org.gradle.api.tasks.Delete import org.gradle.api.tasks.TaskCollection import org.gradle.integtests.fixtures.ToBeFixedForConfigurationCache import org.gradle.kotlin.dsl.fixtures.containsMultiLineString import org.gradle.test.fixtures.file.LeaksFileHandles import org.hamcrest.CoreMatchers.allOf import org.hamcrest.CoreMatchers.containsString import org.hamcrest.CoreMatchers.not import org.hamcrest.MatcherAssert.assertThat import org.junit.Assert.assertTrue import org.junit.Test import java.io.File import java.util.jar.JarFile class GradleApiExtensionsIntegrationTest : AbstractPluginIntegrationTest() { @Test @ToBeFixedForConfigurationCache(because = "test captures script reference") fun `Kotlin chooses withType extension specialized to container type`() { withBuildScript( """ open class A open class B : A() inline fun <reified T> inferredTypeOf(value: T) = typeOf<T>().toString() task("test") { doLast { val ca = container(A::class) val cb = ca.withType<B>() println(inferredTypeOf(ca)) println(inferredTypeOf(cb)) val oca: DomainObjectCollection<A> = ca val ocb = oca.withType<B>() println(inferredTypeOf(oca)) println(inferredTypeOf(ocb)) val tt = tasks.withType<Task>() val td = tt.withType<Delete>() println(inferredTypeOf(tt)) println(inferredTypeOf(td)) } } """ ) assertThat( build("test", "-q").output, containsMultiLineString( """ ${NamedDomainObjectContainer::class.qualifiedName}<Build_gradle.A> ${NamedDomainObjectCollection::class.qualifiedName}<Build_gradle.B> ${DomainObjectCollection::class.qualifiedName}<Build_gradle.A> ${DomainObjectCollection::class.qualifiedName}<Build_gradle.B> ${TaskCollection::class.qualifiedName}<${Task::class.qualifiedName}> ${TaskCollection::class.qualifiedName}<${Delete::class.qualifiedName}> """ ) ) } @Test @ToBeFixedForConfigurationCache(because = "source dependency VCS mappings are defined") fun `can use Gradle API generated extensions in scripts`() { withFile( "init.gradle.kts", """ allprojects { container(String::class) } """ ) withDefaultSettings().appendText( """ sourceControl { vcsMappings { withModule("some:thing") { from(GitVersionControlSpec::class) { url = uri("") } } } } """ ) withBuildScript( """ container(String::class) apply(from = "plugin.gradle.kts") """ ) withFile( "plugin.gradle.kts", """ import org.apache.tools.ant.filters.ReplaceTokens // Class<T> to KClass<T> objects.property(Long::class) // Groovy named arguments to vararg of Pair fileTree("dir" to "src", "excludes" to listOf("**/ignore/**", "**/.data/**")) // Class<T> + Action<T> to KClass<T> + T.() -> Unit tasks.register("foo", Copy::class) { from("src") into("dst") // Class<T> + Groovy named arguments to KClass<T> + vararg of Pair filter(ReplaceTokens::class, "foo" to "bar") } """ ) build("foo", "-I", "init.gradle.kts") } @Test @LeaksFileHandles("Kotlin Compiler Daemon working directory") fun `can use Gradle API generated extensions in buildSrc`() { withKotlinBuildSrc() withFile( "buildSrc/src/main/kotlin/foo/FooTask.kt", """ package foo import org.gradle.api.* import org.gradle.api.model.* import org.gradle.api.tasks.* import org.gradle.kotlin.dsl.* import javax.inject.Inject import org.apache.tools.ant.filters.ReplaceTokens abstract class FooTask : DefaultTask() { @get:Inject abstract val objects: ObjectFactory @TaskAction fun foo() { objects.domainObjectContainer(Long::class) } } """ ) withFile( "buildSrc/src/main/kotlin/foo/foo.gradle.kts", """ package foo tasks.register("foo", FooTask::class) """ ) withBuildScript( """ plugins { id("foo.foo") } """ ) build("foo") } @Test fun `generated jar contains Gradle API extensions sources and byte code and is reproducible`() { val guh = newDir("guh") withBuildScript("") executer.withGradleUserHomeDir(guh) executer.requireIsolatedDaemons() build("help") val generatedJar = generatedExtensionsJarFromGradleUserHome(guh) val (generatedSources, generatedClasses) = JarFile(generatedJar) .use { it.entries().toList().map { entry -> entry.name } } .filter { it.startsWith("org/gradle/kotlin/dsl/GradleApiKotlinDslExtensions") } .groupBy { it.substring(it.lastIndexOf('.')) } .let { it[".kt"]!! to it[".class"]!! } assertTrue(generatedSources.isNotEmpty()) assertTrue(generatedClasses.size >= generatedSources.size) val generatedSourceCode = JarFile(generatedJar).use { jar -> generatedSources.joinToString("\n") { name -> jar.getInputStream(jar.getJarEntry(name)).bufferedReader().use { it.readText() } } } val extensions = listOf( "package org.gradle.kotlin.dsl", """ inline fun <S : T, T : Any> org.gradle.api.DomainObjectSet<T>.`withType`(`type`: kotlin.reflect.KClass<S>): org.gradle.api.DomainObjectSet<S> = `withType`(`type`.java) """, """ inline fun org.gradle.api.tasks.AbstractCopyTask.`filter`(`filterType`: kotlin.reflect.KClass<out java.io.FilterReader>, vararg `properties`: Pair<String, Any?>): org.gradle.api.tasks.AbstractCopyTask = `filter`(mapOf(*`properties`), `filterType`.java) """, """ inline fun <T : org.gradle.api.Task> org.gradle.api.tasks.TaskContainer.`register`(`name`: String, `type`: kotlin.reflect.KClass<T>, `configurationAction`: org.gradle.api.Action<in T>): org.gradle.api.tasks.TaskProvider<T> = `register`(`name`, `type`.java, `configurationAction`) """, """ inline fun <T : Any> org.gradle.api.plugins.ExtensionContainer.`create`(`name`: String, `type`: kotlin.reflect.KClass<T>, vararg `constructionArguments`: Any): T = `create`(`name`, `type`.java, *`constructionArguments`) """, """ inline fun <T : org.gradle.api.Named> org.gradle.api.model.ObjectFactory.`named`(`type`: kotlin.reflect.KClass<T>, `name`: String): T = `named`(`type`.java, `name`) """ ) assertThat( generatedSourceCode, allOf(extensions.map { containsString(it.trimIndent()) }) ) assertThat( generatedSourceCode, not(containsString("\r")) ) } private fun generatedExtensionsJarFromGradleUserHome(guh: File): File = Regex("^\\d.*").let { startsWithDigit -> guh.resolve("caches") .listFiles { f -> f.isDirectory && f.name.matches(startsWithDigit) } .single() .resolve("generated-gradle-jars") .listFiles { f -> f.isFile && f.name.startsWith("gradle-kotlin-dsl-extensions-") } .single() } }
apache-2.0
4d630591b8b1819d7fc4d542a6cb4755
32.530686
236
0.55814
4.88585
false
false
false
false
joseph-roque/BowlingCompanion
app/src/main/java/ca/josephroque/bowlingcompanion/transfer/TransferExportFragment.kt
1
4373
package ca.josephroque.bowlingcompanion.transfer import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import ca.josephroque.bowlingcompanion.R import ca.josephroque.bowlingcompanion.common.Android import ca.josephroque.bowlingcompanion.utils.Analytics import kotlinx.android.synthetic.main.dialog_transfer_export.export_status as exportStatus import kotlinx.android.synthetic.main.dialog_transfer_export.export_next_step as exportNextStep import kotlinx.android.synthetic.main.dialog_transfer_export.btn_cancel as cancelButton import kotlinx.android.synthetic.main.dialog_transfer_export.btn_export as exportButton import kotlinx.android.synthetic.main.dialog_transfer_export.progress as progressView import kotlinx.android.synthetic.main.dialog_transfer_export.view.* import kotlinx.coroutines.experimental.Job import kotlinx.coroutines.experimental.launch /** * Copyright (C) 2018 Joseph Roque * * A fragment to export user's data. */ class TransferExportFragment : BaseTransferFragment() { companion object { @Suppress("unused") private const val TAG = "TransferExportFragment" fun newInstance(): TransferExportFragment { return TransferExportFragment() } } private var exportJob: Job? = null private val onClickListener = View.OnClickListener { when (it.id) { R.id.btn_export -> { exportUserData() } R.id.btn_cancel -> { exportJob?.cancel() exportJob = null } } } // MARK: BaseTransferFragment override val toolbarTitle = R.string.export override val isBackEnabled = exportJob == null // MARK: Lifecycle functions override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.dialog_transfer_export, container, false) view.btn_export.setOnClickListener(onClickListener) view.btn_cancel.setOnClickListener(onClickListener) return view } // MARK: Private functions private fun getServerConnection(): TransferServerConnection? { val context = [email protected] ?: return null return TransferServerConnection.openConnection(context).apply { this.progressView = [email protected] this.cancelButton = [email protected] } } private fun exportFailed() { exportButton.visibility = View.VISIBLE exportNextStep.visibility = View.GONE exportStatus.apply { text = resources.getString(R.string.export_upload_failed) visibility = View.VISIBLE } } private fun exportSucceeded(serverResponse: String) { val requestIdRegex = "requestId:(.*)".toRegex() val key = requestIdRegex.matchEntire(serverResponse)?.groups?.get(1)?.value if (key == null) { exportFailed() return } exportNextStep.visibility = View.VISIBLE exportStatus.apply { text = resources.getString(R.string.export_upload_complete, key) visibility = View.VISIBLE } } private fun exportUserData() { exportJob = Job() launch(Android) { Analytics.trackTransferExport(Analytics.Companion.EventTime.Begin) try { val parentJob = exportJob ?: return@launch val connection = getServerConnection() ?: return@launch exportButton.visibility = View.GONE exportStatus.visibility = View.GONE if (!connection.prepareConnection(parentJob).await()) { exportFailed() } val serverResponse = connection.uploadUserData(parentJob).await() exportJob = null if (serverResponse.isNullOrEmpty()) { exportFailed() } else { exportSucceeded(serverResponse!!) } } catch (ex: Exception) { exportFailed() } finally { Analytics.trackTransferExport(Analytics.Companion.EventTime.End) } } } }
mit
0c933706a1b8d3791cfe1d13a8ba71f7
32.899225
116
0.649897
5.126612
false
false
false
false
AlmasB/FXGL
fxgl-gameplay/src/test/kotlin/com/almasb/fxgl/cutscene/dialogue/DialogueScriptRunnerTest.kt
1
3628
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ @file:Suppress("JAVA_MODULE_DOES_NOT_DEPEND_ON_MODULE") package com.almasb.fxgl.cutscene.dialogue import com.almasb.fxgl.core.collection.PropertyMap import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test /** * * @author Almas Baimagambetov ([email protected]) */ class DialogueScriptRunnerTest { private lateinit var runner: DialogueScriptRunner @BeforeEach fun setUp() { val map = PropertyMap() map.setValue("someInt", 5) map.setValue("someDouble", 3.0) map.setValue("someString", "hello") map.setValue("isAlive", true) map.setValue("isSleeping", false) runner = DialogueScriptRunner(map, PropertyMap(), object : FunctionCallHandler() { override fun handle(functionName: String, args: Array<String>): Any { var result: Any = "" if (functionName == "hasItem") { result = args[0] == "400" } return result } }) } @Test fun `Replace variables in text`() { var result = runner.replaceVariablesInText("Test \$someInt \$isSleeping \$isAlive \$someString \$someDouble") assertThat(result, `is`("Test 5 false true hello 3.0")) result = runner.replaceVariablesInText("Test \$someInt.") assertThat(result, `is`("Test 5.")) } @Test fun `Call a boolean function`() { assertTrue(runner.callBooleanFunction("hasItem 400")) assertFalse(runner.callBooleanFunction("hasItem 300")) } @Test fun `Boolean function returns false if cannot be parsed`() { assertFalse(runner.callBooleanFunction("bla-bla")) } @Test fun `Call a boolean function with single boolean variables`() { assertTrue(runner.callBooleanFunction("isAlive")) assertFalse(runner.callBooleanFunction("isSleeping")) } @Test fun `Call a boolean function with equality check operators`() { assertTrue(runner.callBooleanFunction("5.0 == 5.0")) assertFalse(runner.callBooleanFunction("5.0 == 7")) assertTrue(runner.callBooleanFunction("5 >= 5.0")) assertFalse(runner.callBooleanFunction("5 >= 7")) assertTrue(runner.callBooleanFunction("5 <= 5")) assertFalse(runner.callBooleanFunction("5 <= 3")) assertTrue(runner.callBooleanFunction("5 > 3")) assertFalse(runner.callBooleanFunction("5 > 7")) assertTrue(runner.callBooleanFunction("5 < 7")) assertFalse(runner.callBooleanFunction("5 < 3")) assertTrue(runner.callBooleanFunction("\$someInt == 5")) assertTrue(runner.callBooleanFunction("\$someDouble == 3.0")) assertTrue(runner.callBooleanFunction("\$someDouble < 3.5")) } @Test fun `Call a function with assignment statement`() { runner.callFunction("isPoisoned = false") assertFalse(runner.callBooleanFunction("isPoisoned")) runner.callFunction("isPoisoned = true") assertTrue(runner.callBooleanFunction("isPoisoned")) runner.callFunction("name = Test Name") assertTrue(runner.callBooleanFunction("\$name == Test Name")) runner.callFunction("someInt = 66") assertTrue(runner.callBooleanFunction("\$someInt == 66")) } }
mit
1723c04b3cbdf8d6814a3757623a91eb
31.693694
117
0.651323
4.627551
false
true
false
false
AndroidX/constraintlayout
projects/ComposeConstraintLayout/app/src/main/java/com/example/constraintlayout/verification/VTest02.kt
2
21993
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.constraintlayout.verification import androidx.compose.foundation.background import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.layoutId import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextDirection import androidx.compose.ui.tooling.preview.Preview import androidx.constraintlayout.compose.ConstraintLayout import androidx.constraintlayout.compose.ConstraintSet import com.example.constraintlayout.R @Preview(group = "VTest02d") @Composable fun VTest02a() { ConstraintLayout( ConstraintSet(""" { Header: { exportAs: 'test1'}, guid1: { type: 'vGuideline', start: 80 }, guide2: { type: 'vGuideline', end: 80 }, button1: { width: 'spread', top: ['title', 'bottom', 16], start: ['guid1', 'start'], end: ['guide2', 'end'] }, title: { width: { value: 'wrap', max: 300 }, centerVertically: 'parent', start: ['guid1', 'start'], end: ['guide2','end'] } } """), modifier = Modifier.fillMaxSize() ) { Button( modifier = Modifier.layoutId("button1"), onClick = {}, ) { Text(text = stringResource(id = R.string.log_in)) } Text(modifier = Modifier.layoutId("title").background(Color.Red), text = "ABC dsa sdfs sdf adfas asdas asdad asdas",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) } } @Preview(group = "VTest02d") @Composable fun VTest02b() { ConstraintLayout( ConstraintSet(""" { Header: { exportAs: 'test2'}, gl1: { type: 'hGuideline', start: 80 }, gl2: { type: 'hGuideline', end: 80 }, button2: { width: '38%', start: ['title', 'start', 16], bottom: ['gl2', 'bottom'], rotationZ: 32, }, title0: { width: 100, centerHorizontally: 'parent', top: ['gl1', 'bottom', 16], }, title1: { width: 'spread', centerHorizontally: 'title3', top: ['title0', 'bottom', 16], }, title2: { width: 'parent', centerHorizontally: 'parent', top: ['title1', 'bottom', 16], }, title3: { width: '38%' , centerHorizontally: 'parent', top: ['title2', 'bottom', 16], } } """), modifier = Modifier.fillMaxSize() ) { Button( modifier = Modifier.layoutId("button2"), onClick = {}, ) { Text(text = stringResource(id = R.string.log_in)) } Text(modifier = Modifier.layoutId("title0").background(Color.Red), text = "This is a test of width",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) Text(modifier = Modifier.layoutId("title1").background(Color.Red), text = "This is a test of width",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) Text(modifier = Modifier.layoutId("title2").background(Color.Red), text = "This is a test of width",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) Text(modifier = Modifier.layoutId("title3").background(Color.Red), text = "This is a test of width",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) } } @Preview(group = "VTest02d") @Composable public fun VTest02c() { ConstraintLayout( ConstraintSet(""" { Header: { exportAs: 'test3'}, gl1: { type: 'hGuideline', start: 80 }, gl2: { type: 'hGuideline', end: 80 }, ma: {type: 'barrier', direction: 'end' , contains: ['title0', 'title3'], margin: -12}, button3: { width: { value: 'wrap' }, height: 'spread', start: ['ma', 'start', 0], centerVertically: 'parent' }, title0: { width: { value: 'wrap', min: 60 }, centerHorizontally: 'parent', top: ['gl1', 'bottom', 16], }, title1: { width: { value: 'spread', min: 200 }, centerHorizontally: 'title3', top: ['title0', 'bottom', 16], }, title2: { width: { value: 'parent', min: 400 }, centerHorizontally: 'parent', top: ['title1', 'bottom', 16], }, title3: { width: { value: '30%' } , centerHorizontally: 'parent', top: ['title2', 'bottom', 16], }, title4: { width: { value: 'parent', max: 100 } , centerHorizontally: 'title3', top: ['title3', 'bottom', 16], }, title5: { width: { value: 'preferWrap' } , centerHorizontally: 'parent', top: ['title4', 'bottom', 16], } } """), modifier = Modifier.fillMaxSize() ) { Button( modifier = Modifier.layoutId("button3"), onClick = {}, ) { Text(text = stringResource(id = R.string.log_in)) } Text(modifier = Modifier.layoutId("title0").background(Color.White), text = "a b title0 d e",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) Text(modifier = Modifier.layoutId("title1").background(Color.White), text = "a b c d e f g h j title1 p q r s t u v w x y z",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) Text(modifier = Modifier.layoutId("title2").background(Color.White), text = "a b c d e f g h title2 n o p q r s t u v w x y z",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) Text(modifier = Modifier.layoutId("title3").background(Color.White), text = "a b c d e f g h j k title3 q r s t u v w x y z",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) Text(modifier = Modifier.layoutId("title4").background(Color.White), text = "a b c d e f g h j k l title4 m n o p q r s t u v w x y z",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) Text(modifier = Modifier.layoutId("title5").background(Color.White), text = "a b c d e f g h j k l title5 m n o p q r s t u v w x y z",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) } } @Preview(group = "VTest02d") @Composable public fun VTest02d() { ConstraintLayout( ConstraintSet(""" { Header: { exportAs: 'test4'}, lside: { type: 'vGuideline', percent: 0.33 }, rside: { type: 'vGuideline', percent: 0.66 }, button4: { width: { value: 'spread' }, start: ['lside', 'start' ], end: ['rside', 'end' ], bottom: ['parent', 'bottom',20], }, title0: { width: { value: 'spread', min: 200}, centerHorizontally: 'button4', top: ['parent', 'top', 20], }, title1: { width: { value: 'spread',max: 100 }, centerHorizontally: 'button4', top: ['title0', 'bottom', 16], }, title2: { width: { value: 'spread',min: 'wrap' }, centerHorizontally: 'button4', top: ['title1', 'bottom', 16], }, title3: { width: { value: 'spread',min: 'wrap' } , centerHorizontally: 'button4', top: ['title2', 'bottom', 16], }, title4: { width: { value: 'spread',min: 'I' } , centerHorizontally: 'button4', top: ['title3', 'bottom', 16], }, title5: { width: { value: 'spread' } , centerHorizontally: 'button4', top: ['title4', 'bottom', 16], } } """), modifier = Modifier.fillMaxSize() ) { Button( modifier = Modifier.layoutId("button4"), onClick = {}, ) { Text(text = stringResource(id = R.string.log_in)) } Text(modifier = Modifier.layoutId("title0").background(Color.Red), text = "a b c d e f g h j k l m n o p q r s t u v w x y z",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) Text(modifier = Modifier.layoutId("title1").background(Color.Red), text = "a b c d e f g h j k l m n o p q r s t u v w x y z",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) Text(modifier = Modifier.layoutId("title2").background(Color.Red), text = "a b c d e f g h j k l m n o p q r s t u v w x y z",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) Text(modifier = Modifier.layoutId("title3").background(Color.Red), text = "a b c d e f g h j k l m n o p q r s t u v w x y z",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) Text(modifier = Modifier.layoutId("title4").background(Color.White), text = "a b c d e f g h j k l preferWrap m n o p q r s t u v w x y z",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) Text(modifier = Modifier.layoutId("title5").background(Color.White), text = "a b c d e f g h j k l preferWrap m n o p q r s t u v w x y z",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) } } @Preview(group = "new") @Composable public fun VTest02e() { ConstraintLayout( ConstraintSet(""" { Header: { exportAs: 'test5'}, button5: { width: 'wrap', right: ['title','right'], centerVertically: 'parent', }, button5a: { width: 'wrap', left: ['title','left'], bottom: ['button5', 'top',20, 100], }, button5b: { width: 'wrap', start: ['title','start'], bottom: ['button5a', 'top',20, 100], }, button5c: { width: 'wrap', end: ['title','end'], bottom: ['button5b', 'top',20, 100], }, title: { width: 'wrap', centerHorizontally: 'parent', top: ['button5', 'bottom',20, 100], } } """), modifier = Modifier.fillMaxSize() ) { Button( modifier = Modifier.layoutId("button5"), onClick = {}, ) { Text(text = "right") } Button( modifier = Modifier.layoutId("button5a"), onClick = {}, ) { Text(text = "left") } Button( modifier = Modifier.layoutId("button5b"), onClick = {}, ) { Text(text = "start") } Button( modifier = Modifier.layoutId("button5c"), onClick = {}, ) { Text(text = "end") } Text(modifier = Modifier.layoutId("title").background(Color.Red), text = "ABC dsa sdfs sdf adfas asdas asdad asdas",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) } } @Preview(group = "new") @Composable public fun VTest02f() { ConstraintLayout( ConstraintSet(""" { Header: { exportAs: 'test6'}, button5: { width: 'wrap', pivotX: 0, pivotY: 0, rotationZ: 20, circular: ['title',0,120], }, button5a: { width: 'wrap', rotationZ: 90, circular: ['title',90,120], }, button5b: { width: 'wrap', rotationX: 30, circular: ['title',180,120], }, button5c: { width: 'wrap', rotationY: 30, scaleY: 1.4, circular: ['title',270,120], }, title: { width: 'wrap', translationZ: 13, scaleX: 1.4, centerHorizontally: 'parent', centerVertically: 'parent', }, base1: { width: 'wrap', right: ['title','right'], baseline: ['title','top',30], } } """), modifier = Modifier.fillMaxSize() ) { Button( modifier = Modifier.layoutId("button5"), onClick = {}, ) { Text(text = "12") } Button( modifier = Modifier.layoutId("button5a"), onClick = {}, ) { Text(text = "3") } Button( modifier = Modifier.layoutId("button5b"), onClick = {}, ) { Text(text = "6") } Button( modifier = Modifier.layoutId("button5c"), onClick = {}, ) { Text(text = "9") } Text(modifier = Modifier.layoutId("title").background(Color.Red), text = "clock", style = MaterialTheme.typography.body1, ) Button( modifier = Modifier.layoutId("base1"), onClick = {}, ) { Text(text = "baseline") } } } @Preview(group = "new") @Composable public fun VTest02g() { ConstraintLayout( ConstraintSet(""" { Header: { exportAs: 'test7'}, button5: { width: 'wrap', centerHorizontally: 'parent', centerVertically: 'parent', hBias: 0.1, vBias: 0.1, }, button5a: { width: 'wrap', centerHorizontally: 'parent', centerVertically: 'parent', hBias: 0.1, vBias: 0.9, }, button5b: { width: 'wrap', centerHorizontally: 'parent', centerVertically: 'parent', hBias: 0.9, vBias: 0.1, }, button5c: { width: 'wrap', centerHorizontally: 'parent', centerVertically: 'parent', hBias: 0.9, vBias: 0.9, }, title: { width: 'wrap', centerHorizontally: 'parent', centerVertically: 'parent', hBias: 0.5, vBias: 0.5, }, base1: { width: 'wrap', right: ['title','right'], top: ['button5','bottom',0], bottom: ['title','top',0], vBias: 0.1, } } """), modifier = Modifier.fillMaxSize() ) { Button( modifier = Modifier.layoutId("button5"), onClick = {}, ) { Text(text = "12") } Button( modifier = Modifier.layoutId("button5a"), onClick = {}, ) { Text(text = "3") } Button( modifier = Modifier.layoutId("button5b"), onClick = {}, ) { Text(text = "6") } Button( modifier = Modifier.layoutId("button5c"), onClick = {}, ) { Text(text = "9") } Text(modifier = Modifier.layoutId("title").background(Color.Red), text = "clock", style = MaterialTheme.typography.body1, ) Button( modifier = Modifier.layoutId("base1"), onClick = {}, ) { Text(text = "baseline") } } } @Preview(group = "new") @Composable public fun VTest02h() { ConstraintLayout( ConstraintSet(""" { Header: { exportAs: 'test8'}, Helpers: [ ['hChain', ['button5','button5a','button5b'], { start: ['title', 'end'], style: 'spread_inside'}], ['vChain', ['button5a','button5b','button5c'], { top: ['title', 'bottom'], style: 'spread'}], ], button5: { centerVertically: 'parent', vBias: 0.45 }, button5a: { centerVertically: 'parent', height: 'spread', vWeight: 1 }, button5b: { centerVertically: 'parent', height: 'spread', vWeight: 2 }, button5c: { width: 'wrap', height: 'spread', centerHorizontally: 'parent', centerVertically: 'parent', hBias: 0.9, vWeight: 3 }, title: { width: 'wrap', centerHorizontally: 'parent', centerVertically: 'parent', hBias: 0.1, vBias: 0.5, }, base1: { width: 'wrap', start: ['button5','start'], top: ['button5','bottom',0], bottom: ['parent','bottom',0], vBias: 0.5, } } """), modifier = Modifier.fillMaxSize() ) { Button( modifier = Modifier.layoutId("button5"), onClick = {}, ) { Text(text = "1") } Button( modifier = Modifier.layoutId("button5a"), onClick = {}, ) { Text(text = "2") } Button( modifier = Modifier.layoutId("button5b"), onClick = {}, ) { Text(text = "3") } Button( modifier = Modifier.layoutId("button5c"), onClick = {}, ) { Text(text = "4") } Text(modifier = Modifier.layoutId("title").background(Color.Red), text = "chain", style = MaterialTheme.typography.body1, ) Button( modifier = Modifier.layoutId("base1"), onClick = {}, ) { Text(text = "baseline") } } }
apache-2.0
7c77e30b5785c4caec8b660de455ffd7
31.776453
125
0.429955
4.721554
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/command/chatgroup/ChatGroupLeaveCommand.kt
1
4004
/* * Copyright 2021 Ren Binden * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.chat.bukkit.command.chatgroup import com.rpkit.chat.bukkit.RPKChatBukkit import com.rpkit.chat.bukkit.chatgroup.RPKChatGroupName import com.rpkit.chat.bukkit.chatgroup.RPKChatGroupService import com.rpkit.core.service.Services import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player /** * Chat group leave command. * Leaves a chat group. */ class ChatGroupLeaveCommand(private val plugin: RPKChatBukkit) : CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (!sender.hasPermission("rpkit.chat.command.chatgroup.leave")) { sender.sendMessage(plugin.messages["no-permission-chat-group-leave"]) return true } if (args.isEmpty()) { sender.sendMessage(plugin.messages["chat-group-leave-usage"]) return true } val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] if (minecraftProfileService == null) { sender.sendMessage(plugin.messages["no-minecraft-profile-service"]) return true } val chatGroupService = Services[RPKChatGroupService::class.java] if (chatGroupService == null) { sender.sendMessage(plugin.messages["no-chat-group-service"]) return true } chatGroupService.getChatGroup(RPKChatGroupName(args[0])).thenAccept { chatGroup -> if (chatGroup == null) { sender.sendMessage(plugin.messages["chat-group-leave-invalid-chat-group"]) return@thenAccept } if (sender !is Player) { sender.sendMessage(plugin.messages["not-from-console"]) return@thenAccept } val minecraftProfile = minecraftProfileService.getPreloadedMinecraftProfile(sender) if (minecraftProfile == null) { sender.sendMessage(plugin.messages["no-minecraft-profile"]) return@thenAccept } chatGroup.members.thenAccept getMembers@{ members -> if (members.none { memberMinecraftProfile -> memberMinecraftProfile.id == minecraftProfile.id }) { sender.sendMessage(plugin.messages["chat-group-leave-invalid-not-a-member"]) return@getMembers } plugin.server.scheduler.runTask(plugin, Runnable { chatGroup.removeMember(minecraftProfile).thenRun { chatGroup.members.thenAccept newMembers@{ newMembers -> if (newMembers.isEmpty()) { plugin.server.scheduler.runTask(plugin, Runnable { chatGroupService.removeChatGroup(chatGroup) }) } sender.sendMessage(plugin.messages["chat-group-leave-valid", mapOf( "group" to chatGroup.name.value )]) } } }) } } return true } }
apache-2.0
b86b8893df65b004f894c4f3382b3660
41.606383
118
0.613137
5.113665
false
false
false
false
newbieandroid/AppBase
app/src/main/java/com/fuyoul/sanwenseller/ui/main/main/BabyManagerItemFragment.kt
1
6414
package com.fuyoul.sanwenseller.ui.main.main import android.app.Activity import android.content.Intent import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.View import android.widget.TextView import com.alibaba.fastjson.JSON import com.csl.refresh.SmartRefreshLayout import com.fuyoul.sanwenseller.R import com.fuyoul.sanwenseller.base.BaseAdapter import com.fuyoul.sanwenseller.base.BaseFragment import com.fuyoul.sanwenseller.base.BaseViewHolder import com.fuyoul.sanwenseller.bean.AdapterMultiItem import com.fuyoul.sanwenseller.bean.MultBaseBean import com.fuyoul.sanwenseller.bean.reshttp.ResHttpBabyItem import com.fuyoul.sanwenseller.bean.reshttp.ResLoginInfoBean import com.fuyoul.sanwenseller.configs.Code import com.fuyoul.sanwenseller.structure.model.BabyManagerM import com.fuyoul.sanwenseller.structure.presenter.BabyManagerP import com.fuyoul.sanwenseller.structure.view.BabyManagerV import com.fuyoul.sanwenseller.ui.baby.EditBabyInfoActivity import com.fuyoul.sanwenseller.ui.user.LoginActivity import com.fuyoul.sanwenseller.utils.GlideUtils import kotlinx.android.synthetic.main.babymanageritem.* import org.litepal.crud.DataSupport /** * @author: chen * @CreatDate: 2017\10\27 0027 * @Desc: */ class BabyManagerItemFragment : BaseFragment<BabyManagerM, BabyManagerV, BabyManagerP>() { private var loginInfo = DataSupport.findFirst(ResLoginInfoBean::class.java)//登录信息 private var adapter: ThisAdapter? = null override fun setLayoutRes(): Int = R.layout.babymanageritem override fun init(view: View?, savedInstanceState: Bundle?) { adapter = initViewImpl().getBaseAdapter() val manager = LinearLayoutManager(context) manager.orientation = LinearLayoutManager.VERTICAL adapter?.getRecyclerView()?.layoutManager = manager adapter?.getRecyclerView()?.adapter = adapter getData(true) } override fun setListener() { babyManagerRefresh.setOnRefreshListener { getData(true) } babyManagerRefresh.setOnLoadmoreListener { getData(false) } } private var index = 0 private fun getData(isRefresh: Boolean) { if (isRefresh) { index = 0 } else { index++ } if (loginInfo == null) { initViewImpl().getBaseAdapter().setRefreshAndLoadMoreEnable(false) initViewImpl().getBaseAdapter().setReqLayoutInfo(isRefresh, false) initViewImpl().getBaseAdapter().setEmptyView(R.layout.notsignstatelayout) } else { initViewImpl().getBaseAdapter().setRefreshAndLoadMoreEnable(true) getPresenter().getData(context, isRefresh, index, loginInfo.userInfoId, arguments.getInt("status", Code.HOTSELL)) } } override fun getPresenter(): BabyManagerP = BabyManagerP(initViewImpl()) override fun initViewImpl(): BabyManagerV = object : BabyManagerV() { override fun editBaby(item: ResHttpBabyItem) { EditBabyInfoActivity.start(activity, item) } override fun getBaseAdapter(): BabyManagerItemFragment.ThisAdapter { if (adapter == null) { adapter = ThisAdapter() } return adapter!! } } inner class ThisAdapter : BaseAdapter(context) { override fun convert(holder: BaseViewHolder, position: Int, datas: List<MultBaseBean>) { val item = datas[position] as ResHttpBabyItem GlideUtils.loadNormalImg(context, JSON.parseArray(item.imgs).getJSONObject(0).getString("url"), holder.itemView.findViewById(R.id.babyItemIcon)) holder.itemView.findViewById<TextView>(R.id.babyItemTitle).text = item.goodsName holder.itemView.findViewById<TextView>(R.id.babyItemDes).text = item.introduce holder.itemView.findViewById<TextView>(R.id.babyItemPrice).text = "¥${item?.price}" val babyItemLeftFunc = holder.itemView.findViewById<TextView>(R.id.babyItemLeftFunc) val babyItemMiddleFunc = holder.itemView.findViewById<TextView>(R.id.babyItemMiddleFunc) val babyItemRightFunc = holder.itemView.findViewById<TextView>(R.id.babyItemRightFunc) if (arguments.getInt("status") == Code.SELL) { babyItemRightFunc.visibility = View.GONE babyItemMiddleFunc.text = "下架" } else { babyItemRightFunc.visibility = View.VISIBLE babyItemMiddleFunc.text = "上架" } babyItemLeftFunc.setOnClickListener { initViewImpl().editBaby(item) } babyItemMiddleFunc.setOnClickListener { if (arguments.getInt("status") == Code.SELL) { getPresenter().downToShop(context, position) } else { getPresenter().upToShop(context, position) } } babyItemRightFunc.setOnClickListener { getPresenter().deleteBaby(context, position) } } override fun addMultiType(multiItems: ArrayList<AdapterMultiItem>) { multiItems.add(AdapterMultiItem(Code.VIEWTYPE_BABYMANAGER, R.layout.babymanagerdataitem)) } override fun onItemClicked(view: View, position: Int) { } override fun onEmpryLayou(view: View, layoutResId: Int) { when (layoutResId) { R.layout.emptylayout -> { } R.layout.errorstatelayout -> { } R.layout.notsignstatelayout -> { view.findViewById<TextView>(R.id.errorLoginStateView).setOnClickListener { startActivity(Intent(context, LoginActivity::class.java)) } } } } override fun getSmartRefreshLayout(): SmartRefreshLayout = babyManagerRefresh override fun getRecyclerView(): RecyclerView = babyManagerDataList } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == Code.REQ_EDITBABYINFO && resultCode == Activity.RESULT_OK) { getData(true) } } }
apache-2.0
9c29dce8ca0dd3cf69c0a9a573c60525
34.73743
156
0.665416
4.886173
false
false
false
false
ajalt/clikt
clikt/src/commonMain/kotlin/com/github/ajalt/clikt/output/Localization.kt
1
8850
package com.github.ajalt.clikt.output import com.github.ajalt.clikt.core.* import com.github.ajalt.clikt.parameters.groups.ChoiceGroup import com.github.ajalt.clikt.parameters.groups.MutuallyExclusiveOptions /** * Strings to use for help output and error messages */ interface Localization { /** [Abort] was thrown */ fun aborted() = "Aborted!" /** Prefix for any [UsageError] */ fun usageError(message: String) = "Error: $message" /** Message for [BadParameterValue] */ fun badParameter() = "Invalid value" /** Message for [BadParameterValue] */ fun badParameterWithMessage(message: String) = "Invalid value: $message" /** Message for [BadParameterValue] */ fun badParameterWithParam(paramName: String) = "Invalid value for \"$paramName\"" /** Message for [BadParameterValue] */ fun badParameterWithMessageAndParam(paramName: String, message: String) = "Invalid value for \"$paramName\": $message" /** Message for [MissingOption] */ fun missingOption(paramName: String) = "Missing option \"$paramName\"" /** Message for [MissingArgument] */ fun missingArgument(paramName: String) = "Missing argument \"$paramName\"" /** Message for [NoSuchSubcommand] */ fun noSuchSubcommand(name: String, possibilities: List<String>): String { return "no such subcommand: \"$name\"" + when (possibilities.size) { 0 -> "" 1 -> ". Did you mean \"${possibilities[0]}\"?" else -> possibilities.joinToString(prefix = ". (Possible subcommands: ", postfix = ")") } } /** Message for [NoSuchOption] */ fun noSuchOption(name: String, possibilities: List<String>): String { return "no such option: \"$name\"" + when (possibilities.size) { 0 -> "" 1 -> ". Did you mean \"${possibilities[0]}\"?" else -> possibilities.joinToString(prefix = ". (Possible options: ", postfix = ")") } } /** * Message for [IncorrectOptionValueCount] * * @param count non-negative count of required values */ fun incorrectOptionValueCount(name: String, count: Int): String { return when (count) { 0 -> "option $name does not take a value" 1 -> "option $name requires a value" else -> "option $name requires $count values" } } /** * Message for [IncorrectArgumentValueCount] * * @param count non-negative count of required values */ fun incorrectArgumentValueCount(name: String, count: Int): String { return when (count) { 0 -> "argument $name does not take a value" 1 -> "argument $name requires a value" else -> "argument $name requires $count values" } } /** * Message for [MutuallyExclusiveGroupException] * * @param others non-empty list of other options in the group */ fun mutexGroupException(name: String, others: List<String>): String { return "option $name cannot be used with ${others.joinToString(" or ")}" } /** Message for [FileNotFound] */ fun fileNotFound(filename: String) = "$filename not found" /** Message for [InvalidFileFormat]*/ fun invalidFileFormat(filename: String, message: String) = "incorrect format in file $filename: $message" /** Message for [InvalidFileFormat]*/ fun invalidFileFormat(filename: String, lineNumber: Int, message: String) = "incorrect format in file $filename line $lineNumber: $message" /** Error in message for [InvalidFileFormat] */ fun unclosedQuote() = "unclosed quote" /** Error in message for [InvalidFileFormat] */ fun fileEndsWithSlash() = "file ends with \\" /** One extra argument is present */ fun extraArgumentOne(name: String) = "Got unexpected extra argument $name" /** More than one extra argument is present */ fun extraArgumentMany(name: String, count: Int) = "Got unexpected extra arguments $name" /** Error message when reading flag option from a file */ fun invalidFlagValueInFile(name: String) = "Invalid flag value in file for option $name" /** Error message when reading switch option from environment variable */ fun switchOptionEnvvar() = "environment variables not supported for switch options" /** Required [MutuallyExclusiveOptions] was not provided */ fun requiredMutexOption(options: String) = "Must provide one of $options" /** * [ChoiceGroup] value was invalid * * @param choices non-empty list of possible choices */ fun invalidGroupChoice(value: String, choices: List<String>): String { return "invalid choice: $value. (choose from ${choices.joinToString()})" } /** Invalid value for a parameter of type [Double] or [Float] */ fun floatConversionError(value: String) = "$value is not a valid floating point value" /** Invalid value for a parameter of type [Int] or [Long] */ fun intConversionError(value: String) = "$value is not a valid integer" /** Invalid value for a parameter of type [Boolean] */ fun boolConversionError(value: String) = "$value is not a valid boolean" /** Invalid value falls outside range */ fun rangeExceededMax(value: String, limit: String) = "$value is larger than the maximum valid value of $limit." /** Invalid value falls outside range */ fun rangeExceededMin(value: String, limit: String) = "$value is smaller than the minimum valid value of $limit." /** Invalid value falls outside range */ fun rangeExceededBoth(value: String, min: String, max: String) = "$value is not in the valid range of $min to $max." /** * Invalid value for `choice` parameter * * @param choices non-empty list of possible choices */ fun invalidChoice(choice: String, choices: List<String>): String { return "invalid choice: $choice. (choose from ${choices.joinToString()})" } /** The `pathType` parameter to [pathDoesNotExist] and other `path*` errors */ fun pathTypeFile() = "File" /** The `pathType` parameter to [pathDoesNotExist] and other `path*` errors */ fun pathTypeDirectory() = "Directory" /** The `pathType` parameter to [pathDoesNotExist] and other `path*` errors */ fun pathTypeOther() = "Path" /** Invalid path type */ fun pathDoesNotExist(pathType: String, path: String) = "$pathType \"$path\" does not exist." /** Invalid path type */ fun pathIsFile(pathType: String, path: String) = "$pathType \"$path\" is a file." /** Invalid path type */ fun pathIsDirectory(pathType: String, path: String) = "$pathType \"$path\" is a directory." /** Invalid path type */ fun pathIsNotWritable(pathType: String, path: String) = "$pathType \"$path\" is not writable." /** Invalid path type */ fun pathIsNotReadable(pathType: String, path: String) = "$pathType \"$path\" is not readable." /** Invalid path type */ fun pathIsSymlink(pathType: String, path: String) = "$pathType \"$path\" is a symlink." /** Metavar used for options with unspecified value type */ fun defaultMetavar() = "VALUE" /** Metavar used for options that take [String] values */ fun stringMetavar() = "TEXT" /** Metavar used for options that take [Float] or [Double] values */ fun floatMetavar() = "FLOAT" /** Metavar used for options that take [Int] or [Long] values */ fun intMetavar() = "INT" /** Metavar used for options that take `File` or `Path` values */ fun pathMetavar() = "PATH" /** Metavar used for options that take `InputStream` or `OutputStream` values */ fun fileMetavar() = "FILE" /** The title for the usage section of help output */ fun usageTitle(): String = "Usage:" /** The title for the options section of help output */ fun optionsTitle(): String = "Options:" /** The title for the arguments section of help output */ fun argumentsTitle(): String = "Arguments:" /** The title for the subcommands section of help output */ fun commandsTitle(): String = "Commands:" /** The that indicates where options may be present in the usage help output */ fun optionsMetavar(): String = "[OPTIONS]" /** The that indicates where subcommands may be present in the usage help output */ fun commandMetavar(): String = "COMMAND [ARGS]..." /** Text rendered for parameters tagged with [HelpFormatter.Tags.DEFAULT] */ fun helpTagDefault(): String = "default" /** Text rendered for parameters tagged with [HelpFormatter.Tags.REQUIRED] */ fun helpTagRequired(): String = "required" /** The default message for the `--help` option. */ fun helpOptionMessage(): String = "Show this message and exit" } internal val defaultLocalization = object : Localization {}
apache-2.0
0b10303c5314e9800553a2f5f60fbe4f
37.646288
120
0.652655
4.442771
false
false
false
false
t-yoshi/peca-android
libpeercast/src/main/java/org/peercast/core/lib/PeerCastController.kt
1
7598
package org.peercast.core.lib import android.app.ActivityManager import android.content.* import android.content.pm.PackageManager.NameNotFoundException import android.os.* import android.util.Log import android.widget.Toast import kotlinx.coroutines.delay import org.peercast.core.INotificationCallback import org.peercast.core.IPeerCastService import org.peercast.core.lib.internal.NotificationUtils import org.peercast.core.lib.internal.ServiceIntents import org.peercast.core.lib.notify.NotifyChannelType import org.peercast.core.lib.notify.NotifyMessageType import org.peercast.core.lib.rpc.ChannelInfo import java.util.* /** * PeerCast for Androidをコントロールする。 * * @licenses Dual licensed under the MIT or GPL licenses. * @author (c) 2019-2021, T Yoshizawa * @version 4.0.0 */ class PeerCastController private constructor(private val c: Context) { private var service: IPeerCastService? = null var eventListener: EventListener? = null set(value) { field = value if (isConnected) value?.onConnectService(this) } val isConnected: Boolean get() = service != null private val serviceConnection = object : ServiceConnection { override fun onServiceConnected(arg0: ComponentName, binder: IBinder) { Log.d(TAG, "onServiceConnected: interface=${binder.interfaceDescriptor}") if (binder.interfaceDescriptor == "org.peercast.core.IPeerCastService") { IPeerCastService.Stub.asInterface(binder)?.also { s -> service = s kotlin.runCatching { s.registerNotificationCallback(notificationCallback) }.onFailure { Log.w(TAG, it) } eventListener?.onConnectService(this@PeerCastController) } } else { Toast.makeText(c, "Please update PeerCast app.", Toast.LENGTH_LONG).show() } } override fun onServiceDisconnected(arg0: ComponentName?) { // OSにKillされたとき。 Log.d(TAG, "onServiceDisconnected") kotlin.runCatching { service?.unregisterNotificationCallback(notificationCallback) }.onFailure { Log.w(TAG, it) } service = null eventListener?.onDisconnectService() } } private val notificationCallback = object : INotificationCallback.Stub() { val handler = Handler(Looper.getMainLooper()) override fun onNotifyChannel(notifyType: Int, chId: String, jsonChannelInfo: String) { handler.post { eventListener?.onNotifyChannel( NotifyChannelType.values()[notifyType], chId, NotificationUtils.jsonToChannelInfo(jsonChannelInfo) ?: return@post ) } } override fun onNotifyMessage(types: Int, message: String) { handler.post { eventListener?.onNotifyMessage( NotifyMessageType.from(types), message ) } } } /** * 「PeerCast for Android」がインストールされているか調べる。 * @return "org.peercast.core" がインストールされていればtrue。 */ val isInstalled: Boolean get() { return try { c.packageManager.getApplicationInfo(ServiceIntents.PKG_PEERCAST, 0) true } catch (e: NameNotFoundException) { false } } interface EventListener { /** * bindService後にコネクションが確立されたとき。 */ fun onConnectService(controller: PeerCastController){} /** * unbindServiceを呼んだ後、もしくはOSによってサービスがKillされたとき。 */ fun onDisconnectService(){} /**通知を受信したとき*/ fun onNotifyMessage(types: EnumSet<NotifyMessageType>, message: String){} /**チャンネルの開始などの通知を受信したとき*/ fun onNotifyChannel(type: NotifyChannelType, channelId: String, channelInfo: ChannelInfo){} } /** * JSON-RPCへのエンドポイントを返す。 * 例: "http://127.0.0.1:7144/api/1" * @throws IllegalStateException サービスにbindされていない * @throws RemoteException 取得できないとき * */ val rpcEndPoint: String get() { val port = service?.port ?: error("service not connected.") return "http://127.0.0.1:$port/api/1" } /** * [Context.bindService]を呼び、PeerCastのサービスを開始する。 */ @Deprecated("use tryBindService()") fun bindService(): Boolean { if (!isInstalled) { Log.e(TAG, "PeerCast not installed.") return false } return c.bindService( ServiceIntents.SERVICE4_INTENT, serviceConnection, Context.BIND_AUTO_CREATE ) } private val isForeground: Boolean get() { val info = ActivityManager.RunningAppProcessInfo() ActivityManager.getMyMemoryState(info) return (info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND || info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE) } /** * [Context#bindService]を呼び、PeerCastサービスへの接続を試みる。 * ノート: * OSのカスタマイズ状況によっては、電池やセキリティー設定をいじっていて、 * バックグラウンドからのサービス起動を禁止している場合がある。なので、 * 一度Activity経由でフォアグラウンドでのサービス起動を試みる。 */ suspend fun tryBindService(): Boolean { if (!isInstalled) { Log.e(TAG, "PeerCast not installed.") return false } for (i in 0..2) { val r = c.bindService( ServiceIntents.SERVICE4_INTENT, serviceConnection, Context.BIND_AUTO_CREATE ) if (r) { if (isForeground) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { c.startForegroundService(ServiceIntents.SERVICE4_INTENT) } else { c.startService(ServiceIntents.SERVICE4_INTENT) } } return true } if (i == 0 && isForeground && c.packageName != ServiceIntents.PKG_PEERCAST) { try { c.startActivity(ServiceIntents.SERVICE_LAUNCHER_INTENT) } catch (e: RuntimeException) { Log.e(TAG, "startActivity failed:", e) } } delay(2_000) } return false } /** * [Context.unbindService]を呼ぶ。 他からもbindされていなければPeerCastサービスは終了する。 */ fun unbindService() { if (!isConnected) return c.unbindService(serviceConnection) serviceConnection.onServiceDisconnected(null) } companion object { @Deprecated("Obsoleted since v4.0") const val MSG_GET_APPLICATION_PROPERTIES = 0x00 private const val TAG = "PeCaCtrl" fun from(c: Context) = PeerCastController(c.applicationContext) } }
gpl-3.0
137425d710fff2a54cf5f3e5b2e9af99
31.465116
99
0.594986
4.517799
false
false
false
false
MuchMaxdome/JustToDo
app/src/main/java/ninja/maxdome/justtodo/AddView.kt
1
2976
package ninja.maxdome.justtodo import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.util.AttributeSet import android.view.View import ninja.maxdome.justtodo.R /** * Created by Maximilian on 24.08.2017. */ class AddView: View { val _Background: Paint = Paint() val _Border: Paint = Paint() val _Plus: Paint = Paint() var mHeight: Float = 0F var mWidth: Float = 0F var mRange: Float = 0F var mIsClicked: Boolean = false constructor(context: Context) : super(context) { init(null, 0) } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(attrs, 0) } constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) { init(attrs, defStyle) } private fun init(attrs: AttributeSet?, defStyle: Int){ _Background.color = resources.getColor(R.color.colorAccent) _Background.style = Paint.Style.FILL _Background.isAntiAlias = true _Border.color = resources.getColor(R.color.blackborder) _Border.style = Paint.Style.STROKE _Background.isAntiAlias = true _Plus.color = Color.WHITE _Plus.style = Paint.Style.FILL_AND_STROKE _Plus.isAntiAlias = true // this.setOnClickListener { onClick() } } override fun onDraw(canvas: Canvas?) { super.onDraw(canvas) mHeight = height.toFloat() mWidth = width.toFloat() } override fun draw(canvas: Canvas?) { super.draw(canvas) val radius: Float = Math.sqrt((height*height).toDouble()+(width*width).toDouble()).toFloat() / 10 if (mIsClicked){ canvas?.drawRoundRect(mRange, mRange, mWidth-mRange, mHeight-mRange, radius, radius, _Background) } canvas?.drawRoundRect(1F, 1F, width.toFloat()-1F,height.toFloat()-1F,radius,radius,_Background) /*--------------------------------------------------*/ for (i in 0..120){ val pos: Float = 1 + i*0.01F canvas?.drawRoundRect(pos, pos, width.toFloat()-pos,height.toFloat()-pos,radius,radius,_Border) } /*---------------------------------------------------*/ // draw the Plus in the middle val plusThickness = mWidth/12 canvas?.drawRect(mWidth/2-plusThickness/2, plusThickness*3, mWidth/2+plusThickness/2, mHeight-plusThickness*3, _Plus) canvas?.drawRect(plusThickness*3, mHeight/2-plusThickness/2, mWidth-plusThickness*3, mHeight/2+plusThickness/2, _Plus) } fun onClick(){ mIsClicked = true _Background.color =if (_Background.color == Color.WHITE) resources.getColor(R.color.colorAccent) else Color.WHITE _Plus.color =if (_Background.color == Color.WHITE) resources.getColor(R.color.colorAccent) else Color.WHITE invalidate() mIsClicked = false } }
apache-2.0
23e06603e7df6c68023d0ce855b9507d
30.010417
126
0.624664
4.060027
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/extensions/ExposedExtensions.kt
1
949
package net.perfectdreams.loritta.morenitta.utils.extensions import net.perfectdreams.loritta.morenitta.LorittaBot import org.jetbrains.exposed.dao.Entity /** * Refreshes the current entity within a transaction * * @see [Entity.refresh] */ fun Entity<*>.refreshInTransaction(loritta: LorittaBot, flush: Boolean = false) = loritta.transaction { [email protected](flush) } /** * Refreshes the current entity within a deferred transaction * * @see [Entity.refresh] */ suspend fun Entity<*>.refreshInDeferredTransaction(loritta: LorittaBot, flush: Boolean = false) = loritta.suspendedTransactionAsync { [email protected](flush) } /** * Refreshes the current entity within a async transaction * * @see [Entity.refresh] */ suspend fun Entity<*>.refreshInAsyncTransaction(loritta: LorittaBot, flush: Boolean = false) = loritta.newSuspendedTransaction { [email protected](flush) }
agpl-3.0
92c6f776f1b1d7cd882d9016331b8453
37
184
0.782929
4.393519
false
false
false
false
googlesamples/android-play-location
LocationAddressKotlin/app/src/main/java/com/google/android/gms/location/sample/locationaddress/FetchAddressIntentService.kt
1
6555
/* * 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.android.gms.location.sample.locationaddress import android.app.IntentService import android.content.Intent import android.location.Address import android.location.Geocoder import android.location.Location import android.os.Bundle import android.os.ResultReceiver import android.util.Log import java.io.IOException import java.util.Locale /** * Asynchronously handles an intent using a worker thread. Receives a ResultReceiver object and a * location through an intent. Tries to fetch the address for the location using a Geocoder, and * sends the result to the ResultReceiver. */ /** * This constructor is required, and calls the super IntentService(String) * constructor with the name for a worker thread. */ class FetchAddressIntentService : IntentService("FetchAddress") { private val TAG = "FetchAddressService" /** * The receiver where results are forwarded from this service. */ private var receiver: ResultReceiver? = null /** * Tries to get the location address using a Geocoder. If successful, sends an address to a * result receiver. If unsuccessful, sends an error message instead. * Note: We define a [android.os.ResultReceiver] in * MainActivity to process content * sent from this service. * * This service calls this method from the default worker thread with the intent that started * the service. When this method returns, the service automatically stops. */ override fun onHandleIntent(intent: Intent?) { var errorMessage = "" receiver = intent?.getParcelableExtra(Constants.RECEIVER) // Check if receiver was properly registered. if (intent == null || receiver == null) { Log.wtf(TAG, "No receiver received. There is nowhere to send the results.") return } // Get the location passed to this service through an extra. val location = intent.getParcelableExtra<Location>(Constants.LOCATION_DATA_EXTRA) // Make sure that the location data was really sent over through an extra. If it wasn't, // send an error error message and return. if (location == null) { errorMessage = getString(R.string.no_location_data_provided) Log.wtf(TAG, errorMessage) deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage) return } // Errors could still arise from using the Geocoder (for example, if there is no // connectivity, or if the Geocoder is given illegal location data). Or, the Geocoder may // simply not have an address for a location. In all these cases, we communicate with the // receiver using a resultCode indicating failure. If an address is found, we use a // resultCode indicating success. // The Geocoder used in this sample. The Geocoder's responses are localized for the given // Locale, which represents a specific geographical or linguistic region. Locales are used // to alter the presentation of information such as numbers or dates to suit the conventions // in the region they describe. val geocoder = Geocoder(this, Locale.getDefault()) // Address found using the Geocoder. var addresses: List<Address> = emptyList() try { // Using getFromLocation() returns an array of Addresses for the area immediately // surrounding the given latitude and longitude. The results are a best guess and are // not guaranteed to be accurate. addresses = geocoder.getFromLocation( location.latitude, location.longitude, // In this sample, we get just a single address. 1) } catch (ioException: IOException) { // Catch network or other I/O problems. errorMessage = getString(R.string.service_not_available) Log.e(TAG, errorMessage, ioException) } catch (illegalArgumentException: IllegalArgumentException) { // Catch invalid latitude or longitude values. errorMessage = getString(R.string.invalid_lat_long_used) Log.e(TAG, "$errorMessage. Latitude = $location.latitude , " + "Longitude = $location.longitude", illegalArgumentException) } // Handle case where no address was found. if (addresses.isEmpty()) { if (errorMessage.isEmpty()) { errorMessage = getString(R.string.no_address_found) Log.e(TAG, errorMessage) } deliverResultToReceiver(Constants.FAILURE_RESULT, errorMessage) } else { val address = addresses[0] // Fetch the address lines using {@code getAddressLine}, // join them, and send them to the thread. The {@link android.location.address} // class provides other options for fetching address details that you may prefer // to use. Here are some examples: // getLocality() ("Mountain View", for example) // getAdminArea() ("CA", for example) // getPostalCode() ("94043", for example) // getCountryCode() ("US", for example) // getCountryName() ("United States", for example) val addressFragments = with(address) { (0..maxAddressLineIndex).map { getAddressLine(it) } } Log.i(TAG, getString(R.string.address_found)) deliverResultToReceiver(Constants.SUCCESS_RESULT, addressFragments.joinToString(separator = "\n")) } } /** * Sends a resultCode and message to the receiver. */ private fun deliverResultToReceiver(resultCode: Int, message: String) { val bundle = Bundle().apply { putString(Constants.RESULT_DATA_KEY, message) } receiver?.send(resultCode, bundle) } }
apache-2.0
8fd654ee03cfe1185cf9c6b8dd835baa
42.7
100
0.659344
4.93228
false
false
false
false
christophpickl/gadsu
src/main/kotlin/at/cpickl/gadsu/mail/bulkmail/controller.kt
1
5791
package at.cpickl.gadsu.mail.bulkmail import at.cpickl.gadsu.client.Client import at.cpickl.gadsu.client.ClientService import at.cpickl.gadsu.client.ClientState import at.cpickl.gadsu.firstNotEmpty import at.cpickl.gadsu.global.QuitEvent import at.cpickl.gadsu.mail.Mail import at.cpickl.gadsu.mail.MailPreferencesData import at.cpickl.gadsu.mail.MailSender import at.cpickl.gadsu.preferences.Prefs import at.cpickl.gadsu.service.LOG import at.cpickl.gadsu.service.TemplateData import at.cpickl.gadsu.service.TemplateDeclaration import at.cpickl.gadsu.service.TemplatingEngine import at.cpickl.gadsu.view.AsyncDialogSettings import at.cpickl.gadsu.view.AsyncWorker import at.cpickl.gadsu.view.components.DialogType import at.cpickl.gadsu.view.components.Dialogs import com.google.api.client.googleapis.json.GoogleJsonResponseException import com.google.common.eventbus.Subscribe import javax.inject.Inject open class BulkMailController @Inject constructor( private val prefs: Prefs, private val mailSender: MailSender, private val clientService: ClientService, private val view: BulkMailView, private val dialogs: Dialogs, private val asyncWorker: AsyncWorker, private val templating: TemplatingEngine ) { private val log = LOG(javaClass) @Subscribe open fun onRequestOpenBulkMailEvent(event: RequestPrepareBulkMailEvent) { if (!ensurePreferencesSet()) { return } val mailEnabledClients = clientService.findAllForMail() view.initClients(mailEnabledClients) val mailPrefs = prefs.mailPreferencesData view.initSubject(mailPrefs.subject) view.initBody(mailPrefs.body) view.start() } @Subscribe open fun onRequestSendBulkMailEvent(event: RequestSendBulkMailEvent) { val mails = readMailsFromView() ?: return asyncWorker.doInBackground(AsyncDialogSettings("Versende Mail", "Verbindung zu GMail wird aufgebaut und Mails versendet ..."), { mails.forEach { mailSender.send(it) } }, { dialogs.show( title = "Mail versendet", message = "Die Mail wurde an ${mails.size} Empfänger erfolgreich versendet.", overrideOwner = view.asJFrame()) view.closeWindow() }, { e -> log.error("Failed to send mail!", e) val detailMessage = if (e is GoogleJsonResponseException) "\n(code: ${e.statusCode}, message: ${e.statusMessage})" //details=${e.details.map { "${it.key}: ${it.value}" }.join(", ")})" else "" dialogs.show( title = "Mail versendet", message = "Beim Versenden der Mail ist ein Fehler aufgetreten!$detailMessage", type = DialogType.ERROR, overrideOwner = view.asJFrame()) } ) } @Subscribe open fun onMailWindowClosedEvent(event: BulkMailWindowClosedEvent) { if (!event.shouldPersistState) { return } val subject = view.readSubject() val body = view.readBody() prefs.mailPreferencesData = MailPreferencesData(subject, body) } @Subscribe open fun onQuitEvent(event: QuitEvent) { view.destroy() } private fun ensurePreferencesSet(): Boolean { if (prefs.preferencesData.gmailAddress == null) { showDialog("Um Mails zu versenden muss zuerst eine GMail Adresse in den Einstellungen angegeben werden.") return false } if (prefs.preferencesData.gapiCredentials == null) { showDialog("Um Mails zu versenden müssen die Google API credentials gesetzt sein.") return false } return true } private fun readMailsFromView(): List<Mail>? { val recipients = view.readRecipients() val subject = view.readSubject() val body = view.readBody() if (recipients.isEmpty()) { dialogs.showInvalidInput("Es muss zumindest ein Klient ausgewählt sein!") return null } if (subject.isEmpty() || body.isEmpty()) { dialogs.showInvalidInput("Betreff und Mailinhalt darf nicht leer sein!") return null } return recipients.map { val data = BulkMailTemplateDeclaration.process(it) val processedSubject = templating.process(subject, data) val processedBody = templating.process(body, data) Mail(it.contact.mail, processedSubject, processedBody) } } private fun Dialogs.showInvalidInput(message: String) { dialogs.show( title = "Ungültige Eingabe", message = message, type = DialogType.WARN, overrideOwner = view.asJFrame()) } private fun showDialog(message: String) { dialogs.show(title = "Mail senden", message = message, type = DialogType.WARN) } private fun ClientService.findAllForMail(): List<Client> { return findAll(ClientState.ACTIVE).filter { it.wantReceiveMails && it.contact.mail.isNotBlank() } } } object BulkMailTemplateDeclaration : TemplateDeclaration<Client> { override val data = listOf( TemplateData<Client>("name", "Der externe Spitzname bzw Vorname falls nicht vorhanden, zB: \${name?lower_case}") { firstNotEmpty(it.nickNameExt, it.firstName) } ) }
apache-2.0
5b55d5a214fc189f6c7d4b75cef802b7
35.626582
157
0.618455
4.607484
false
false
false
false
cbeyls/fosdem-companion-android
app/src/main/java/be/digitalia/fosdem/utils/ThemeUtils.kt
1
2001
package be.digitalia.fosdem.utils import android.app.Activity import android.app.ActivityManager.TaskDescription import android.content.Context import android.content.res.ColorStateList import android.graphics.Color import android.graphics.ColorFilter import android.graphics.ColorMatrixColorFilter import android.os.Build import android.util.TypedValue import android.view.View import android.view.Window import android.widget.ImageView import androidx.annotation.ColorInt import androidx.core.graphics.drawable.DrawableCompat var Window.statusBarColorCompat: Int @ColorInt get() { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) statusBarColor else Color.BLACK } set(@ColorInt color) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { statusBarColor = color } } @Suppress("DEPRECATION") fun Activity.setTaskColorPrimary(@ColorInt colorPrimary: Int) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val taskDescription = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { TaskDescription(null, 0, colorPrimary or -0x1000000) } else { TaskDescription(null, null, colorPrimary or -0x1000000) } setTaskDescription(taskDescription) } } fun View.tintBackground(backgroundColor: ColorStateList?) { background?.let { it.mutate() DrawableCompat.setTintList(it, backgroundColor) } } val Context.isLightTheme: Boolean get() { val value = TypedValue() return theme.resolveAttribute(androidx.appcompat.R.attr.isLightTheme, value, true) && value.data != 0 } fun ImageView.invertImageColors() { val invertColorFilter: ColorFilter = ColorMatrixColorFilter(floatArrayOf( -1.0f, 0.0f, 0.0f, 0.0f, 255.0f, 0.0f, -1.0f, 0.0f, 0.0f, 255.0f, 0.0f, 0.0f, -1.0f, 0.0f, 255.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f )) colorFilter = invertColorFilter }
apache-2.0
67229d8568f88c696e9ba69eacc70d05
31.290323
109
0.697151
3.811429
false
false
false
false
christophpickl/gadsu
src/main/kotlin/at/cpickl/gadsu/tcm/elements_view.kt
1
6319
package at.cpickl.gadsu.tcm import at.cpickl.gadsu.global.Event import at.cpickl.gadsu.tcm.model.Element import at.cpickl.gadsu.view.brighterIfTrue import at.cpickl.gadsu.view.swing.addSingleLeftClickListener import com.github.christophpickl.kpotpourri.common.collection.toMutableMap import com.google.common.eventbus.EventBus import org.slf4j.LoggerFactory import java.awt.BasicStroke import java.awt.Color import java.awt.Cursor import java.awt.Graphics import java.awt.Graphics2D import java.awt.Point import java.awt.Rectangle import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.util.LinkedHashMap import javax.swing.JPanel abstract class ElementsEvent : Event() class ElementsOverEvent(val element: Element) : ElementsEvent() { override fun toString() = "ElementsOverEvent(element=$element)" } class ElementsOutEvent(val element: Element) : ElementsEvent() { override fun toString() = "ElementsOutEvent(element=$element)" } class ElementClickedEvent(val element: Element) : ElementsEvent() { override fun toString() = "ElementClickedEvent(element=$element)" } class ElementsStarView( val bus: EventBus, // FUTURE pass values for each element, indicating their size from -1.0, 0.0 (normal) up to +1.0 (max size) val CIRCLE_DIAMETER: Int = 140 ) : JPanel() { private val log = LoggerFactory.getLogger(javaClass) val FRAME_PADDING = 10 val CIRCLE_RADIUS = CIRCLE_DIAMETER / 2 val CIRCLE_PADDING = FRAME_PADDING + CIRCLE_RADIUS private var coordinates = calcCoordinates() private var overs: MutableMap<Element, Boolean> = Element.values().map { Pair(it, false) }.toMutableMap() init { isOpaque = true addSingleLeftClickListener({ onMouseClicked(it) }) addMouseMotionListener(object : MouseAdapter() { override fun mouseMoved(e: MouseEvent) { onMouseMoved(e.point) } }) } override fun paintComponent(rawGraphics: Graphics) { // println("paintComponent() size=$size") super.paintComponent(rawGraphics) val g = rawGraphics as Graphics2D coordinates = calcCoordinates() drawBackground(g) drawLines(g) drawCircle(g) } private fun drawBackground(g: Graphics2D) { g.color = Color.LIGHT_GRAY g.fillRect(FRAME_PADDING, FRAME_PADDING, width - (FRAME_PADDING * 2), height - (FRAME_PADDING * 2)) } private fun onMouseClicked(point: Point) { log.trace("onMouseClicked(point={})", point) val overElement = overs.filterValues { it == true }.keys.firstOrNull() ?: return bus.post(ElementClickedEvent(overElement)) } private fun onMouseMoved(point: Point) { // println("onMouseMoved(point=$point)") val g = graphics as Graphics2D val mouseArea = Rectangle(point.x, point.y, 1, 1) var repaintRequired = false coordinates.coordinateByElement.forEach { element, coordinate -> if (g.hit(coordinate.hitArea, mouseArea, false)) { if (overs[element] == false) { // println("hit on [$element] at $point") overs.put(element, true) repaintRequired = true cursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) bus.post(ElementsOverEvent(element)) } } else { if (overs[element] == true) { overs.put(element, false) repaintRequired = true cursor = Cursor.getDefaultCursor() bus.post(ElementsOutEvent(element)) } } } if (repaintRequired) { repaint() } } private fun drawLines(g: Graphics2D) { g.color = Color.BLACK g.stroke = BasicStroke(2.0F) coordinates.coordinatesArray.forEachIndexed { i, pair -> val point = pair.second.center val nextElementIndex = if (i == 4) 0 else i + 1 val nextPoint = coordinates.coordinatesArray[nextElementIndex].second.center g.drawLine(point.x, point.y, nextPoint.x, nextPoint.y) } } private fun drawCircle(g: Graphics2D) { coordinates.coordinateByElement.forEach { g.fillCircleAt(it.value.center, CIRCLE_DIAMETER, it.key.color.brighterIfTrue(overs[it.key]!!)) } } private fun calcCoordinates(): ElementsCoordinates { val verticalGap = (height - CIRCLE_PADDING * 2) / 2 val horizontalGap = (width / 2 - CIRCLE_PADDING) / 2 val map = LinkedHashMap<Element, Coordinate>(5) map.put(Element.Wood, ensuredPoint(CIRCLE_PADDING, verticalGap)) map.put(Element.Fire, ensuredPoint(width / 2, CIRCLE_PADDING)) map.put(Element.Earth, ensuredPoint(width - CIRCLE_PADDING, verticalGap)) map.put(Element.Metal, ensuredPoint(width - CIRCLE_PADDING - horizontalGap, height - CIRCLE_PADDING)) map.put(Element.Water, ensuredPoint(0 + CIRCLE_PADDING + horizontalGap, height - CIRCLE_PADDING)) return ElementsCoordinates(map) } private fun ensuredPoint(x: Int, y: Int): Coordinate { val center = Point( Math.min(Math.max(x, CIRCLE_PADDING), width - CIRCLE_PADDING), Math.min(Math.max(y, CIRCLE_PADDING), height - CIRCLE_PADDING) ) val hitArea = Rectangle(center.x - CIRCLE_RADIUS, center.y - CIRCLE_RADIUS, CIRCLE_DIAMETER, CIRCLE_DIAMETER) return Coordinate(center, hitArea) } } data class Coordinate(val center: Point, val hitArea: Rectangle) private data class ElementsCoordinates( val coordinateByElement: LinkedHashMap<Element, Coordinate> ) { val coordinatesArray: Array<Pair<Element, Coordinate>> = coordinateByElement.map { Pair(it.key, it.value) }.toTypedArray() } /** * Given point location will be the center of the drawed circle (java defaults to top left corner). */ fun Graphics2D.fillCircleAt(point: Point, diameter: Int, color: Color? = null) { if (color != null) { this.color = color } val radius = diameter / 2.0 val x = point.x - radius val y = point.y - radius fillOval(x.toInt(), y.toInt(), diameter, diameter) }
apache-2.0
d073e517ff965ce0bff16c5d90f68565
34.5
126
0.649786
4.226756
false
false
false
false
chRyNaN/GuitarChords
sample/src/main/java/com/chrynan/sample/util/ToneEqualNoteUtils.kt
1
753
package com.chrynan.sample.util import com.chrynan.sample.model.DiatonicScale import com.chrynan.sample.model.DiatonicScaleMode import com.chrynan.sample.model.ToneEqualNote val ToneEqualNote.Companion.A_FLAT get() = ToneEqualNote.G_SHARP val ToneEqualNote.Companion.B_FLAT get() = ToneEqualNote.A_SHARP val ToneEqualNote.Companion.D_FLAT get() = ToneEqualNote.C_SHARP val ToneEqualNote.Companion.E_FLAT get() = ToneEqualNote.D_SHARP val ToneEqualNote.Companion.G_FLAT get() = ToneEqualNote.F_SHARP fun ToneEqualNote.majorScale(): DiatonicScale = DiatonicScale(tonic = this, mode = DiatonicScaleMode.IONIAN) fun ToneEqualNote.relativeMinorScale(): DiatonicScale = DiatonicScale(tonic = this, mode = DiatonicScaleMode.AEOLIAN)
apache-2.0
2170f586bdf55be06f4bac128881da3f
30.416667
117
0.791501
3.78392
false
false
false
false
carlphilipp/chicago-commutes
android-app/src/main/kotlin/fr/cph/chicago/core/model/dto/EntityDTO.kt
1
4285
/** * Copyright 2021 Carl-Philipp Harmant * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * http://www.apache.org/licenses/LICENSE-2.0 * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package fr.cph.chicago.core.model.dto import android.util.ArrayMap import fr.cph.chicago.core.model.BikeStation import fr.cph.chicago.core.model.BusArrival import fr.cph.chicago.core.model.BusRoute import fr.cph.chicago.core.model.TrainArrival import java.util.TreeMap import org.apache.commons.lang3.StringUtils data class BaseDTO( val trainArrivalsDTO: TrainArrivalDTO, val busArrivalsDTO: BusArrivalDTO, val trainFavorites: List<String>, val busFavorites: List<String>, val busRouteFavorites: List<String>, val bikeFavorites: List<String> ) data class BusArrivalDTO(val busArrivals: List<BusArrival>, val error: Boolean) data class TrainArrivalDTO(val trainsArrivals: MutableMap<String, TrainArrival>, val error: Boolean) data class FirstLoadDTO( val busRoutesError: Boolean, val bikeStationsError: Boolean, val busRoutes: List<BusRoute>, val bikeStations: List<BikeStation>) data class FavoritesDTO( val trainArrivalDTO: TrainArrivalDTO, val busArrivalDTO: BusArrivalDTO, val bikeError: Boolean, val bikeStations: List<BikeStation>) data class BusFavoriteDTO(val routeId: String, val stopId: String, val bound: String) data class BusDetailsDTO( val busRouteId: String, val bound: String, val boundTitle: String, val stopId: Int, val routeName: String, val stopName: String ) // destination -> list of bus arrival class BusArrivalStopDTO(private val underlying: MutableMap<String, MutableList<BusArrival>> = ArrayMap()) : MutableMap<String, MutableList<BusArrival>> by underlying class BusArrivalStopMappedDTO(private val underlying: TreeMap<String, MutableMap<String, MutableSet<BusArrival>>> = TreeMap()) : MutableMap<String, MutableMap<String, MutableSet<BusArrival>>> by underlying { // stop name => { bound => BusArrival } fun addBusArrival(busArrival: BusArrival) { getOrPut(busArrival.stopName, { TreeMap() }) .getOrPut(busArrival.routeDirection, { mutableSetOf() }) .add(busArrival) } fun containsStopNameAndBound(stopName: String, bound: String): Boolean { return contains(stopName) && getValue(stopName).containsKey(bound) } } class BusArrivalRouteDTO( comparator: Comparator<String>, private val underlying: TreeMap<String, MutableMap<String, MutableSet<BusArrival>>> = TreeMap(comparator) ) : MutableMap<String, MutableMap<String, MutableSet<BusArrival>>> by underlying { // route => { bound => BusArrival } companion object { private val busRouteIdRegex = Regex("[^0-9]+") val busComparator: Comparator<String> = Comparator { key1: String, key2: String -> if (key1.matches(busRouteIdRegex) && key2.matches(busRouteIdRegex)) { key1.toInt().compareTo(key2.toInt()) } else { key1.replace(busRouteIdRegex, StringUtils.EMPTY).toInt().compareTo(key2.replace(busRouteIdRegex, StringUtils.EMPTY).toInt()) } } } fun addBusArrival(busArrival: BusArrival) { getOrPut(busArrival.routeId, { TreeMap() }) .getOrPut(busArrival.routeDirection, { mutableSetOf() }) .add(busArrival) } } data class RoutesAlertsDTO( val id: String, val routeName: String, val routeBackgroundColor: String, val routeTextColor: String, val routeStatus: String, val routeStatusColor: String, val alertType: AlertType ) enum class AlertType { TRAIN, BUS } data class RouteAlertsDTO( val id: String, val headLine: String, val description: String, val impact: String, val severityScore: Int, val start: String, val end: String )
apache-2.0
d157d0eaf90ee3fcb43cca7c514a8f12
31.709924
207
0.713419
4.302209
false
false
false
false
cliffano/swaggy-jenkins
clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/api/ApiApiController.kt
1
2873
package org.openapitools.api import org.openapitools.model.Hudson import io.swagger.v3.oas.annotations.* import io.swagger.v3.oas.annotations.enums.* import io.swagger.v3.oas.annotations.media.* import io.swagger.v3.oas.annotations.responses.* import io.swagger.v3.oas.annotations.security.* import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import org.springframework.validation.annotation.Validated import org.springframework.web.context.request.NativeWebRequest import org.springframework.beans.factory.annotation.Autowired import javax.validation.Valid import javax.validation.constraints.DecimalMax import javax.validation.constraints.DecimalMin import javax.validation.constraints.Email import javax.validation.constraints.Max import javax.validation.constraints.Min import javax.validation.constraints.NotNull import javax.validation.constraints.Pattern import javax.validation.constraints.Size import kotlin.collections.List import kotlin.collections.Map @RestController @Validated @RequestMapping("\${api.base-path:}") class ApiApiController() { @Operation( summary = "", operationId = "getJenkins", description = "Retrieve Jenkins details", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved Jenkins details", content = [Content(schema = Schema(implementation = Hudson::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/api/json"], produces = ["application/json"] ) fun getJenkins(): ResponseEntity<Hudson> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "headJenkins", description = "Retrieve Jenkins headers", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved Jenkins headers"), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.HEAD], value = ["/api/json"] ) fun headJenkins(): ResponseEntity<Unit> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } }
mit
35e02c44402dff82210daf105c484c4d
38.902778
172
0.726766
4.709836
false
false
false
false
gxwangdi/practice
android-dagger-master/app/src/main/java/com/example/android/dagger/login/LoginViewModel.kt
1
1538
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.dagger.login import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.example.android.dagger.user.UserManager import javax.inject.Inject /** * LoginViewModel is the ViewModel that [LoginActivity] uses to * obtain information of what to show on the screen and handle complex logic. */ class LoginViewModel @Inject constructor(private val userManager: UserManager) { private val _loginState = MutableLiveData<LoginViewState>() val loginState: LiveData<LoginViewState> get() = _loginState fun login(username: String, password: String) { if (userManager.loginUser(username, password)) { _loginState.value = LoginSuccess } else { _loginState.value = LoginError } } fun unregister() { userManager.unregister() } fun getUsername(): String = userManager.username }
gpl-2.0
00972544fdffca64031ab4f09af3dca0
31.723404
80
0.720416
4.523529
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/features/multiblocks/tileentities/Multiblocks.kt
2
2248
package com.cout970.magneticraft.features.multiblocks.tileentities import com.cout970.magneticraft.misc.RegisterTileEntity import com.cout970.magneticraft.misc.block.get import com.cout970.magneticraft.misc.vector.* import com.cout970.magneticraft.systems.multiblocks.Multiblock import com.cout970.magneticraft.systems.multiblocks.MultiblockContext import com.cout970.magneticraft.systems.tileentities.TileBase import com.cout970.magneticraft.systems.tilemodules.ModuleMultiblockCenter import com.cout970.magneticraft.systems.tilemodules.ModuleMultiblockGap import net.minecraft.util.EnumFacing import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.Vec3d import net.minecraft.util.text.ITextComponent import com.cout970.magneticraft.features.multiblocks.Blocks as Multiblocks /** * Created by cout970 on 2017/07/03. */ @RegisterTileEntity("multiblock_gap") class TileMultiblockGap : TileBase() { val multiblockModule = ModuleMultiblockGap() init { initModules(multiblockModule) } } abstract class TileMultiblock : TileBase() { val facing: EnumFacing get() = getBlockState()[Multiblocks.PROPERTY_MULTIBLOCK_ORIENTATION]?.facing ?: EnumFacing.NORTH val active: Boolean get() = getBlockState()[Multiblocks.PROPERTY_MULTIBLOCK_ORIENTATION]?.active ?: false var clientErrors: List<ITextComponent> = emptyList() abstract fun getMultiblock(): Multiblock @Suppress("LeakingThis") abstract val multiblockModule: ModuleMultiblockCenter override fun shouldRenderInPass(pass: Int): Boolean { return if (active) super.shouldRenderInPass(pass) else pass == 1 } override fun getRenderBoundingBox(): AxisAlignedBB { val size = getMultiblock().size.toVec3d() val center = getMultiblock().center.toVec3d() val box = Vec3d.ZERO createAABBUsing size val boxWithOffset = box.offset(-center) val normalizedBox = EnumFacing.SOUTH.rotateBox(vec3Of(0.5), boxWithOffset) val alignedBox = facing.rotateBox(vec3Of(0.5), normalizedBox) return alignedBox.offset(pos) } fun multiblockContext(): MultiblockContext { return MultiblockContext(getMultiblock(), world, pos, facing, null) } }
gpl-2.0
50b90fb9addaa86cd9e44ef363a44010
35.274194
104
0.761121
4.314779
false
false
false
false
xfournet/intellij-community
python/src/com/jetbrains/python/codeInsight/typing/PyProtocols.kt
1
2900
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.codeInsight.typing import com.intellij.openapi.util.io.FileUtil import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider.PROTOCOL import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider.PROTOCOL_EXT import com.jetbrains.python.psi.AccessDirection import com.jetbrains.python.psi.PyClass import com.jetbrains.python.psi.PyTypedElement import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.resolve.RatedResolveResult import com.jetbrains.python.psi.types.PyClassLikeType import com.jetbrains.python.psi.types.PyClassType import com.jetbrains.python.psi.types.PyType import com.jetbrains.python.psi.types.TypeEvalContext fun isProtocol(classLikeType: PyClassLikeType, context: TypeEvalContext) = containsProtocol(classLikeType.getSuperClassTypes(context)) fun isProtocol(cls: PyClass, context: TypeEvalContext) = containsProtocol(cls.getSuperClassTypes(context)) fun matchingProtocolDefinitions(expected: PyType?, actual: PyType?, context: TypeEvalContext) = expected is PyClassLikeType && actual is PyClassLikeType && expected.isDefinition && actual.isDefinition && isProtocol(expected, context) && isProtocol(actual, context) typealias ProtocolAndSubclassElements = Pair<PyTypedElement, List<RatedResolveResult>?> fun inspectProtocolSubclass(protocol: PyClassType, subclass: PyClassType, context: TypeEvalContext): List<ProtocolAndSubclassElements> { val subclassAsInstance = subclass.toInstance() val resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(context) val result = mutableListOf<Pair<PyTypedElement, List<RatedResolveResult>?>>() protocol.toInstance().visitMembers( { e -> if (e is PyTypedElement && FileUtil.getNameWithoutExtension(e.containingFile.name) != "typing_extensions") { val name = e.name ?: return@visitMembers true val resolveResults = subclassAsInstance.resolveMember(name, null, AccessDirection.READ, resolveContext) result.add(Pair(e, resolveResults)) } true }, true, context ) return result } private fun containsProtocol(types: List<PyClassLikeType?>) = types.any { type -> val classQName = type?.classQName PROTOCOL == classQName || PROTOCOL_EXT == classQName }
apache-2.0
24747f2c7a7a1ea0c324f0c9595f976c
49.894737
140
0.664483
5.380334
false
false
false
false
corenting/EDCompanion
app/src/main/java/fr/corenting/edcompanion/views/DelayAutoCompleteTextView.kt
1
1895
package fr.corenting.edcompanion.views import android.content.Context import android.os.Handler import android.os.Looper import android.os.Message import android.text.InputType import android.util.AttributeSet import android.view.KeyEvent import android.view.inputmethod.EditorInfo import android.widget.TextView import androidx.appcompat.widget.AppCompatAutoCompleteTextView // Code from http://makovkastar.github.io/blog/2014/04/12/android-autocompletetextview-with-suggestions-from-a-web-service/ class DelayAutoCompleteTextView(context: Context, attrs: AttributeSet) : AppCompatAutoCompleteTextView(context, attrs) { private val mHandler: Handler = AutoCompleteHandler(this) init { this.inputType = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS this.imeOptions = EditorInfo.IME_ACTION_DONE } private fun performFiltering(msg: Message) { super.performFiltering(msg.obj as CharSequence, msg.arg1) } fun setOnSubmit(onSubmit: Runnable) { setOnEditorActionListener { _: TextView?, i: Int, _: KeyEvent? -> if (i == EditorInfo.IME_ACTION_DONE) { onSubmit.run() return@setOnEditorActionListener true } false } } override fun performFiltering(text: CharSequence, keyCode: Int) { mHandler.removeMessages(MESSAGE_TEXT_CHANGED) mHandler.sendMessageDelayed(mHandler.obtainMessage(MESSAGE_TEXT_CHANGED, text), DEFAULT_AUTOCOMPLETE_DELAY.toLong()) } private class AutoCompleteHandler(private val view: DelayAutoCompleteTextView) : Handler(Looper.getMainLooper()) { override fun handleMessage(msg: Message) { view.performFiltering(msg) } } companion object { private const val MESSAGE_TEXT_CHANGED = 100 private const val DEFAULT_AUTOCOMPLETE_DELAY = 250 } }
mit
1f5efd935ac1e68359234107ae782d50
32.857143
123
0.707652
4.633252
false
false
false
false
mrkirby153/KirBot
src/main/kotlin/me/mrkirby153/KirBot/utils/KUtils.kt
1
8453
package me.mrkirby153.KirBot.utils import me.mrkirby153.KirBot.Bot import me.mrkirby153.KirBot.listener.WaitUtils import me.mrkirby153.KirBot.module.ModuleManager import me.mrkirby153.KirBot.modules.Redis import me.mrkirby153.kcutils.Time import me.xdrop.fuzzywuzzy.FuzzySearch import net.dv8tion.jda.api.entities.Message import net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent import net.dv8tion.jda.api.sharding.ShardManager import okhttp3.Request import java.awt.Color import java.awt.image.BufferedImage import java.util.Calendar import java.util.Date import java.util.UUID import java.util.concurrent.CompletableFuture import javax.imageio.ImageIO /** * Uploads a string to the bot archive * * @param text The text to upload to the archive * @param ttl The time (in seconds) that the archive should exist for * * @return A URL to the archive */ fun uploadToArchive(text: String, ttl: Int = 604800): String { Bot.applicationContext.get(Redis::class.java).getConnection().use { val key = UUID.randomUUID().toString() Bot.LOG.debug("Archive created $key (Expires in ${Time.formatLong(ttl * 1000L, Time.TimeUnit.SECONDS).toLowerCase()})") it.set("archive:$key", text) it.expire("archive:$key", ttl) return String.format(Bot.properties.getProperty("archive-base"), key) } } /** * Prompt the user for confirmation before performing an action * * @param context The context * @param msg The message to send to the user * @param onConfirm The action to run when confirmed * @param onDeny The action to run when denied */ @Deprecated("Use WaitUtils.confirmYesNo") fun promptForConfirmation(context: Context, msg: String, onConfirm: (() -> Boolean)? = null, onDeny: (() -> Boolean)? = null) { context.channel.sendMessage(msg).queue { m -> m.addReaction(GREEN_TICK.emote!!).queue() m.addReaction(RED_TICK.emote!!).queue() WaitUtils.waitFor(MessageReactionAddEvent::class.java) { if (it.user?.id != context.author.id) return@waitFor if (it.messageId != m.id) return@waitFor if (it.reactionEmote.isEmote) { when (it.reactionEmote.id) { GREEN_TICK.id -> { if (onConfirm == null || onConfirm.invoke()) m.delete().queue() cancel() } RED_TICK.id -> { if (onDeny == null || onDeny.invoke()) m.delete().queue() cancel() } } } } } } /** * Converts a snowflake to a [Date] * * @param snowflake The snowflake to convert * * @return The [Date] */ fun convertSnowflake(snowflake: String): Date { val s = snowflake.toLong() val time = s.shr(22) val calendar = Calendar.getInstance() calendar.timeInMillis = time + 1420070400000 return calendar.time } fun toSnowflake(date: Date): String { return (date.toInstant().toEpochMilli() - 1420070400000).shl(22).toString() } infix fun Any.botUrl(url: String): String { return Bot.constants.getProperty("bot-base-url") + "/" + url } /** * Fuzzy matches an item out of a list given a query string * * @param items The list of items to search * @param query The query string to search for in the item * @param mapper A function that maps the items to strings * @param ratio The ratio that the items must match the query string * @param minDifference The minimum difference in ratios between the first and second candidate (if any) * * @throws FuzzyMatchException.TooManyMatchesException If more than one item is candidate for the string * @throws FuzzyMatchException.NoMatchesException If no items match the query string * * @return The item that most closely matches the query string */ fun <T> fuzzyMatch(items: List<T>, query: String, mapper: (T) -> String = { it.toString() }, ratio: Int = 40, minDifference: Int = 20): T { val exactMatches = items.filter { i -> mapper.invoke(i) == query } if (exactMatches.isNotEmpty()) { if (exactMatches.size > 1) throw FuzzyMatchException.TooManyMatchesException() return exactMatches.first() } else { val fuzzyRated = mutableMapOf<T, Int>() items.forEach { i -> fuzzyRated[i] = FuzzySearch.partialRatio(query, mapper.invoke(i)) } val matches = fuzzyRated.entries.sortedBy { it.value }.reversed().filter { it.value > ratio } if (matches.isEmpty()) throw FuzzyMatchException.NoMatchesException() val first = matches.first() return when { // Only 1 item matched the criteria matches.size == 1 -> first.key // The 2nd item has a ratio that is less than the minDifference first.value - matches[1].value > minDifference -> first.key // We've failed the previous two conditions, we can't determine the role else -> throw FuzzyMatchException.TooManyMatchesException() } } } /** * Gets the primary color in an image * * @param url The url * @return The primary color */ fun getPrimaryColor(url: String): Color { val req = Request.Builder().url(url).build() val resp = HttpUtils.CLIENT.newCall(req).execute() if (resp.code() != 200) throw IllegalArgumentException("Received non-success response code ${resp.code()}") val img = ImageIO.read(resp.body()!!.byteStream()) return getPrimaryColor(img) } /** * Gets the primary color in an image * * @param image The imag * @return The primary color */ fun getPrimaryColor(image: BufferedImage): Color { val freq = mutableMapOf<Int, Int>() for (x in 0 until image.width) { for (y in 0 until image.height) { val f = freq[image.getRGB(x, y)] ?: 0 freq[image.getRGB(x, y)] = f + 1 } } var max = freq.entries.first().key var cnt = freq.entries.first().value freq.forEach { k, v -> if (v > cnt) { max = k cnt = v } } return Color(max) } /** * Finds a message from the given search string */ fun findMessage(string: String): CompletableFuture<Message> { val cf = CompletableFuture<Message>() val jumpRegex = Regex( "https://(?>(?>canary|ptb)\\.)?discordapp\\.com/channels/(\\d+)/(\\d+)/(\\d+)") if (string.matches(jumpRegex)) { val match = jumpRegex.find(string)?.groups ?: return CompletableFuture.failedFuture( NoSuchElementException("Message not found")) val guildId = match[1]!! val channelId = match[2]!! val messageId = match[3]!! val guild = Bot.applicationContext.get(ShardManager::class.java).getGuildById(guildId.value) val channel = guild?.getTextChannelById(channelId.value) if (guild == null || channel == null) { return CompletableFuture.failedFuture(NoSuchElementException("Message not found")) } channel.retrieveMessageById(messageId.value).queue({ cf.complete(it) }, { cf.completeExceptionally(it) }) } else { Bot.scheduler.submit { Bot.applicationContext.get(ShardManager::class.java).guilds.forEach guilds@{ guild -> guild.textChannels.forEach channels@{ chan -> try { val msg = chan.retrieveMessageById(string).complete() if (msg != null) { cf.complete(msg) return@guilds } } catch (e: Exception) { // Ignore } } } cf.completeExceptionally(NoSuchElementException("Message not found")) } } return cf } /** * An exception thrown when an error occurs when [Matching Strings][fuzzyMatch] */ open class FuzzyMatchException : Exception() { /** * An exception thrown when too many items match the given query string */ class TooManyMatchesException : FuzzyMatchException() /** * An exception thrown when no items match the given query */ class NoMatchesException : FuzzyMatchException() }
mit
2a3fe5e0fe2817f371d29c2678e73eca
33.790123
104
0.614102
4.334872
false
false
false
false
AllanWang/Frost-for-Facebook
app/src/main/kotlin/com/pitchedapps/frost/services/NotificationUtils.kt
1
5836
/* * Copyright 2018 Allan Wang * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.pitchedapps.frost.services import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.job.JobInfo import android.app.job.JobScheduler import android.app.job.JobService import android.content.ComponentName import android.content.Context import android.os.Build import android.os.PersistableBundle import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import ca.allanwang.kau.utils.color import ca.allanwang.kau.utils.string import com.pitchedapps.frost.R import com.pitchedapps.frost.injectors.ThemeProvider import com.pitchedapps.frost.prefs.Prefs import com.pitchedapps.frost.utils.L import com.pitchedapps.frost.utils.frostUri /** Created by Allan Wang on 07/04/18. */ const val NOTIF_CHANNEL_GENERAL = "general" const val NOTIF_CHANNEL_MESSAGES = "messages" fun setupNotificationChannels(c: Context, themeProvider: ThemeProvider) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return val manager = c.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val appName = c.string(R.string.frost_name) val msg = c.string(R.string.messages) manager.createNotificationChannel(NOTIF_CHANNEL_GENERAL, appName, themeProvider) manager.createNotificationChannel(NOTIF_CHANNEL_MESSAGES, "$appName: $msg", themeProvider) manager.notificationChannels .filter { it.id != NOTIF_CHANNEL_GENERAL && it.id != NOTIF_CHANNEL_MESSAGES } .forEach { manager.deleteNotificationChannel(it.id) } L.d { "Created notification channels: ${manager.notificationChannels.size} channels, ${manager.notificationChannelGroups.size} groups" } } @RequiresApi(Build.VERSION_CODES.O) private fun NotificationManager.createNotificationChannel( id: String, name: String, themeProvider: ThemeProvider ): NotificationChannel { val channel = NotificationChannel(id, name, NotificationManager.IMPORTANCE_DEFAULT) channel.enableLights(true) channel.lightColor = themeProvider.accentColor channel.lockscreenVisibility = Notification.VISIBILITY_PUBLIC createNotificationChannel(channel) return channel } fun Context.frostNotification(id: String) = NotificationCompat.Builder(this, id).apply { setSmallIcon(R.drawable.frost_f_24) setAutoCancel(true) setOnlyAlertOnce(true) setStyle(NotificationCompat.BigTextStyle()) color = color(R.color.frost_notification_accent) } /** * Dictates whether a notification should have sound/vibration/lights or not Delegates to channels * if Android O and up Otherwise uses our provided preferences */ fun NotificationCompat.Builder.setFrostAlert( context: Context, enable: Boolean, ringtone: String, prefs: Prefs ): NotificationCompat.Builder { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { setGroupAlertBehavior( if (enable) NotificationCompat.GROUP_ALERT_CHILDREN else NotificationCompat.GROUP_ALERT_SUMMARY ) } else if (!enable) { setDefaults(0) } else { var defaults = 0 if (prefs.notificationVibrate) defaults = defaults or Notification.DEFAULT_VIBRATE if (prefs.notificationSound) { if (ringtone.isNotBlank()) setSound(context.frostUri(ringtone)) else defaults = defaults or Notification.DEFAULT_SOUND } if (prefs.notificationLights) defaults = defaults or Notification.DEFAULT_LIGHTS setDefaults(defaults) } return this } /* * ----------------------------------- * Job Scheduler * ----------------------------------- */ const val NOTIFICATION_PARAM_ID = "notif_param_id" fun JobInfo.Builder.setExtras(id: Int): JobInfo.Builder { val bundle = PersistableBundle() bundle.putInt(NOTIFICATION_PARAM_ID, id) return setExtras(bundle) } /** * interval is # of min, which must be at least 15 returns false if an error occurs; true otherwise */ inline fun <reified T : JobService> Context.scheduleJob(id: Int, minutes: Long): Boolean { val scheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler scheduler.cancel(id) if (minutes < 0L) return true val serviceComponent = ComponentName(this, T::class.java) val builder = JobInfo.Builder(id, serviceComponent) .setPeriodic(minutes * 60000) .setExtras(id) .setPersisted(true) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) // TODO add options val result = scheduler.schedule(builder.build()) if (result <= 0) { L.eThrow("${T::class.java.simpleName} scheduler failed") return false } return true } /** Run notification job right now */ inline fun <reified T : JobService> Context.fetchJob(id: Int): Boolean { val scheduler = getSystemService(Context.JOB_SCHEDULER_SERVICE) as JobScheduler val serviceComponent = ComponentName(this, T::class.java) val builder = JobInfo.Builder(id, serviceComponent) .setMinimumLatency(0L) .setExtras(id) .setOverrideDeadline(2000L) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) val result = scheduler.schedule(builder.build()) if (result <= 0) { L.eThrow("${T::class.java.simpleName} instant scheduler failed") return false } return true }
gpl-3.0
4624d2ae096c12452e88237b481f5a5d
34.803681
132
0.747087
4.177523
false
false
false
false
beyama/winter
winter/src/main/kotlin/io/jentz/winter/common.kt
1
2383
package io.jentz.winter import io.jentz.winter.inject.ApplicationScope internal val UNINITIALIZED_VALUE = Any() /** * Factory function signature with [Graph] as receiver. */ typealias GFactory<R> = Graph.() -> R /** * Factory callback function signature with [Graph] as receiver. * Used for onPostConstruct and onClose callbacks. */ typealias GFactoryCallback<R> = Graph.(R) -> Unit /** * Function signature alias for component builder DSL blocks. */ typealias ComponentBuilderBlock = Component.Builder.() -> Unit /** * Provider function signature. */ typealias Provider<R> = () -> R internal typealias OnCloseCallback = (Graph) -> Unit /** * Key used to store a set of dependency keys of eager dependencies in the dependency map. */ internal val eagerDependenciesKey = typeKey<Set<TypeKey<Any>>>("EAGER_DEPENDENCIES") /** * Returns a [Component] without qualifier and without any declared dependencies. */ fun emptyComponent(): Component = Component.EMPTY /** * Returns a [Graph] with empty component. */ fun emptyGraph(): Graph = Component.EMPTY.createGraph() /** * Create an instance of [Component]. * * @param qualifier A qualifier for the component. * @param block A builder block to register provider on the component. * @return A instance of component containing all provider defined in the builder block. */ fun component( qualifier: Any = ApplicationScope::class, block: ComponentBuilderBlock ): Component = Component.Builder(qualifier).apply(block).build() /** * Create an ad-hoc instance of [Graph]. * * @param qualifier A qualifier for the backing component. * @param block A builder block to register provider on the backing component. * @return A instance of component containing all provider defined in the builder block. */ fun graph(qualifier: Any = ApplicationScope::class, block: ComponentBuilderBlock): Graph = component(qualifier, block).createGraph() /** * Returns [TypeKey] for type [R]. * * @param qualifier An optional qualifier for this key. * @param generics If true this creates a type key that also takes generic type parameters into * account. */ inline fun <reified R : Any> typeKey( qualifier: Any? = null, generics: Boolean = false ): TypeKey<R> = if (generics) { object : GenericClassTypeKey<R>(qualifier) {} } else { ClassTypeKey(R::class.java, qualifier) }
apache-2.0
0f47fe78601a8f74dfff7c00a390d0c2
28.419753
95
0.720101
4.240214
false
false
false
false
rustamgaifullin/TranslateIt
api/src/main/kotlin/com/rm/translateit/api/translation/source/babla/BablaInterceptor.kt
1
492
package com.rm.translateit.api.translation.source.babla import okhttp3.Interceptor import okhttp3.Response internal class BablaInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val originalResponse: Response = chain.proceed(chain.request()) var newResponse = originalResponse if (originalResponse.code == 301) { newResponse = originalResponse.newBuilder() .code(200) .build() } return newResponse } }
mit
9a8bf548b32df6839bab59c053bc6fc6
26.388889
67
0.719512
4.598131
false
false
false
false
rock3r/detekt
detekt-cli/src/main/kotlin/io/gitlab/arturbosch/detekt/cli/Configurations.kt
1
3657
package io.gitlab.arturbosch.detekt.cli import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.commaSeparatedPattern import io.gitlab.arturbosch.detekt.api.internal.CompositeConfig import io.gitlab.arturbosch.detekt.api.internal.DisabledAutoCorrectConfig import io.gitlab.arturbosch.detekt.api.internal.FailFastConfig import io.gitlab.arturbosch.detekt.api.internal.PathFilters import io.gitlab.arturbosch.detekt.api.internal.YamlConfig import java.net.URI import java.net.URL import java.nio.file.FileSystemNotFoundException import java.nio.file.FileSystems import java.nio.file.Path fun CliArgs.createFilters(): PathFilters? = PathFilters.of( (includes ?: "") .trim() .commaSeparatedPattern(",", ";") .toList(), (excludes ?: "") .trim() .commaSeparatedPattern(",", ";") .toList()) fun CliArgs.createPlugins(): List<Path> = plugins.letIfNonEmpty { MultipleExistingPathConverter().convert(this) } fun CliArgs.createClasspath(): List<String> = classpath.letIfNonEmpty { split(";") } private fun <T> String?.letIfNonEmpty(init: String.() -> List<T>): List<T> = if (this == null || this.isEmpty()) listOf() else this.init() @Suppress("UnsafeCallOnNullableType") fun CliArgs.loadConfiguration(): Config { var declaredConfig: Config? = when { !config.isNullOrBlank() -> parsePathConfig(config!!) !configResource.isNullOrBlank() -> parseResourceConfig(configResource!!) else -> null } var defaultConfig: Config? = null if (buildUponDefaultConfig) { defaultConfig = loadDefaultConfig() declaredConfig = CompositeConfig(declaredConfig ?: defaultConfig, defaultConfig) } if (failFast) { val initializedDefaultConfig = defaultConfig ?: loadDefaultConfig() declaredConfig = FailFastConfig(declaredConfig ?: initializedDefaultConfig, initializedDefaultConfig) } if (!autoCorrect) { declaredConfig = DisabledAutoCorrectConfig(declaredConfig ?: loadDefaultConfig()) } return declaredConfig ?: loadDefaultConfig() } private fun parseResourceConfig(configPath: String): Config { val urls = MultipleClasspathResourceConverter().convert(configPath) return if (urls.size == 1) { YamlConfig.loadResource(urls[0]) } else { urls.asSequence() .map { YamlConfig.loadResource(it) } .reduce { composite, config -> CompositeConfig(config, composite) } } } private fun parsePathConfig(configPath: String): Config { val paths = MultipleExistingPathConverter().convert(configPath) return if (paths.size == 1) { YamlConfig.load(paths[0]) } else { paths.asSequence() .map { YamlConfig.load(it) } .reduce { composite, config -> CompositeConfig(config, composite) } } } const val DEFAULT_CONFIG = "default-detekt-config.yml" fun loadDefaultConfig() = YamlConfig.loadResource(ClasspathResourceConverter().convert(DEFAULT_CONFIG)) private fun initFileSystem(uri: URI) { runCatching { try { FileSystems.getFileSystem(uri) } catch (e: FileSystemNotFoundException) { FileSystems.newFileSystem(uri, mapOf("create" to "true")) } } } fun CliArgs.extractUris(): Collection<URI> { val pathUris = config?.let { MultipleExistingPathConverter().convert(it).map(Path::toUri) } ?: emptyList() val resourceUris = configResource?.let { MultipleClasspathResourceConverter().convert(it).map(URL::toURI) } ?: emptyList() resourceUris.forEach(::initFileSystem) return resourceUris + pathUris }
apache-2.0
7b25902084f96538444867487bd40da5
34.163462
111
0.696746
4.520396
false
true
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/multimediacard/AudioView.kt
1
13517
/* * Copyright (c) 2013 Bibek Shrestha <[email protected]> * Copyright (c) 2013 Zaur Molotnikov <[email protected]> * Copyright (c) 2013 Nicolas Raoul <[email protected]> * Copyright (c) 2013 Flavio Lerda <[email protected]> * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ package com.ichi2.anki.multimediacard import android.annotation.SuppressLint import android.content.Context import android.view.Gravity import android.view.View import android.view.View.OnClickListener import android.widget.LinearLayout import androidx.annotation.VisibleForTesting import androidx.appcompat.widget.AppCompatImageButton import com.ichi2.anki.CrashReportService import com.ichi2.anki.R import com.ichi2.anki.UIUtils.showThemedToast import com.ichi2.utils.Permissions.canRecordAudio import timber.log.Timber import java.io.File import java.io.IOException // Not designed for visual editing @SuppressLint("ViewConstructor") class AudioView private constructor(context: Context, resPlay: Int, resPause: Int, resStop: Int, audioPath: String) : LinearLayout(context) { val audioPath: String? protected var playPause: PlayPauseButton? protected var stop: StopButton? protected var record: RecordButton? = null private var mAudioRecorder = AudioRecorder() private var mPlayer = AudioPlayer() private var mOnRecordingFinishEventListener: OnRecordingFinishEventListener? = null @get:VisibleForTesting(otherwise = VisibleForTesting.NONE) var status = Status.IDLE private set private val mResPlayImage: Int private val mResPauseImage: Int private val mResStopImage: Int private var mResRecordImage = 0 private var mResRecordStopImage = 0 private val mContext: Context @VisibleForTesting(otherwise = VisibleForTesting.PACKAGE_PRIVATE) enum class Status { IDLE, // Default initial state INITIALIZED, // When datasource has been set PLAYING, PAUSED, STOPPED, // The different possible states once playing // has started RECORDING // The recorder being played status } private fun gtxt(id: Int): String { return mContext.getText(id).toString() } private constructor( context: Context, resPlay: Int, resPause: Int, resStop: Int, resRecord: Int, resRecordStop: Int, audioPath: String ) : this(context, resPlay, resPause, resStop, audioPath) { mResRecordImage = resRecord mResRecordStopImage = resRecordStop this.orientation = HORIZONTAL this.gravity = Gravity.CENTER record = RecordButton(context) addView(record, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)) } fun setOnRecordingFinishEventListener(listener: OnRecordingFinishEventListener?) { mOnRecordingFinishEventListener = listener } fun notifyPlay() { playPause!!.update() stop!!.update() if (record != null) { record!!.update() } } fun notifyStop() { // Send state change signal to all buttons playPause!!.update() stop!!.update() if (record != null) { record!!.update() } } fun notifyPause() { playPause!!.update() stop!!.update() if (record != null) { record!!.update() } } fun notifyRecord() { playPause!!.update() stop!!.update() if (record != null) { record!!.update() } } fun notifyStopRecord() { if (status == Status.RECORDING) { try { mAudioRecorder.stopRecording() } catch (e: RuntimeException) { Timber.i(e, "Recording stop failed, this happens if stop was hit immediately after start") showThemedToast(mContext, gtxt(R.string.multimedia_editor_audio_view_recording_failed), true) } status = Status.IDLE if (mOnRecordingFinishEventListener != null) { mOnRecordingFinishEventListener!!.onRecordingFinish(this@AudioView) } } playPause!!.update() stop!!.update() if (record != null) { record!!.update() } } fun notifyReleaseRecorder() { mAudioRecorder.release() } /** Stops playing and records */ fun toggleRecord() { stopPlaying() if (record != null) { record!!.callOnClick() } } /** Stops recording and presses the play button */ fun togglePlay() { // cancelling recording is done via pressing the record button again stopRecording() if (playPause != null) { playPause!!.callOnClick() } } /** If recording is occurring, stop it */ private fun stopRecording() { if (status == Status.RECORDING && record != null) { record!!.callOnClick() } } /** If playing, stop it */ protected fun stopPlaying() { // The stop button only applies to the player, and does nothing if no action is needed if (stop != null) { stop!!.callOnClick() } } protected inner class PlayPauseButton(context: Context?) : AppCompatImageButton(context!!) { private val mOnClickListener: OnClickListener = object : OnClickListener { override fun onClick(v: View) { if (audioPath == null) { return } when (status) { Status.IDLE -> try { mPlayer.play(audioPath) setImageResource(mResPauseImage) status = Status.PLAYING notifyPlay() } catch (e: Exception) { Timber.e(e) showThemedToast(mContext, gtxt(R.string.multimedia_editor_audio_view_playing_failed), true) status = Status.IDLE } Status.PAUSED -> { // -> Play, continue playing status = Status.PLAYING setImageResource(mResPauseImage) mPlayer.start() notifyPlay() } Status.STOPPED -> { // -> Play, start from beginning status = Status.PLAYING setImageResource(mResPauseImage) mPlayer.stop() mPlayer.start() notifyPlay() } Status.PLAYING -> { setImageResource(mResPlayImage) mPlayer.pause() status = Status.PAUSED notifyPause() } Status.RECORDING -> { } else -> { } } } } fun update() { isEnabled = when (status) { Status.IDLE, Status.STOPPED -> { setImageResource(mResPlayImage) true } Status.RECORDING -> false else -> true } } init { setImageResource(mResPlayImage) setOnClickListener(mOnClickListener) } } protected inner class StopButton(context: Context?) : AppCompatImageButton(context!!) { private val mOnClickListener = OnClickListener { when (status) { Status.PAUSED, Status.PLAYING -> { mPlayer.stop() status = Status.STOPPED notifyStop() } Status.IDLE, Status.STOPPED, Status.RECORDING, Status.INITIALIZED -> { } } } fun update() { isEnabled = status != Status.RECORDING // It doesn't need to update itself on any other state changes } init { setImageResource(mResStopImage) setOnClickListener(mOnClickListener) } } protected inner class RecordButton(context: Context?) : AppCompatImageButton(context!!) { private val mOnClickListener: OnClickListener = object : OnClickListener { override fun onClick(v: View) { // Since mAudioPath is not compulsory, we check if it exists if (audioPath == null) { return } // We can get to this screen without permissions through the "Pronunciation" feature. if (!canRecordAudio(mContext)) { Timber.w("Audio recording permission denied.") showThemedToast( mContext, resources.getString(R.string.multimedia_editor_audio_permission_denied), true ) return } when (status) { Status.IDLE, Status.STOPPED -> { try { mAudioRecorder.startRecording(mContext, audioPath) } catch (e: Exception) { // either output file failed or codec didn't work, in any case fail out Timber.e("RecordButton.onClick() :: error recording to %s\n%s", audioPath, e.message) showThemedToast(mContext, gtxt(R.string.multimedia_editor_audio_view_recording_failed), true) status = Status.STOPPED } status = Status.RECORDING setImageResource(mResRecordImage) notifyRecord() } Status.RECORDING -> { setImageResource(mResRecordStopImage) notifyStopRecord() } else -> { } } } } fun update() { isEnabled = when (status) { Status.PLAYING, Status.PAUSED -> false else -> true } } init { setImageResource(mResRecordStopImage) setOnClickListener(mOnClickListener) } } interface OnRecordingFinishEventListener { fun onRecordingFinish(v: View) } @VisibleForTesting(otherwise = VisibleForTesting.NONE) fun setRecorder(recorder: AudioRecorder) { mAudioRecorder = recorder } @VisibleForTesting(otherwise = VisibleForTesting.NONE) fun setPlayer(player: AudioPlayer) { mPlayer = player } companion object { fun createRecorderInstance( context: Context, resPlay: Int, resPause: Int, resStop: Int, resRecord: Int, resRecordStop: Int, audioPath: String ): AudioView? { return try { AudioView(context, resPlay, resPause, resStop, resRecord, resRecordStop, audioPath) } catch (e: Exception) { Timber.e(e) CrashReportService.sendExceptionReport(e, "Unable to create recorder tool bar") showThemedToast( context, context.getText(R.string.multimedia_editor_audio_view_create_failed).toString(), true ) null } } fun generateTempAudioFile(context: Context): String? { val tempAudioPath: String? tempAudioPath = try { val storingDirectory = context.cacheDir File.createTempFile("ankidroid_audiorec", ".3gp", storingDirectory).absolutePath } catch (e: IOException) { Timber.e(e, "Could not create temporary audio file.") null } return tempAudioPath } } init { mPlayer.onStoppingListener = { status = Status.STOPPED } mPlayer.onStoppedListener = { notifyStop() } mAudioRecorder.setOnRecordingInitializedHandler { status = Status.INITIALIZED } mContext = context mResPlayImage = resPlay mResPauseImage = resPause mResStopImage = resStop this.audioPath = audioPath this.orientation = HORIZONTAL playPause = PlayPauseButton(context) addView(playPause, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)) stop = StopButton(context) addView(stop, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)) } }
gpl-3.0
b8fde406329fd64c960486e287bac0c7
33.748072
141
0.553377
5.408964
false
false
false
false
akvo/akvo-flow-mobile
domain/src/main/java/org/akvo/flow/domain/interactor/datapoints/DownloadMedia.kt
1
2507
/* * Copyright (C) 2020 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo Flow. * * Akvo Flow 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. * * Akvo Flow 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 Akvo Flow. If not, see <http://www.gnu.org/licenses/>. */ package org.akvo.flow.domain.interactor.datapoints import io.reactivex.Completable import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import io.reactivex.observers.DisposableCompletableObserver import io.reactivex.schedulers.Schedulers import org.akvo.flow.domain.executor.PostExecutionThread import org.akvo.flow.domain.executor.ThreadExecutor import org.akvo.flow.domain.repository.DataPointRepository import javax.inject.Inject class DownloadMedia @Inject constructor( private val dataPointRepository: DataPointRepository, private val threadExecutor: ThreadExecutor, private val postExecutionThread: PostExecutionThread ) { private val disposables = CompositeDisposable() fun execute(observer: DisposableCompletableObserver, parameters: Map<String?, Any>?) { val observable: Completable = buildUseCaseObservable(parameters) .subscribeOn(Schedulers.from(threadExecutor)) .observeOn(postExecutionThread.scheduler) addDisposable(observable.subscribeWith(observer)) } fun dispose() { if (!disposables.isDisposed) { disposables.clear() } } private fun <T> buildUseCaseObservable(parameters: Map<String?, T>?): Completable { if (parameters == null || !parameters.containsKey(PARAM_FILE_PATH)) { return Completable.error(IllegalArgumentException("Missing file name")) } val filePath = parameters[PARAM_FILE_PATH] as String return dataPointRepository.cleanPathAndDownLoadMedia(filePath) } private fun addDisposable(disposable: Disposable) { disposables.add(disposable) } companion object { const val PARAM_FILE_PATH = "file_path" } }
gpl-3.0
cf4093c32d4e25675bbf938e60ac64c8
35.333333
90
0.737934
4.73913
false
false
false
false
openMF/self-service-app
app/src/main/java/org/mifos/mobile/models/accounts/loan/InterestRecalculationData.kt
1
1474
package org.mifos.mobile.models.accounts.loan import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize import org.mifos.mobile.models.accounts.loan.calendardata.CalendarData /** * Created by Rajan Maurya on 04/03/17. */ @Parcelize data class InterestRecalculationData( @SerializedName("id") var id: Int? = null, @SerializedName("loanId") var loanId: Int? = null, @SerializedName("interestRecalculationCompoundingType") var interestRecalculationCompoundingType: InterestRecalculationCompoundingType, @SerializedName("rescheduleStrategyType") var rescheduleStrategyType: RescheduleStrategyType, @SerializedName("calendarData") var calendarData: CalendarData, @SerializedName("recalculationRestFrequencyType") var recalculationRestFrequencyType: RecalculationRestFrequencyType, @SerializedName("recalculationRestFrequencyInterval") var recalculationRestFrequencyInterval: Double? = null, @SerializedName("recalculationCompoundingFrequencyType") var recalculationCompoundingFrequencyType: RecalculationCompoundingFrequencyType, @SerializedName("isCompoundingToBePostedAsTransaction") var compoundingToBePostedAsTransaction: Boolean? = null, @SerializedName("allowCompoundingOnEod") var allowCompoundingOnEod: Boolean? = null ) : Parcelable
mpl-2.0
9d6b823c06915a7db038e4c014159e8b
31.065217
89
0.752374
5.135889
false
false
false
false
sabi0/intellij-community
plugins/gradle/java/src/action/ImportProjectFromScriptAction.kt
1
1928
// 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.plugins.gradle.action import com.intellij.ide.actions.ImportModuleAction.createFromWizard import com.intellij.ide.actions.ImportModuleAction.createImportWizard import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.externalSystem.action.ExternalSystemAction import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.projectImport.ProjectImportProvider import org.jetbrains.plugins.gradle.settings.GradleSettings import org.jetbrains.plugins.gradle.util.GradleConstants class ImportProjectFromScriptAction: ExternalSystemAction() { override fun isEnabled(e: AnActionEvent?): Boolean = true override fun isVisible(e: AnActionEvent?): Boolean { if (e == null) { return false } val virtualFile = e.getData<VirtualFile>(CommonDataKeys.VIRTUAL_FILE) ?: return false val project = e.getData<Project>(CommonDataKeys.PROJECT) ?: return false if (virtualFile.name != GradleConstants.DEFAULT_SCRIPT_NAME && virtualFile.name != GradleConstants.KOTLIN_DSL_SCRIPT_NAME) { return false } return GradleSettings.getInstance(project).getLinkedProjectSettings(virtualFile.parent.path) == null } override fun actionPerformed(e: AnActionEvent) { val virtualFile = e.getData<VirtualFile>(CommonDataKeys.VIRTUAL_FILE) ?: return val project = e.getData<Project>(CommonDataKeys.PROJECT) ?: return val wizard = createImportWizard(project, null, virtualFile, *ProjectImportProvider.PROJECT_IMPORT_PROVIDER.extensions) if (wizard != null && (wizard.stepCount <= 0 || wizard.showAndGet())) { createFromWizard(project, wizard) } } }
apache-2.0
c8625fec1422e3bf83ad07e2cb0d431b
42.840909
140
0.764004
4.657005
false
false
false
false
jcam3ron/cassandra-migration
src/test/java/com/builtamont/cassandra/migration/internal/command/ValidateKIT.kt
1
4541
/** * File : ValidateKIT.kt * License : * Original - Copyright (c) 2015 - 2016 Contrast Security * Derivative - Copyright (c) 2016 Citadel Technology Solutions Pte Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.builtamont.cassandra.migration.internal.command import com.builtamont.cassandra.migration.BaseKIT import com.builtamont.cassandra.migration.CassandraMigration import com.builtamont.cassandra.migration.api.CassandraMigrationException /** * Validate command unit tests. */ class ValidateKIT : BaseKIT() { init { "Validate command API" - { "should throw exception when invalid migration scripts are provided" - { "for session and keyspace setup via configuration" { // apply migration scripts val scriptsLocations = arrayOf("migration/integ", "migration/integ/java") var cm = CassandraMigration() cm.locations = scriptsLocations cm.keyspaceConfig = getKeyspace() cm.migrate() val infoService = cm.info() val validationError = infoService.validate() validationError shouldBe null cm = CassandraMigration() cm.locations = scriptsLocations cm.keyspaceConfig = getKeyspace() cm.validate() cm = CassandraMigration() cm.locations = arrayOf("migration/integ/java") cm.keyspaceConfig = getKeyspace() shouldThrow<CassandraMigrationException> { cm.validate() } } "for external session, but keyspace setup via configuration" { // apply migration scripts val scriptsLocations = arrayOf("migration/integ", "migration/integ/java") val session = getSession() var cm = CassandraMigration() cm.locations = scriptsLocations cm.keyspaceConfig = getKeyspace() cm.migrate(session) val infoService = cm.info(session) val validationError = infoService.validate() validationError shouldBe null cm = CassandraMigration() cm.locations = scriptsLocations cm.keyspaceConfig = getKeyspace() cm.validate(session) cm = CassandraMigration() cm.locations = arrayOf("migration/integ/java") cm.keyspaceConfig = getKeyspace() shouldThrow<CassandraMigrationException> { cm.validate(session) } session.isClosed shouldBe false } "for external session and defaulted keyspace" { // apply migration scripts val scriptsLocations = arrayOf("migration/integ", "migration/integ/java") val session = getSession() var cm = CassandraMigration() cm.locations = scriptsLocations cm.migrate(session) val infoService = cm.info(session) val validationError = infoService.validate() validationError shouldBe null cm = CassandraMigration() cm.locations = scriptsLocations cm.validate(session) cm = CassandraMigration() cm.locations = arrayOf("migration/integ/java") shouldThrow<CassandraMigrationException> { cm.validate(session) } session.isClosed shouldBe false } } } } }
apache-2.0
4fb60ba60f9936e58f9ac74b5bc96cf6
35.039683
93
0.545475
6.136486
false
true
false
false
lfkdsk/JustDB
src/transaction/concurrency/ConcurrencyManager.kt
1
1239
package transaction.concurrency import storage.Block import java.util.* /** * Concurrency Manager * @see LockTable base function depend on lockTable * Created by liufengkai on 2017/5/1. */ class ConcurrencyManager { /** * lock-table */ val lockTable: LockTable = LockTable() /** * bind < Block , Lock Type> message */ private val locks = HashMap<Block, String>() /** * add read lock * @param block block */ fun readLock(block: Block) { locks[block]?.run { lockTable.readLock(block) locks.put(block, "R") println("add read lock to $block") } } /** * add write lock * 1.add read lock * 2.writeLock => block * 3.upgrade read-lock to write-lock */ fun writeLock(block: Block) { if (!hasWriteLock(block)) { // add read lock readLock(block) // add write lock - lock-update lockTable.writeLock(block) locks.put(block, "W") println("add write lock to $block") } } /** * release all block */ fun release() { for (block in locks.keys) lockTable.unlock(block) locks.clear() } /** * has write lock * @param block lock-block */ private fun hasWriteLock(block: Block): Boolean { val lockType = locks[block] return lockType ?: lockType == "W" } }
apache-2.0
34c4f084dd246a2f02217dfb6229a69d
16.971014
51
0.638418
3.152672
false
false
false
false
arturbosch/detekt
detekt-cli/src/test/kotlin/io/gitlab/arturbosch/detekt/cli/CliArgsSpec.kt
1
4894
package io.gitlab.arturbosch.detekt.cli import com.beust.jcommander.ParameterException import io.github.detekt.test.utils.resourceAsPath import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatCode import org.assertj.core.api.Assertions.assertThatExceptionOfType import org.assertj.core.api.Assertions.assertThatIllegalArgumentException import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.nio.file.Path import java.nio.file.Paths internal class CliArgsSpec : Spek({ val projectPath = resourceAsPath("/").parent.parent.parent.parent.toAbsolutePath() describe("Parsing the input path") { it("the current working directory is used if parameter is not set") { val cli = parseArguments(emptyArray()) assertThat(cli.inputPaths).hasSize(1) assertThat(cli.inputPaths.first()).isEqualTo(Paths.get(System.getProperty("user.dir"))) } it("a single value is converted to a path") { val cli = parseArguments(arrayOf("--input", "$projectPath")) assertThat(cli.inputPaths).hasSize(1) assertThat(cli.inputPaths.first().toAbsolutePath()).isEqualTo(projectPath) } it("multiple input paths can be separated by comma") { val mainPath = projectPath.resolve("src/main").toAbsolutePath() val testPath = projectPath.resolve("src/test").toAbsolutePath() val cli = parseArguments(arrayOf("--input", "$mainPath,$testPath")) assertThat(cli.inputPaths).hasSize(2) assertThat(cli.inputPaths.map(Path::toAbsolutePath)).containsExactlyInAnyOrder(mainPath, testPath) } it("reports an error if the input path does not exist") { val pathToNonExistentDirectory = projectPath.resolve("nonExistent") val params = arrayOf("--input", "$pathToNonExistentDirectory") assertThatExceptionOfType(ParameterException::class.java) .isThrownBy { parseArguments(params).inputPaths } .withMessageContaining("does not exist") } } describe("parsing config parameters") { it("should fail on invalid config value") { assertThatIllegalArgumentException() .isThrownBy { parseArguments(arrayOf("--config", ",")).toSpec() } assertThatExceptionOfType(ParameterException::class.java) .isThrownBy { parseArguments(arrayOf("--config", "sfsjfsdkfsd")).toSpec() } assertThatExceptionOfType(ParameterException::class.java) .isThrownBy { parseArguments(arrayOf("--config", "./i.do.not.exist.yml")).toSpec() } } } describe("Valid combination of options") { describe("Baseline feature") { it("reports an error when using --create-baseline without a --baseline file") { assertThatCode { parseArguments(arrayOf("--create-baseline")) } .isInstanceOf(HandledArgumentViolation::class.java) .hasMessageContaining("Creating a baseline.xml requires the --baseline parameter to specify a path") } it("reports an error when using --baseline file does not exist") { val nonExistingDirectory = projectPath.resolve("nonExistent").toString() assertThatCode { parseArguments(arrayOf("--baseline", nonExistingDirectory)) } .isInstanceOf(HandledArgumentViolation::class.java) .hasMessageContaining("The file specified by --baseline should exist '$nonExistingDirectory'.") } it("reports an error when using --baseline file which is not a file") { val directory = resourceAsPath("/cases").toString() assertThatCode { parseArguments(arrayOf("--baseline", directory)) } .isInstanceOf(HandledArgumentViolation::class.java) .hasMessageContaining("The path specified by --baseline should be a file '$directory'.") } } it("throws HelpRequest on --help") { assertThatExceptionOfType(HelpRequest::class.java) .isThrownBy { parseArguments(arrayOf("--help")) } } it("throws HandledArgumentViolation on wrong options") { assertThatExceptionOfType(HandledArgumentViolation::class.java) .isThrownBy { parseArguments(arrayOf("--unknown-to-us-all")) } } } describe("--all-rules and --fail-fast lead to all rules being activated") { arrayOf("--all-rules", "--fail-fast").forEach { flag -> it("is true for flag $flag") { val spec = parseArguments(arrayOf(flag)).toSpec() assertThat(spec.rulesSpec.activateAllRules).isTrue() } } } })
apache-2.0
beff9c19e4cea4a62e5e323253e1b319
44.738318
120
0.64385
5.262366
false
false
false
false
nemerosa/ontrack
ontrack-extension-github/src/main/java/net/nemerosa/ontrack/extension/github/indicators/compliance/RepositoryMustNotHaveTheWikiFeature.kt
1
1406
package net.nemerosa.ontrack.extension.github.indicators.compliance import net.nemerosa.ontrack.extension.github.client.OntrackGitHubClientFactory import net.nemerosa.ontrack.extension.github.model.GitHubRepositorySettings import net.nemerosa.ontrack.extension.indicators.computing.ConfigurableIndicatorState import net.nemerosa.ontrack.extension.indicators.values.BooleanIndicatorValueType import net.nemerosa.ontrack.extension.indicators.values.BooleanIndicatorValueTypeConfig import net.nemerosa.ontrack.model.structure.Project import net.nemerosa.ontrack.model.structure.PropertyService import org.springframework.stereotype.Component @Component class RepositoryMustNotHaveTheWikiFeature( propertyService: PropertyService, clientFactory: OntrackGitHubClientFactory, valueType: BooleanIndicatorValueType, ) : AbstractRepositorySettingsCheck( propertyService, clientFactory, valueType ) { companion object { const val ID = "github-compliance-repository-must-not-have-the-wiki-feature" } override val id: String = ID override val name: String = "A repository MUST NOT have the Wiki feature" override val valueConfig = { _: Project, _: ConfigurableIndicatorState -> BooleanIndicatorValueTypeConfig(required = true) } override fun checkSettings(project: Project, settings: GitHubRepositorySettings): Boolean? = settings.hasWikiEnabled }
mit
fca1a6ae4cf66bfe83c64a9713d44553
39.2
128
0.812945
4.798635
false
true
false
false
REBOOTERS/AndroidAnimationExercise
imitate/src/main/java/com/engineer/imitate/ui/fragments/DrawableExampleFragment.kt
1
4856
package com.engineer.imitate.ui.fragments import android.graphics.Color import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.annotation.NonNull import androidx.fragment.app.Fragment import com.alibaba.android.arouter.facade.annotation.Route import com.engineer.imitate.R import com.engineer.imitate.util.span.span.CenteredImageSpan import com.engineer.imitate.util.span.span.NoUnderlineClickSpan import com.engineer.imitate.util.span.span.RoundBgColorSpan import com.engineer.imitate.util.span.toolkit.TextSpanBuilder import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import kotlinx.android.synthetic.main.fragment_text_drawable.* import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger /** * A simple [Fragment] subclass. * */ @Route(path = "/anim/drawable_example") class DrawableExampleFragment : Fragment() { private val TAG = "DrawableExampleFragment" private var disposable: Disposable? = null private var count = AtomicInteger() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_text_drawable, container, false) } private fun setLabel() { val label: CharSequence = TextSpanBuilder.create("缩进") .leadingMargin(100, 0) .append("圆角背景文字色") .span(RoundBgColorSpan(-0x22bdb3, -0x1, 20)) .append("\u0020\u0020") .append("居中对齐的图片") .span(CenteredImageSpan(context, R.mipmap.ic_launcher)) .append("点击") .span(object : NoUnderlineClickSpan() { override fun onClick(widget: View) { Toast.makeText(context, "点击回调", Toast.LENGTH_SHORT).show() } }) .append("背景色") .backgroundColor(Color.BLUE) .append("前景色") .foregroundColor(-0x100) .append("粗体") .bold() .append("斜体") .italic() .append("粗斜体") .boldItalic() .append("删除线") .strikeThrough() .append("下标") .subscript() .append("上标") .superscript() .append("下划线") .underline() .append("文字缩放") .xProportion(2f) .append("文字大小") .sizeInPx(18) .append("URL") .url("mailto:[email protected]?subject=test") .build() textMessage.setText(label) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setLabel() edit.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { text.text = s } override fun afterTextChanged(s: Editable?) { } }) poll() } private fun poll() { Log.e(TAG, "next : ${count.getAndIncrement()}") val base = 10L // releaseDisposable() disposable = Observable.intervalRange(1, base, 0, 1, TimeUnit.SECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe { Log.e(TAG, "onViewCreated: it ==$it") val percent = it * 1f / base Log.e(TAG, "onViewCreated: percent ==$percent") value_text.text = "${percent} %" progress_view.setProgress(percent) if (it.toInt() == base.toInt()) { poll() } } } private fun releaseDisposable() { disposable?.let { if (it.isDisposed.not()) { it.dispose() } } } override fun onDestroy() { super.onDestroy() Log.e(TAG, "onDestroy() called") } override fun onDestroyView() { Log.e(TAG, "onDestroyView() called ${count}") super.onDestroyView() releaseDisposable() } }
apache-2.0
a451bd5ef072823239593235febe2c2f
31.094595
98
0.565684
4.607177
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/ui/UIProgressBar.kt
1
2011
package com.soywiz.korge.ui import com.soywiz.kmem.* import com.soywiz.korge.debug.* import com.soywiz.korge.render.* import com.soywiz.korge.view.* import com.soywiz.korge.view.ktree.* import com.soywiz.korui.* inline fun Container.uiProgressBar( width: Double = 256.0, height: Double = 24.0, current: Double = 0.0, maximum: Double = 100.0, block: @ViewDslMarker UIProgressBar.() -> Unit = {} ): UIProgressBar = UIProgressBar(width, height, current, maximum).addTo(this).apply(block) open class UIProgressBar( width: Double = 256.0, height: Double = 24.0, current: Double = 0.0, maximum: Double = 100.0, ) : UIView(width, height), ViewLeaf { var current by uiObservable(current) { updateState() } var maximum by uiObservable(maximum) { updateState() } override var ratio: Double set(value) { current = value * maximum } get() = (current / maximum).clamp01() private val background = solidRect(width, height, buttonBackColor) protected open val progressView: NinePatchEx = ninePatch(buttonNormal, width * (current / maximum).clamp01(), height) override fun renderInternal(ctx: RenderContext) { background.size(width, height) progressView.size(width * ratio, height) progressView.ninePatch = buttonNormal background.color = buttonBackColor super.renderInternal(ctx) } override fun buildDebugComponent(views: Views, container: UiContainer) { container.uiCollapsibleSection(this@UIProgressBar::class.simpleName!!) { uiEditableValue(::current, min = 0.0, max = 100.0, clamp = false) uiEditableValue(::maximum, min = 1.0, max = 100.0, clamp = false) } super.buildDebugComponent(views, container) } object Serializer : KTreeSerializerExt<UIProgressBar>("UIProgressBar", UIProgressBar::class, { UIProgressBar() }, { add(UIProgressBar::current) add(UIProgressBar::maximum) add(UIProgressBar::width) add(UIProgressBar::height) }) }
apache-2.0
e77b651c338627fe47a8a82001a69706
33.672414
119
0.689707
3.904854
false
false
false
false
mibac138/ArgParser
binder/src/test/kotlin/com/github/mibac138/argparser/binder/JavaDefaultValueSyntaxGeneratorTest.kt
1
2172
package com.github.mibac138.argparser.binder import com.github.mibac138.argparser.binder.JavaDefaultValueSyntaxGenerator.NO_DEFAULT_VALUE import com.github.mibac138.argparser.syntax.DefaultValueComponent import com.github.mibac138.argparser.syntax.defaultValue import com.github.mibac138.argparser.syntax.dsl.SyntaxContainerDSL import com.github.mibac138.argparser.syntax.dsl.SyntaxElementDSL import com.github.mibac138.argparser.syntax.dsl.elementDsl import org.junit.Test import kotlin.test.assertEquals /** * Created by mibac138 on 09-07-2017. */ class JavaDefaultValueSyntaxGeneratorTest { private val generator: (Array<Any?>) -> JavaDefaultValueSyntaxGenerator = { JavaDefaultValueSyntaxGenerator(*it) } @Test fun test() { val dsl = SyntaxElementDSL(Any::class.java) val param = this::kotlinFunction.parameters[0] generator(arrayOf("default")).generate(dsl, param) assertEquals("default", dsl.defaultValue) } @Test fun test2() { val dsl = SyntaxElementDSL(Any::class.java) val param = this::kotlinFunction.parameters[1] generator(arrayOf(null, 10)).generate(dsl, param) assertEquals(10, dsl.defaultValue) } @Test fun testNoDefaultValue() { val dsl = SyntaxElementDSL(Any::class.java) val param = this::kotlinFunction.parameters[0] generator(arrayOf(NO_DEFAULT_VALUE)).generate(dsl, param) assertEquals(null, dsl.defaultValue) assertEquals(null, dsl.components.firstOrNull { it is DefaultValueComponent }) } @Test fun testAlmostOutOfBounds() { val dsl = SyntaxContainerDSL(Any::class.java) val gen = generator(arrayOf(0)) val element1 = dsl.elementDsl(Any::class.java) gen.generate(element1, this::kotlinFunction.parameters[0]) assertEquals(0, element1.defaultValue) val element2 = dsl.elementDsl(Any::class.java) gen.generate(element2, this::kotlinFunction.parameters[1]) assertEquals(null, element2.defaultValue) } private fun kotlinFunction(string: String, int: Int) { println("string = $string, int = $int") } }
mit
3f91cc59911324708004b19603f971c2
31.924242
118
0.707182
4.168906
false
true
false
false
cashapp/sqldelight
sqldelight-idea-plugin/src/main/kotlin/app/cash/sqldelight/intellij/util/GeneratedVirtualFile.kt
1
2831
/* * Copyright (C) 2018 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.sqldelight.intellij.util import app.cash.sqldelight.core.SqlDelightFileIndex import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.module.Module import com.intellij.openapi.vfs.VirtualFile import kotlin.reflect.KProperty class GeneratedVirtualFile(private val path: String, module: Module) { private val applicationManager = ApplicationManager.getApplication() private val index = SqlDelightFileIndex.getInstance(module) private var backingFile: VirtualFile? = null operator fun getValue( thisRef: Nothing?, property: KProperty<*>, ): VirtualFile { applicationManager.assertWriteAccessAllowed() synchronized(this) { val backingFile = this.backingFile if (backingFile == null || !backingFile.exists()) { var file = index.contentRoot.findFileByRelativePath(path) if (file == null || !file.exists()) { file = getOrCreateFile(path) } check(file.exists()) { "VirtualFile $path still doesn't exist after creating." } this.backingFile = file return file } else { return backingFile } } } private fun getOrCreateFile(path: String): VirtualFile { val indexOfName = path.lastIndexOf('/') val parent = getOrCreateDirectory(path.substring(0, indexOfName)) return parent.findOrCreateChildData(this, path.substring(indexOfName + 1, path.length)) } private fun getOrCreateDirectory(path: String): VirtualFile { val indexOfName = path.lastIndexOf('/') if (indexOfName == -1) { return index.contentRoot.findChild(path) ?: index.contentRoot.createChildDirectory(this, path) } val parentPath = path.substring(0, indexOfName) var parent = index.contentRoot.findFileByRelativePath(parentPath) if (parent == null || !parent.exists()) { parent = getOrCreateDirectory(parentPath) if (!parent.exists() || !parent.isDirectory) throw AssertionError() } val name = path.substring(indexOfName + 1, path.length) var child = parent.findChild(name) if (child != null && !child.isDirectory) { child.delete(this) child = null } return child ?: parent.createChildDirectory(this, name) } }
apache-2.0
f142cadc9b01509a3c538ad004937f37
36.25
100
0.708937
4.472354
false
false
false
false
android/health-samples
health-platform-v1/HealthPlatformSample/app/src/main/java/com/example/healthplatformsample/presentation/ui/TotalStepsScreen/TotalStepsScreen.kt
1
2671
/* * 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.healthplatformsample.presentation.ui.TotalStepsScreen import android.content.Context import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import com.example.healthplatformsample.data.HealthPlatformManager import com.example.healthplatformsample.presentation.components.TotalStepsEntry import java.util.UUID @Composable fun TotalStepsScreen( healthPlatformManager: HealthPlatformManager, onError: (Context, Throwable?) -> Unit, viewModel: TotalStepsViewModel = viewModel( factory = TotalStepsViewModelFactory( healthPlatformManager = healthPlatformManager ) ) ) { val totalSteps by viewModel.totalSteps val state = viewModel.uiState val context = LocalContext.current // Remember the last error ID, such that it is possible to avoid re-launching the error // notification for the same error when the screen is recomposed, or configuration changes etc. val errorId = rememberSaveable { mutableStateOf(UUID.randomUUID()) } // The [MainModel.UiState] provides details of whether the last action was a success or resulted // in an error. Where an error occurred, for example in reading and writing to Health Platform, // the user is notified, and where the error is one that can be recovered from, an attempt to // do so is made. LaunchedEffect(state) { if (state is TotalStepsViewModel.UiState.Error && errorId.value != state.uuid) { onError(context, state.exception) errorId.value = state.uuid } } val modifier = Modifier.padding(4.dp) TotalStepsEntry(totalSteps, modifier = modifier) }
apache-2.0
4e67cd25a2d834f0255d17ede263b2e9
41.396825
100
0.761887
4.589347
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/inventory/items/ItemRecyclerFragment.kt
1
13408
package com.habitrpg.android.habitica.ui.fragments.inventory.items import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.result.contract.ActivityResultContracts import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.InventoryRepository import com.habitrpg.android.habitica.data.SocialRepository import com.habitrpg.android.habitica.data.UserRepository import com.habitrpg.android.habitica.databinding.FragmentItemsBinding import com.habitrpg.android.habitica.extensions.addCloseButton import com.habitrpg.android.habitica.extensions.subscribeWithErrorHandler import com.habitrpg.android.habitica.helpers.MainNavigationController import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.interactors.HatchPetUseCase import com.habitrpg.android.habitica.models.inventory.Egg import com.habitrpg.android.habitica.models.inventory.Food import com.habitrpg.android.habitica.models.inventory.HatchingPotion import com.habitrpg.android.habitica.models.inventory.Item import com.habitrpg.android.habitica.models.inventory.QuestContent import com.habitrpg.android.habitica.models.inventory.SpecialItem import com.habitrpg.android.habitica.models.responses.SkillResponse import com.habitrpg.android.habitica.models.user.OwnedItem import com.habitrpg.android.habitica.models.user.OwnedPet import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.ui.activities.BaseActivity import com.habitrpg.android.habitica.ui.activities.MainActivity import com.habitrpg.android.habitica.ui.activities.SkillMemberActivity import com.habitrpg.android.habitica.ui.adapter.inventory.ItemRecyclerAdapter import com.habitrpg.android.habitica.ui.fragments.BaseFragment import com.habitrpg.android.habitica.ui.helpers.EmptyItem import com.habitrpg.android.habitica.ui.helpers.SafeDefaultItemAnimator import com.habitrpg.android.habitica.ui.helpers.loadImage import com.habitrpg.android.habitica.ui.viewmodels.MainUserViewModel import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar import com.habitrpg.android.habitica.ui.views.dialogs.OpenedMysteryitemDialog import io.reactivex.rxjava3.core.Flowable import javax.inject.Inject class ItemRecyclerFragment : BaseFragment<FragmentItemsBinding>(), SwipeRefreshLayout.OnRefreshListener { @Inject lateinit var inventoryRepository: InventoryRepository @Inject lateinit var socialRepository: SocialRepository @Inject lateinit var userRepository: UserRepository @Inject internal lateinit var hatchPetUseCase: HatchPetUseCase @Inject lateinit var userViewModel: MainUserViewModel var adapter: ItemRecyclerAdapter? = null var itemType: String? = null var transformationItems: MutableList<OwnedItem> = mutableListOf() var itemTypeText: String? = null var user: User? = null private var selectedSpecialItem: SpecialItem? = null internal var layoutManager: androidx.recyclerview.widget.LinearLayoutManager? = null override var binding: FragmentItemsBinding? = null override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentItemsBinding { return FragmentItemsBinding.inflate(inflater, container, false) } override fun onDestroy() { inventoryRepository.close() super.onDestroy() } override fun injectFragment(component: UserComponent) { component.inject(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding?.refreshLayout?.setOnRefreshListener(this) binding?.recyclerView?.emptyItem = EmptyItem( getString(R.string.empty_items, itemTypeText ?: itemType), null, null, if (itemType == "special") null else getString(R.string.open_shop) ) { if (itemType == "quests") { MainNavigationController.navigate(R.id.questShopFragment) } else { openMarket() } } val context = activity layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context) binding?.recyclerView?.layoutManager = layoutManager adapter = binding?.recyclerView?.adapter as? ItemRecyclerAdapter if (adapter == null) { context?.let { adapter = ItemRecyclerAdapter(context) } binding?.recyclerView?.adapter = adapter adapter?.useSpecialEvents?.subscribeWithErrorHandler { onSpecialItemSelected(it) }?.let { compositeSubscription.add(it) } adapter?.let { adapter -> compositeSubscription.add( adapter.getSellItemFlowable() .flatMap { item -> inventoryRepository.sellItem(item) } .subscribe({ }, RxErrorHandler.handleEmptyError()) ) compositeSubscription.add( adapter.getQuestInvitationFlowable() .flatMap { quest -> inventoryRepository.inviteToQuest(quest) } .flatMap { socialRepository.retrieveGroup("party") } .subscribe( { MainNavigationController.navigate(R.id.partyFragment) }, RxErrorHandler.handleEmptyError() ) ) compositeSubscription.add( adapter.getOpenMysteryItemFlowable() .flatMap { inventoryRepository.openMysteryItem(userViewModel.user.value) } .doOnNext { val activity = activity as? MainActivity if (activity != null) { val dialog = OpenedMysteryitemDialog(activity) dialog.isCelebratory = true dialog.setTitle(R.string.mystery_item_title) dialog.binding.iconView.loadImage("shop_${it.key}") dialog.binding.titleView.text = it.text dialog.binding.descriptionView.text = it.notes dialog.addButton(R.string.equip, true) { _, _ -> inventoryRepository.equip("equipped", it.key ?: "").subscribe({}, RxErrorHandler.handleEmptyError()) } dialog.addCloseButton() dialog.enqueue() } } .subscribe({ }, RxErrorHandler.handleEmptyError()) ) compositeSubscription.add(adapter.startHatchingEvents.subscribeWithErrorHandler { showHatchingDialog(it) }) compositeSubscription.add(adapter.hatchPetEvents.subscribeWithErrorHandler { hatchPet(it.first, it.second) }) } } activity?.let { binding?.recyclerView?.addItemDecoration(androidx.recyclerview.widget.DividerItemDecoration(it, androidx.recyclerview.widget.DividerItemDecoration.VERTICAL)) } binding?.recyclerView?.itemAnimator = SafeDefaultItemAnimator() if (savedInstanceState != null) { this.itemType = savedInstanceState.getString(ITEM_TYPE_KEY, "") } binding?.titleTextView?.visibility = View.GONE binding?.footerTextView?.visibility = View.GONE binding?.openMarketButton?.visibility = View.GONE binding?.openMarketButton?.setOnClickListener { openMarket() } this.loadItems() } private fun showHatchingDialog(item: Item) { val fragment = ItemDialogFragment() if (item is Egg) { fragment.itemType = "hatchingPotions" fragment.hatchingItem = item } else { fragment.itemType = "eggs" fragment.hatchingItem = item } fragment.isHatching = true fragment.isFeeding = false parentFragmentManager.let { fragment.show(it, "hatchingDialog") } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(ITEM_TYPE_KEY, this.itemType) } override fun onRefresh() { binding?.refreshLayout?.isRefreshing = true compositeSubscription.add( userRepository.retrieveUser(true, true) .doOnTerminate { binding?.refreshLayout?.isRefreshing = false }.subscribe({ }, RxErrorHandler.handleEmptyError()) ) } private fun hatchPet(potion: HatchingPotion, egg: Egg) { (activity as? BaseActivity)?.let { compositeSubscription.add( hatchPetUseCase.observable( HatchPetUseCase.RequestValues( potion, egg, it ) ).subscribeWithErrorHandler {} ) } } private fun loadItems() { val itemClass: Class<out Item> = when (itemType) { "eggs" -> Egg::class.java "hatchingPotions" -> HatchingPotion::class.java "food" -> Food::class.java "quests" -> QuestContent::class.java "special" -> SpecialItem::class.java else -> Egg::class.java } itemType?.let { type -> compositeSubscription.add( inventoryRepository.getOwnedItems(type) .map { it.distinctBy { it.key } } .doOnNext { items -> adapter?.data = items } .map { items -> items.mapNotNull { it.key } } .flatMap { inventoryRepository.getItems(itemClass, it.toTypedArray()) } .map { val itemMap = mutableMapOf<String, Item>() for (item in it) { itemMap[item.key] = item } itemMap } .subscribe( { items -> adapter?.items = items }, RxErrorHandler.handleEmptyError() ) ) } compositeSubscription.add(inventoryRepository.getPets().subscribe({ adapter?.setExistingPets(it) }, RxErrorHandler.handleEmptyError())) compositeSubscription.add( inventoryRepository.getOwnedPets() .map { ownedMounts -> val mountMap = mutableMapOf<String, OwnedPet>() ownedMounts.forEach { mountMap[it.key ?: ""] = it } return@map mountMap } .subscribe({ adapter?.setOwnedPets(it) }, RxErrorHandler.handleEmptyError()) ) } private fun openMarket() { MainNavigationController.navigate(R.id.marketFragment) } private fun onSpecialItemSelected(specialItem: SpecialItem) { selectedSpecialItem = specialItem val intent = Intent(activity, SkillMemberActivity::class.java) memberSelectionResult.launch(intent) } private val memberSelectionResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { if (it.resultCode == Activity.RESULT_OK) { useSpecialItem(selectedSpecialItem, it.data?.getStringExtra("member_id")) } } private fun useSpecialItem(specialItem: SpecialItem?, memberID: String? = null) { if (specialItem == null || memberID == null) { return } val observable: Flowable<SkillResponse> = userRepository.useSkill(specialItem.key, specialItem.target, memberID) compositeSubscription.add( observable.subscribe( { skillResponse -> this.displaySpecialItemResult(specialItem) }, RxErrorHandler.handleEmptyError() ) ) } private fun displaySpecialItemResult(specialItem: SpecialItem?) { if (!isAdded) return val activity = activity as? MainActivity activity?.let { HabiticaSnackbar.showSnackbar( it.snackbarContainer, context?.getString(R.string.used_skill_without_mana, specialItem?.text), HabiticaSnackbar.SnackbarDisplayType.BLUE ) } loadItems() } companion object { private const val ITEM_TYPE_KEY = "CLASS_TYPE_KEY" } }
gpl-3.0
dfd8dfc629808b15a454e4d33d029fb4
40.43038
169
0.605832
5.669345
false
false
false
false
androidx/androidx
window/window-core/src/main/java/androidx/window/core/layout/WindowSizeClass.kt
3
3729
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.window.core.layout /** * [WindowSizeClass] provides breakpoints for a viewport. Designers should design around the * different combinations of width and height buckets. Developers should use the different buckets * to specify the layouts. Ideally apps will work well in each bucket and by extension work well * across multiple devices. If two devices are in similar buckets they should behave similarly. * * This class is meant to be a common definition that can be shared across different device types. * Application developers can use WindowSizeClass to have standard window buckets and design the UI * around those buckets. Library developers can use these buckets to create different UI with * respect to each bucket. This will help with consistency across multiple device types. * * A library developer use-case can be creating some navigation UI library. For a size * class with the [WindowWidthSizeClass.EXPANDED] width it might be more reasonable to have a side * navigation. For a [WindowWidthSizeClass.COMPACT] width, a bottom navigation might be a better * fit. * * An application use-case can be applied for apps that use a list-detail pattern. The app can use * the [WindowWidthSizeClass.MEDIUM] to determine if there is enough space to show the list and the * detail side by side. If all apps follow this guidance then it will present a very consistent user * experience. * * @see WindowWidthSizeClass * @see WindowHeightSizeClass */ class WindowSizeClass private constructor( val windowWidthSizeClass: WindowWidthSizeClass, val windowHeightSizeClass: WindowHeightSizeClass ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as WindowSizeClass if (windowWidthSizeClass != other.windowWidthSizeClass) return false if (windowHeightSizeClass != other.windowHeightSizeClass) return false return true } override fun hashCode(): Int { var result = windowWidthSizeClass.hashCode() result = 31 * result + windowHeightSizeClass.hashCode() return result } override fun toString(): String { return "SizeClass { widthSizeClass: $windowWidthSizeClass," + " heightSizeClass: $windowHeightSizeClass }" } companion object { /** * Computes the [WindowSizeClass] for the given width and height in DP. * @param dpWidth width of a window in DP. * @param dpHeight height of a window in DP. * @return [WindowSizeClass] that is recommended for the given dimensions. * @throws IllegalArgumentException if [dpWidth] or [dpHeight] is * negative. */ @JvmStatic fun compute(dpWidth: Float, dpHeight: Float): WindowSizeClass { val windowWidthSizeClass = WindowWidthSizeClass.compute(dpWidth) val windowHeightSizeClass = WindowHeightSizeClass.compute(dpHeight) return WindowSizeClass(windowWidthSizeClass, windowHeightSizeClass) } } }
apache-2.0
387645a41d4f748bcb2eef4baf303616
41.873563
100
0.724323
4.99866
false
false
false
false
androidx/androidx
wear/compose/compose-material/src/androidAndroidTest/kotlin/androidx/wear/compose/material/PositionIndicatorScreenshotTest.kt
3
4250
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.compose.material import android.os.Build import androidx.compose.foundation.background import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.testutils.assertAgainstGolden import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.unit.LayoutDirection import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import androidx.test.filters.SdkSuppress import androidx.test.screenshot.AndroidXScreenshotTestRule import org.junit.Rule import org.junit.Test import org.junit.rules.TestName import org.junit.runner.RunWith @MediumTest @RunWith(AndroidJUnit4::class) @SdkSuppress(minSdkVersion = Build.VERSION_CODES.O) class PositionIndicatorScreenshotTest { @get:Rule val rule = createComposeRule() @get:Rule val screenshotRule = AndroidXScreenshotTestRule(SCREENSHOT_GOLDEN_PATH) @get:Rule val testName = TestName() @Test fun left_position_indicator() = position_indicator_position_test( position = PositionIndicatorAlignment.Left, value = 0.2f, ltr = true, goldenIdentifier = testName.methodName ) @Test fun left_in_rtl_position_indicator() = position_indicator_position_test( position = PositionIndicatorAlignment.Left, value = 0.4f, ltr = false, goldenIdentifier = testName.methodName ) @Test fun right_position_indicator() = position_indicator_position_test( position = PositionIndicatorAlignment.Right, value = 0.3f, ltr = true, goldenIdentifier = testName.methodName ) @Test fun right_in_rtl_position_indicator() = position_indicator_position_test( position = PositionIndicatorAlignment.Right, value = 0.5f, ltr = false, goldenIdentifier = testName.methodName ) @Test fun end_position_indicator() = position_indicator_position_test( position = PositionIndicatorAlignment.End, value = 0.1f, ltr = true, goldenIdentifier = testName.methodName ) @Test fun end_in_rtl_position_indicator() = position_indicator_position_test( position = PositionIndicatorAlignment.End, value = 0.8f, ltr = false, goldenIdentifier = testName.methodName ) private fun position_indicator_position_test( position: PositionIndicatorAlignment, value: Float, goldenIdentifier: String, ltr: Boolean = true, ) { rule.setContentWithTheme { val actualLayoutDirection = if (ltr) LayoutDirection.Ltr else LayoutDirection.Rtl CompositionLocalProvider(LocalLayoutDirection provides actualLayoutDirection) { PositionIndicator( value = { value }, position = position, modifier = Modifier.testTag(TEST_TAG).background(Color.Black) ) } } rule.waitForIdle() rule.onNodeWithTag(TEST_TAG) .captureToImage() .assertAgainstGolden(screenshotRule, goldenIdentifier) } }
apache-2.0
5836eb5bb442362d5973cfa235e8d257
30.962406
91
0.668941
4.924681
false
true
false
false
androidx/androidx
paging/paging-common/src/main/kotlin/androidx/paging/PositionalDataSource.kt
3
21425
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.paging import androidx.annotation.RestrictTo import androidx.annotation.VisibleForTesting import androidx.annotation.WorkerThread import androidx.arch.core.util.Function import androidx.paging.DataSource.KeyType.POSITIONAL import androidx.paging.PagingSource.LoadResult.Page.Companion.COUNT_UNDEFINED import kotlinx.coroutines.suspendCancellableCoroutine import kotlin.coroutines.resume /** * Position-based data loader for a fixed-size, countable data set, supporting fixed-size loads at * arbitrary page positions. * * Extend PositionalDataSource if you can load pages of a requested size at arbitrary positions, * and provide a fixed item count. If your data source can't support loading arbitrary requested * page sizes (e.g. when network page size constraints are only known at runtime), either use * [PageKeyedDataSource] or [ItemKeyedDataSource], or pass the initial result with the two parameter * [LoadInitialCallback.onResult]. * * Room can generate a Factory of PositionalDataSources for you: * ``` * @Dao * interface UserDao { * @Query("SELECT * FROM user ORDER BY age DESC") * public abstract DataSource.Factory<Integer, User> loadUsersByAgeDesc(); * } * ``` * * @param T Type of items being loaded by the [PositionalDataSource]. */ @Deprecated( message = "PositionalDataSource is deprecated and has been replaced by PagingSource", replaceWith = ReplaceWith( "PagingSource<Int, T>", "androidx.paging.PagingSource" ) ) public abstract class PositionalDataSource<T : Any> : DataSource<Int, T>(POSITIONAL) { /** * Holder object for inputs to [loadInitial]. */ public open class LoadInitialParams( /** * Initial load position requested. * * Note that this may not be within the bounds of your data set, it may need to be adjusted * before you execute your load. */ @JvmField public val requestedStartPosition: Int, /** * Requested number of items to load. * * Note that this may be larger than available data. */ @JvmField public val requestedLoadSize: Int, /** * Defines page size acceptable for return values. * * List of items passed to the callback must be an integer multiple of page size. */ @JvmField public val pageSize: Int, /** * Defines whether placeholders are enabled, and whether the loaded total count will be * ignored. */ @JvmField public val placeholdersEnabled: Boolean ) { init { check(requestedStartPosition >= 0) { "invalid start position: $requestedStartPosition" } check(requestedLoadSize >= 0) { "invalid load size: $requestedLoadSize" } check(pageSize >= 0) { "invalid page size: $pageSize" } } } /** * Holder object for inputs to [loadRange]. */ public open class LoadRangeParams( /** * START position of data to load. * * Returned data must start at this position. */ @JvmField public val startPosition: Int, /** * Number of items to load. * * Returned data must be of this size, unless at end of the list. */ @JvmField public val loadSize: Int ) /** * Callback for [loadInitial] to return data, position, and count. * * A callback should be called only once, and may throw if called again. * * It is always valid for a DataSource loading method that takes a callback to stash the * callback and call it later. This enables DataSources to be fully asynchronous, and to handle * temporary, recoverable error states (such as a network error that can be retried). * * @param T Type of items being loaded. */ public abstract class LoadInitialCallback<T> { /** * Called to pass initial load state from a DataSource. * * Call this method from [loadInitial] function to return data, and inform how many * placeholders should be shown before and after. If counting is cheap compute (for example, * if a network load returns the information regardless), it's recommended to pass the total * size to the totalCount parameter. If placeholders are not requested (when * [LoadInitialParams.placeholdersEnabled] is false), you can instead call [onResult]. * * @param data List of items loaded from the [DataSource]. If this is empty, the * [DataSource] is treated as empty, and no further loads will occur. * @param position Position of the item at the front of the list. If there are N items * before the items in data that can be loaded from this DataSource, pass N. * @param totalCount Total number of items that may be returned from this DataSource. * Includes the number in the initial [data] parameter as well as any items that can be * loaded in front or behind of [data]. */ public abstract fun onResult(data: List<T>, position: Int, totalCount: Int) /** * Called to pass initial load state from a DataSource without total count, when * placeholders aren't requested. * * **Note:** This method can only be called when placeholders are disabled (i.e., * [LoadInitialParams.placeholdersEnabled] is `false`). * * Call this method from [loadInitial] function to return data, if position is known but * total size is not. If placeholders are requested, call the three parameter variant: * [onResult]. * * @param data List of items loaded from the [DataSource]. If this is empty, the * [DataSource] is treated as empty, and no further loads will occur. * @param position Position of the item at the front of the list. If there are N items * before the items in data that can be provided by this [DataSource], pass N. */ public abstract fun onResult(data: List<T>, position: Int) } /** * Callback for PositionalDataSource [loadRange] to return data. * * A callback should be called only once, and may throw if called again. * * It is always valid for a [DataSource] loading method that takes a callback to stash the * callback and call it later. This enables DataSources to be fully asynchronous, and to handle * temporary, recoverable error states (such as a network error that can be retried). * * @param T Type of items being loaded. */ public abstract class LoadRangeCallback<T> { /** * Called to pass loaded data from [loadRange]. * * @param data List of items loaded from the [DataSource]. Must be same size as requested, * unless at end of list. */ public abstract fun onResult(data: List<T>) } /** * @suppress */ @RestrictTo(RestrictTo.Scope.LIBRARY) public companion object { /** * Helper for computing an initial position in [loadInitial] when total data set size can be * computed ahead of loading. * * The value computed by this function will do bounds checking, page alignment, and * positioning based on initial load size requested. * * Example usage in a [PositionalDataSource] subclass: * ``` * class ItemDataSource extends PositionalDataSource<Item> { * private int computeCount() { * // actual count code here * } * * private List<Item> loadRangeInternal(int startPosition, int loadCount) { * // actual load code here * } * * @Override * public void loadInitial(@NonNull LoadInitialParams params, * @NonNull LoadInitialCallback<Item> callback) { * int totalCount = computeCount(); * int position = computeInitialLoadPosition(params, totalCount); * int loadSize = computeInitialLoadSize(params, position, totalCount); * callback.onResult(loadRangeInternal(position, loadSize), position, totalCount); * } * * @Override * public void loadRange(@NonNull LoadRangeParams params, * @NonNull LoadRangeCallback<Item> callback) { * callback.onResult(loadRangeInternal(params.startPosition, params.loadSize)); * } * } * ``` * * @param params Params passed to [loadInitial], including page size, and requested start / * loadSize. * @param totalCount Total size of the data set. * @return Position to start loading at. * * @see [computeInitialLoadSize] */ @JvmStatic public fun computeInitialLoadPosition(params: LoadInitialParams, totalCount: Int): Int { val position = params.requestedStartPosition val initialLoadSize = params.requestedLoadSize val pageSize = params.pageSize var pageStart = position / pageSize * pageSize // maximum start pos is that which will encompass end of list val maximumLoadPage = (totalCount - initialLoadSize + pageSize - 1) / pageSize * pageSize pageStart = minOf(maximumLoadPage, pageStart) // minimum start position is 0 pageStart = maxOf(0, pageStart) return pageStart } /** * Helper for computing an initial load size in [loadInitial] when total data set size can * be computed ahead of loading. * * This function takes the requested load size, and bounds checks it against the value * returned by [computeInitialLoadPosition]. * * Example usage in a [PositionalDataSource] subclass: * ``` * class ItemDataSource extends PositionalDataSource<Item> { * private int computeCount() { * // actual count code here * } * * private List<Item> loadRangeInternal(int startPosition, int loadCount) { * // actual load code here * } * * @Override * public void loadInitial(@NonNull LoadInitialParams params, * @NonNull LoadInitialCallback<Item> callback) { * int totalCount = computeCount(); * int position = computeInitialLoadPosition(params, totalCount); * int loadSize = computeInitialLoadSize(params, position, totalCount); * callback.onResult(loadRangeInternal(position, loadSize), position, totalCount); * } * * @Override * public void loadRange(@NonNull LoadRangeParams params, * @NonNull LoadRangeCallback<Item> callback) { * callback.onResult(loadRangeInternal(params.startPosition, params.loadSize)); * } * } * ``` * * @param params Params passed to [loadInitial], including page size, and requested start / * loadSize. * @param initialLoadPosition Value returned by [computeInitialLoadPosition] * @param totalCount Total size of the data set. * @return Number of items to load. * * @see [computeInitialLoadPosition] */ @JvmStatic public fun computeInitialLoadSize( params: LoadInitialParams, initialLoadPosition: Int, totalCount: Int ): Int = minOf(totalCount - initialLoadPosition, params.requestedLoadSize) } final override suspend fun load(params: Params<Int>): BaseResult<T> { if (params.type == LoadType.REFRESH) { var initialPosition = 0 var initialLoadSize = params.initialLoadSize if (params.key != null) { initialPosition = params.key if (params.placeholdersEnabled) { // snap load size to page multiple (minimum two) initialLoadSize = maxOf(initialLoadSize / params.pageSize, 2) * params.pageSize // move start so the load is centered around the key, not starting at it val idealStart = initialPosition - initialLoadSize / 2 initialPosition = maxOf(0, idealStart / params.pageSize * params.pageSize) } else { // not tiled, so don't try to snap or force multiple of a page size initialPosition = maxOf(0, initialPosition - initialLoadSize / 2) } } val initParams = LoadInitialParams( initialPosition, initialLoadSize, params.pageSize, params.placeholdersEnabled ) return loadInitial(initParams) } else { var startIndex = params.key!! var loadSize = params.pageSize if (params.type == LoadType.PREPEND) { // clamp load size to positive indices only, and shift start index by load size loadSize = minOf(loadSize, startIndex) startIndex -= loadSize } return loadRange(LoadRangeParams(startIndex, loadSize)) } } /** * Load initial list data. * * This method is called to load the initial page(s) from the DataSource. * * LoadResult list must be a multiple of pageSize to enable efficient tiling. */ @VisibleForTesting internal suspend fun loadInitial(params: LoadInitialParams) = suspendCancellableCoroutine<BaseResult<T>> { cont -> loadInitial( params, object : LoadInitialCallback<T>() { override fun onResult(data: List<T>, position: Int, totalCount: Int) { if (isInvalid) { // NOTE: this isInvalid check works around // https://issuetracker.google.com/issues/124511903 cont.resume(BaseResult.empty()) } else { val nextKey = position + data.size resume( params, BaseResult( data = data, // skip passing prevKey if nothing else to load prevKey = if (position == 0) null else position, // skip passing nextKey if nothing else to load nextKey = if (nextKey == totalCount) null else nextKey, itemsBefore = position, itemsAfter = totalCount - data.size - position ) ) } } override fun onResult(data: List<T>, position: Int) { if (isInvalid) { // NOTE: this isInvalid check works around // https://issuetracker.google.com/issues/124511903 cont.resume(BaseResult.empty()) } else { resume( params, BaseResult( data = data, // skip passing prevKey if nothing else to load prevKey = if (position == 0) null else position, // can't do same for nextKey, since we don't know if load is terminal nextKey = position + data.size, itemsBefore = position, itemsAfter = COUNT_UNDEFINED ) ) } } private fun resume(params: LoadInitialParams, result: BaseResult<T>) { if (params.placeholdersEnabled) { result.validateForInitialTiling(params.pageSize) } cont.resume(result) } } ) } /** * Called to load a range of data from the DataSource. * * This method is called to load additional pages from the DataSource after the * [ItemKeyedDataSource.LoadInitialCallback] passed to dispatchLoadInitial has initialized a * [PagedList]. * * Unlike [ItemKeyedDataSource.loadInitial], this method must return the number of items * requested, at the position requested. */ private suspend fun loadRange(params: LoadRangeParams) = suspendCancellableCoroutine<BaseResult<T>> { cont -> loadRange( params, object : LoadRangeCallback<T>() { override fun onResult(data: List<T>) { // skip passing prevKey if nothing else to load. We only do this for prepend // direction, since 0 as first index is well defined, but max index may not be val prevKey = if (params.startPosition == 0) null else params.startPosition when { isInvalid -> cont.resume(BaseResult.empty()) else -> cont.resume( BaseResult( data = data, prevKey = prevKey, nextKey = params.startPosition + data.size ) ) } } } ) } /** * Load initial list data. * * This method is called to load the initial page(s) from the [DataSource]. * * LoadResult list must be a multiple of pageSize to enable efficient tiling. * * @param params Parameters for initial load, including requested start position, load size, and * page size. * @param callback Callback that receives initial load data, including position and total data * set size. */ @WorkerThread public abstract fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<T>) /** * Called to load a range of data from the DataSource. * * This method is called to load additional pages from the DataSource after the * [LoadInitialCallback] passed to dispatchLoadInitial has initialized a [PagedList]. * * Unlike [loadInitial], this method must return the number of items requested, at the position * requested. * * @param params Parameters for load, including start position and load size. * @param callback Callback that receives loaded data. */ @WorkerThread public abstract fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<T>) @Suppress("RedundantVisibilityModifier") // Metalava doesn't inherit visibility properly. internal override val isContiguous = false @Suppress("RedundantVisibilityModifier") // Metalava doesn't inherit visibility properly. internal final override fun getKeyInternal(item: T): Int = throw IllegalStateException("Cannot get key by item in positionalDataSource") @Suppress("DEPRECATION") final override fun <V : Any> mapByPage( function: Function<List<T>, List<V>> ): PositionalDataSource<V> = WrapperPositionalDataSource(this, function) @Suppress("DEPRECATION") final override fun <V : Any> mapByPage( function: (List<T>) -> List<V> ): PositionalDataSource<V> = mapByPage(Function { function(it) }) @Suppress("DEPRECATION") final override fun <V : Any> map(function: Function<T, V>): PositionalDataSource<V> = mapByPage(Function { list -> list.map { function.apply(it) } }) @Suppress("DEPRECATION") final override fun <V : Any> map(function: (T) -> V): PositionalDataSource<V> = mapByPage(Function { list -> list.map(function) }) }
apache-2.0
e8e9a532f2744ead56dbe17fc8d0a92a
41.425743
105
0.578156
5.450267
false
false
false
false
robohorse/RoboPOJOGenerator
generator/src/main/kotlin/com/robohorse/robopojogenerator/properties/ClassField.kt
1
937
package com.robohorse.robopojogenerator.properties import com.robohorse.robopojogenerator.properties.templates.ArrayItemsTemplate internal class ClassField( private var classEnum: ClassEnum? = null, var className: String? = null, var classField: ClassField? = null ) { fun getJavaItem(primitive: Boolean = true): String? { return if (null != classField) { String.format( ArrayItemsTemplate.LIST_OF_ITEM, classField?.getJavaItem(primitive = false) ) } else { className ?: if (primitive) classEnum?.primitive else classEnum?.boxed } } fun getKotlinItem(): String? { return if (null != classField) { String.format( ArrayItemsTemplate.LIST_OF_ITEM, classField?.getKotlinItem() ) } else { className ?: classEnum?.kotlin } } }
mit
528d7f7b889123e8f002c64626f44f53
28.28125
82
0.591249
4.732323
false
false
false
false
inorichi/tachiyomi-extensions
src/pt/brmangas/src/eu/kanade/tachiyomi/extension/pt/brmangas/BrMangas.kt
1
5487
package eu.kanade.tachiyomi.extension.pt.brmangas import eu.kanade.tachiyomi.annotations.Nsfw import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import okhttp3.Headers import okhttp3.HttpUrl.Companion.toHttpUrlOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element import java.util.concurrent.TimeUnit @Nsfw class BrMangas : ParsedHttpSource() { override val name = "BR Mangás" override val baseUrl = "https://brmangas.com" override val lang = "pt-BR" override val supportsLatest = true override val client: OkHttpClient = network.cloudflareClient.newBuilder() .addInterceptor(RateLimitInterceptor(1, 1, TimeUnit.SECONDS)) .build() override fun headersBuilder(): Headers.Builder = Headers.Builder() .add("Accept", ACCEPT) .add("Accept-Language", ACCEPT_LANGUAGE) .add("Referer", "$baseUrl/") override fun popularMangaRequest(page: Int): Request { val listPath = if (page == 1) "" else "page/${page - 1}" val newHeaders = headersBuilder() .set("Referer", "$baseUrl/lista-de-mangas/$listPath") .build() val pageStr = if (page != 1) "page/$page" else "" return GET("$baseUrl/lista-de-mangas/$pageStr", newHeaders) } override fun popularMangaSelector(): String = "div.listagem.row div.item a[title]" override fun popularMangaFromElement(element: Element): SManga = SManga.create().apply { val thumbnailEl = element.select("img").first()!! title = element.select("h2.titulo").first()!!.text() thumbnail_url = when { thumbnailEl.hasAttr("original-src") -> thumbnailEl.attr("original-src") else -> thumbnailEl.attr("src") } setUrlWithoutDomain(element.attr("href")) } override fun popularMangaNextPageSelector() = "div.navigation a.next" override fun latestUpdatesRequest(page: Int): Request { val listPath = if (page == 1) "" else "category/page/${page - 1}" val newHeaders = headersBuilder() .set("Referer", "$baseUrl/$listPath") .build() val pageStr = if (page != 1) "page/$page" else "" return GET("$baseUrl/category/mangas/$pageStr", newHeaders) } override fun latestUpdatesSelector() = popularMangaSelector() override fun latestUpdatesFromElement(element: Element): SManga = popularMangaFromElement(element) override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector() override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val url = baseUrl.toHttpUrlOrNull()!!.newBuilder() .addQueryParameter("s", query) return GET(url.toString(), headers) } override fun searchMangaSelector() = popularMangaSelector() override fun searchMangaFromElement(element: Element): SManga = popularMangaFromElement(element) override fun searchMangaNextPageSelector(): String? = null override fun mangaDetailsParse(document: Document): SManga = SManga.create().apply { val infoElement = document.select("div.serie-geral div.infoall").first()!! title = document.select("title").first().text().substringBeforeLast(" - ") genre = infoElement.select("a.category.tag").joinToString { it.text() } description = document.select("div.manga_sinopse ~ p").text().trim() thumbnail_url = infoElement.select("div.serie-capa img").first()!!.attr("src") } override fun chapterListParse(response: Response): List<SChapter> { return super.chapterListParse(response).reversed() } override fun chapterListSelector() = "ul.capitulos li.row a" override fun chapterFromElement(element: Element): SChapter = SChapter.create().apply { name = element.text() setUrlWithoutDomain(element.attr("href")) } override fun pageListParse(document: Document): List<Page> { return document.select("script:containsData(imageArray)").first()!! .data() .substringAfter("[") .substringBefore("]") .split(",") .mapIndexed { i, imageUrl -> val fixedImageUrl = imageUrl .replace("\\\"", "") .replace("\\/", "/") Page(i, document.location(), fixedImageUrl) } } override fun imageUrlParse(document: Document) = "" override fun imageRequest(page: Page): Request { val newHeaders = headersBuilder() .set("Accept", ACCEPT_IMAGE) .set("Referer", page.url) .build() return GET(page.imageUrl!!, newHeaders) } companion object { private const val ACCEPT = "text/html,application/xhtml+xml,application/xml;q=0.9," + "image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9" private const val ACCEPT_IMAGE = "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8" private const val ACCEPT_LANGUAGE = "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7,es;q=0.6,gl;q=0.5" } }
apache-2.0
a4a37bc6fb1afe0a600c212bcf966367
36.834483
107
0.659679
4.357427
false
false
false
false
JavaEden/Orchid
integrations/OrchidNetlify/src/main/kotlin/com/eden/orchid/netlify/publication/NetlifyPublisher.kt
2
10538
package com.eden.orchid.netlify.publication import com.caseyjbrooks.clog.Clog import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.publication.OrchidPublisher import com.eden.orchid.utilities.OrchidUtils import com.eden.orchid.utilities.makeMillisReadable import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.asRequestBody import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response import org.apache.commons.io.FileUtils import org.json.JSONObject import java.io.File import java.io.IOException import java.net.URL import java.text.SimpleDateFormat import java.time.Duration import java.time.Instant import java.util.ArrayList import javax.inject.Inject import javax.inject.Named import javax.validation.ValidationException import javax.validation.constraints.NotBlank @Description(value = "Upload your site directly to Netlify, while using your favorite CI platform.", name = "Netlify") class NetlifyPublisher @Inject constructor( private val client: OkHttpClient, @Named("dest") private val destinationDir: String, @Named("netlifyToken") @NotBlank(message = "A Netlify Personal Access Token is required for deploys, set as \'netlifyToken\' flag") val netlifyToken: String ) : OrchidPublisher("netlify") { @Option @Description("Your Netlify site ID or domain (ie. orchid.netlify.com, orchid.run). If not provided, your site's baseUrl will be used.") lateinit var siteId: String override fun validate(context: OrchidContext): Boolean { var valid = super.validate(context) if(siteId.isBlank()) { // siteId not provided, use the baseUrl instead try { siteId = URL(context.baseUrl).host } catch (e: Exception) { } } if(siteId.isBlank()) { throw ValidationException("A valid siteId must be provided.") } // make sure the site exists val site = getFrom("sites/$siteId").call(client) if (!site.first) { Clog.e("A Netlify site at {} does not exist or it cannot be accessed.", siteId) valid = false } return valid } override fun publish(context: OrchidContext) { doNetlifyDeploy() } private fun doNetlifyDeploy() { val file = File(destinationDir) val fileMap = mutableMapOf<String, MutableList<Pair<String, File>>>() // create digest of files to be uploaded if (file.exists() && file.isDirectory) { FileUtils.listFiles(file, null, true) .filter { it.isFile } .forEach { val path = OrchidUtils.getRelativeFilename(it.absolutePath, destinationDir) val sha1 = OrchidUtils.sha1(it) fileMap.computeIfAbsent(sha1) { ArrayList() }.add(path to it) } } // post to Netlify to determine which files need to be uploaded still val asyncDeployResponse = startDeploySite(fileMap) // poll Netlify until it has finished determining which files need to be uploaded, or until a timeout is reached val deployResponse = pollUntilDeployIsReady(asyncDeployResponse) if (deployResponse.toUploadTotalCount == 0) { Clog.i("All files up-to-date on Netlify.") } else { uploadRequiredFiles(deployResponse) } } /** * This method will start the Netlify deploy using their async method, which is needed to deploy really large sites. * It will make the initial request, but must then poll for a while until either the site is ready or a timeout is * reached. That timeout is proportional to the number of files being uploaded. */ private fun startDeploySite( files: Map<String, MutableList<Pair<String, File>>> ) : CreateSiteResponse { val body = JSONObject() body.put("async", true) body.put("files", JSONObject().apply { for((sha1, filePairs) in files) { for(filePair in filePairs) { this.put(filePair.first, sha1) } } }) val requiredFilesResponse = body.postTo("sites/$siteId/deploys").call(client) if (!requiredFilesResponse.first) { throw RuntimeException("something went wrong attempting to deploy to Netlify: " + requiredFilesResponse.second) } val required = JSONObject(requiredFilesResponse.second) val deployId = required.getString("id") return CreateSiteResponse( deployId, files, emptyList() ) } /** * Poll for a while until either the site is ready or a timeout is reached. That timeout is proportional to the number of files being uploaded. */ private fun pollUntilDeployIsReady(response: CreateSiteResponse): CreateSiteResponse { val timeout = (30 * 1000) + (response.originalFilesCount * 50) // give timeout of 30s + 50ms * (number of files) val startTime = System.currentTimeMillis() while(true) { val now = System.currentTimeMillis() if((now - startTime) > timeout) break val requiredFilesResponse = getFrom("sites/$siteId/deploys/${response.deployId}").call(client) val required = JSONObject(requiredFilesResponse.second) val deployState = required.getString("state") if(deployState == "prepared" && (required.has("required") || required.has("required_functions"))) { val requiredFiles = required.optJSONArray("required")?.filterNotNull()?.map { it.toString() } ?: emptyList() return response.copy(requiredFiles = requiredFiles) } else { Clog.d(" Deploy still processing, trying again in {}", 5000.makeMillisReadable()) Thread.sleep(5000) } } throw IOException("NetlifyPublisher timed out waiting for site to be ready to upload files") } /** * Upload the required files to Netlify as site files as requested from the initial deploy call. */ private fun uploadRequiredFiles(response: CreateSiteResponse) { response.uploadedFilesCount = 0 // upload all required files Clog.i("Uploading {} files to Netlify.", response.toUploadFilesCount) response .requiredFiles .flatMap { sha1ToUpload -> response.getFiles(sha1ToUpload) } .parallelStream() .forEach { fileToUpload -> val path = OrchidUtils.getRelativeFilename(fileToUpload.absolutePath, destinationDir) Clog.d("Netlify FILE UPLOAD {}/{}: {}", response.uploadedFilesCount + 1, response.toUploadFilesCount, path) fileToUpload.uploadTo("deploys/${response.deployId}/files/$path").call(client) response.uploadedFilesCount++ } } private fun getFrom(url: String, vararg args: Any): Request { val fullURL = Clog.format("$netlifyUrl/$url", *args) Clog.d("Netlify GET: {}", fullURL) return newRequest(fullURL) .get() .build() } private fun JSONObject.postTo(url: String, vararg args: Any): Request { val fullURL = Clog.format("$netlifyUrl/$url", *args) Clog.d("Netlify POST: {}", fullURL) return newRequest(fullURL) .post(this.toString().toRequestBody(JSON)) .build() } private fun File.uploadTo(url: String, vararg args: Any): Request { val fullURL = Clog.format("$netlifyUrl/$url", *args) return newRequest(fullURL) .put(this.asRequestBody(BINARY)) .build() } private fun newRequest(url: String): Request.Builder { return Request.Builder() .url(url) .header("Authorization", "Bearer $netlifyToken") } private fun Request.call(client: OkHttpClient) : Pair<Boolean, String> { val response = client .newCall(this) .execute() .timeoutRateLimit() return try { val bodyString = response.body!!.string() if (!response.isSuccessful) { Clog.e("{}", bodyString) } response.isSuccessful to bodyString } catch (e: Exception) { e.printStackTrace() false to "" } } private fun Response.timeoutRateLimit(): Response { try { val rateLimitLimit = header("X-Ratelimit-Limit")?.toIntOrNull() ?: header("X-RateLimit-Limit")?.toIntOrNull() ?: 1 val rateLimitRemaining = header("X-Ratelimit-Remaining")?.toIntOrNull() ?: header("X-RateLimit-Remaining")?.toIntOrNull() ?: 1 val rateLimitReset = SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").parse(header("X-Ratelimit-Reset")!!).toInstant() val current = Instant.now() val d = Duration.between(rateLimitReset, current) // if we are nearing the rate limit, pause down a bit until it resets if ((rateLimitRemaining * 1.0 / rateLimitLimit * 1.0) < 0.1) { val totalMillis = Math.abs(d.toMillis()) Clog.d(" Rate limit running low, sleeping for {}", totalMillis.makeMillisReadable()) Thread.sleep(totalMillis) } } catch (e: Exception) { } return this } companion object { private val JSON = "application/json; charset=utf-8".toMediaTypeOrNull() private val BINARY = "application/octet-stream".toMediaTypeOrNull() private const val netlifyUrl = "https://api.netlify.com/api/v1" } } private data class CreateSiteResponse( val deployId: String, val originalFiles: Map<String, MutableList<Pair<String, File>>>, val requiredFiles: List<String> ) { val originalFilesCount: Int by lazy { originalFiles.map { it.value.size }.sum() } val originaltotalCount: Int = originalFilesCount val toUploadFilesCount: Int = requiredFiles.size val toUploadTotalCount: Int = toUploadFilesCount var uploadedFilesCount = 0 fun getFiles(sha1: String) : List<File> { return originalFiles.getOrDefault(sha1, ArrayList()).map { it.second } } }
lgpl-3.0
97e2eb339c57832bb9d72ade9e835216
35.846154
147
0.634276
4.679396
false
false
false
false
rhdunn/xquery-intellij-plugin
src/kotlin-intellij/main/uk/co/reecedunn/intellij/plugin/core/serviceContainer/KotlinLazyInstance.kt
1
2384
/* * Copyright (C) 2020 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.core.serviceContainer import com.intellij.diagnostic.PluginException import com.intellij.openapi.application.ApplicationManager @Suppress("UsePropertyAccessSyntax") // getImplementationClassName is not available as a property on IntelliJ <= 2020.1 abstract class KotlinLazyInstance<T> : BaseKeyedLazyInstance<T>() { // region Bean Properties abstract var implementationClass: String override fun getImplementationClassName(): String = implementationClass abstract var fieldName: String // endregion // region Instance private var instance: T? = null override fun getInstance(): T = instance ?: createInstance() private fun createInstance(): T { instance = when { fieldName != "" -> getFieldInstance(getImplementationClassName(), fieldName) getImplementationClassName().endsWith("\$Companion") -> getCompanionObjectInstance() else -> getInstance(ApplicationManager.getApplication(), pluginDescriptor!!) } return instance!! } private fun getCompanionObjectInstance(): T { return getFieldInstance(getImplementationClassName().substringBefore("\$Companion"), "Companion") } private fun getFieldInstance(className: String, fieldName: String): T { try { @Suppress("UNCHECKED_CAST") val aClass = Class.forName(className, true, pluginDescriptor!!.pluginClassLoader) as Class<T> val field = aClass.getDeclaredField(fieldName) field.isAccessible = true @Suppress("UNCHECKED_CAST") return field.get(null) as T } catch (e: Throwable) { throw PluginException(e, pluginDescriptor!!.pluginId) } } // endregion }
apache-2.0
07b597dc7b0ebdf498389c69854810c6
34.58209
119
0.697567
5.171367
false
false
false
false
jiaminglu/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/ir/Ir.kt
1
7876
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.backend.konan.ir import org.jetbrains.kotlin.backend.common.atMostOne import org.jetbrains.kotlin.backend.common.ir.Ir import org.jetbrains.kotlin.backend.common.ir.Symbols import org.jetbrains.kotlin.backend.konan.Context import org.jetbrains.kotlin.backend.konan.ValueType import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.ir.declarations.IrModuleFragment import org.jetbrains.kotlin.ir.util.SymbolTable import org.jetbrains.kotlin.name.Name import kotlin.properties.Delegates // This is what Context collects about IR. internal class KonanIr(context: Context, irModule: IrModuleFragment): Ir<Context>(context, irModule) { val propertiesWithBackingFields = mutableSetOf<PropertyDescriptor>() val originalModuleIndex = ModuleIndex(irModule) lateinit var moduleIndexForCodegen: ModuleIndex override var symbols: KonanSymbols by Delegates.notNull() } internal class KonanSymbols(context: Context, val symbolTable: SymbolTable): Symbols<Context>(context, symbolTable) { val interopNativePointedGetRawPointer = symbolTable.referenceSimpleFunction(context.interopBuiltIns.nativePointedGetRawPointer) val interopCPointerGetRawValue = symbolTable.referenceSimpleFunction(context.interopBuiltIns.cPointerGetRawValue) val interopAllocObjCObject = symbolTable.referenceSimpleFunction(context.interopBuiltIns.allocObjCObject) val interopGetObjCClass = symbolTable.referenceSimpleFunction(context.interopBuiltIns.getObjCClass) val interopObjCObjectInitFromPtr = symbolTable.referenceSimpleFunction(context.interopBuiltIns.objCObjectInitFromPtr) val interopObjCObjectSuperInitCheck = symbolTable.referenceSimpleFunction(context.interopBuiltIns.objCObjectSuperInitCheck) val interopObjCObjectRawValueGetter = symbolTable.referenceSimpleFunction(context.interopBuiltIns.objCObjectRawPtr.getter!!) val interopInvokeImpls = context.interopBuiltIns.invokeImpls.mapValues { (_, function) -> symbolTable.referenceSimpleFunction(function) } val interopInterpretObjCPointer = symbolTable.referenceSimpleFunction(context.interopBuiltIns.interpretObjCPointer) val interopInterpretObjCPointerOrNull = symbolTable.referenceSimpleFunction(context.interopBuiltIns.interpretObjCPointerOrNull) val getNativeNullPtr = symbolTable.referenceSimpleFunction(context.builtIns.getNativeNullPtr) val boxFunctions = ValueType.values().associate { val boxFunctionName = "box${it.classFqName.shortName()}" it to symbolTable.referenceSimpleFunction(context.getInternalFunctions(boxFunctionName).single()) } val boxClasses = ValueType.values().associate { it to symbolTable.referenceClass(context.getInternalClass("${it.classFqName.shortName()}Box")) } val unboxFunctions = ValueType.values().mapNotNull { val unboxFunctionName = "unbox${it.classFqName.shortName()}" context.getInternalFunctions(unboxFunctionName).atMostOne()?.let { descriptor -> it to symbolTable.referenceSimpleFunction(descriptor) } }.toMap() val immutableBinaryBlob = symbolTable.referenceClass( builtInsPackage("konan").getContributedClassifier( Name.identifier("ImmutableBinaryBlob"), NoLookupLocation.FROM_BACKEND ) as ClassDescriptor ) val immutableBinaryBlobOf = symbolTable.referenceSimpleFunction(context.builtIns.immutableBinaryBlobOf) val scheduleImpl = symbolTable.referenceSimpleFunction(context.interopBuiltIns.scheduleImplFunction) val areEqualByValue = context.getInternalFunctions("areEqualByValue").map { symbolTable.referenceSimpleFunction(it) } override val areEqual = symbolTable.referenceSimpleFunction(context.getInternalFunctions("areEqual").single()) override val ThrowNullPointerException = symbolTable.referenceSimpleFunction( context.getInternalFunctions("ThrowNullPointerException").single()) override val ThrowNoWhenBranchMatchedException = symbolTable.referenceSimpleFunction( context.getInternalFunctions("ThrowNoWhenBranchMatchedException").single()) override val ThrowTypeCastException = symbolTable.referenceSimpleFunction( context.getInternalFunctions("ThrowTypeCastException").single()) override val ThrowUninitializedPropertyAccessException = symbolTable.referenceSimpleFunction( context.getInternalFunctions("ThrowUninitializedPropertyAccessException").single() ) override val stringBuilder = symbolTable.referenceClass( builtInsPackage("kotlin", "text").getContributedClassifier( Name.identifier("StringBuilder"), NoLookupLocation.FROM_BACKEND ) as ClassDescriptor ) val checkProgressionStep = context.getInternalFunctions("checkProgressionStep") .map { Pair(it.returnType, symbolTable.referenceSimpleFunction(it)) }.toMap() val getProgressionLast = context.getInternalFunctions("getProgressionLast") .map { Pair(it.returnType, symbolTable.referenceSimpleFunction(it)) }.toMap() val arrayContentToString = arrayTypes.associateBy({ it }, { arrayExtensionFun(it, "contentToString") }) val arrayContentHashCode = arrayTypes.associateBy({ it }, { arrayExtensionFun(it, "contentHashCode") }) override val copyRangeTo = arrays.map { symbol -> val packageViewDescriptor = builtIns.builtInsModule.getPackage(KotlinBuiltIns.COLLECTIONS_PACKAGE_FQ_NAME) val functionDescriptor = packageViewDescriptor.memberScope .getContributedFunctions(Name.identifier("copyRangeTo"), NoLookupLocation.FROM_BACKEND) .first { it.extensionReceiverParameter?.type?.constructor?.declarationDescriptor == symbol.descriptor } symbol.descriptor to symbolTable.referenceSimpleFunction(functionDescriptor) }.toMap() val valuesForEnum = symbolTable.referenceSimpleFunction( context.getInternalFunctions("valuesForEnum").single()) val valueOfForEnum = symbolTable.referenceSimpleFunction( context.getInternalFunctions("valueOfForEnum").single()) val getContinuation = symbolTable.referenceSimpleFunction( context.getInternalFunctions("getContinuation").single()) override val coroutineImpl = symbolTable.referenceClass(context.getInternalClass("CoroutineImpl")) override val coroutineSuspendedGetter = symbolTable.referenceSimpleFunction( builtInsPackage("kotlin", "coroutines", "experimental", "intrinsics") .getContributedVariables(Name.identifier("COROUTINE_SUSPENDED"), NoLookupLocation.FROM_BACKEND) .single().getter!! ) val kLocalDelegatedPropertyImpl = symbolTable.referenceClass(context.reflectionTypes.kLocalDelegatedPropertyImpl) val kLocalDelegatedMutablePropertyImpl = symbolTable.referenceClass(context.reflectionTypes.kLocalDelegatedMutablePropertyImpl) }
apache-2.0
cbcd118f08cc9b1fb32e1027c6c8852e
46.167665
131
0.768029
5.597726
false
false
false
false
Cognifide/APM
app/aem/core/src/main/kotlin/com/cognifide/apm/core/services/async/AsyncScriptExecutor.kt
1
1233
/*- * ========================LICENSE_START================================= * AEM Permission Management * %% * Copyright (C) 2013 Wunderman Thompson Technology * %% * 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. * =========================LICENSE_END================================== */ package com.cognifide.apm.core.services.async import com.cognifide.apm.api.scripts.Script import com.cognifide.apm.api.services.ExecutionMode import org.apache.sling.api.resource.ResourceResolver interface AsyncScriptExecutor { fun process(script: Script, executionMode: ExecutionMode, customDefinitions: Map<String, String>, resourceResolver: ResourceResolver): String fun checkStatus(id: String): ExecutionStatus }
apache-2.0
d9a0e748381c2f4ee15aa625610ed1c8
38.806452
145
0.691809
4.600746
false
false
false
false
apollostack/apollo-android
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/adapter/InputAdapter.kt
1
3547
/* * Generates ResponseAdapters for variables/input */ package com.apollographql.apollo3.compiler.codegen.adapter import com.apollographql.apollo3.api.Optional import com.apollographql.apollo3.api.ResponseAdapter import com.apollographql.apollo3.api.ResponseAdapterCache import com.apollographql.apollo3.api.json.JsonReader import com.apollographql.apollo3.api.json.JsonWriter import com.apollographql.apollo3.compiler.codegen.Identifier import com.apollographql.apollo3.compiler.codegen.Identifier.responseAdapterCache import com.apollographql.apollo3.compiler.codegen.Identifier.toResponse import com.apollographql.apollo3.compiler.codegen.Identifier.value import com.apollographql.apollo3.compiler.codegen.Identifier.writer import com.apollographql.apollo3.compiler.codegen.CgContext import com.apollographql.apollo3.compiler.codegen.helpers.NamedType import com.apollographql.apollo3.compiler.unified.ir.IrOptionalType import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.TypeSpec import com.squareup.kotlinpoet.asClassName import com.squareup.kotlinpoet.asTypeName internal fun List<NamedType>.inputAdapterTypeSpec( context: CgContext, adapterName: String, adaptedTypeName: TypeName, ): TypeSpec { return TypeSpec.objectBuilder(adapterName) .addSuperinterface(ResponseAdapter::class.asTypeName().parameterizedBy(adaptedTypeName)) .addFunction(notImplementedFromResponseFunSpec(adaptedTypeName)) .addFunction(writeToResponseFunSpec(context, adaptedTypeName)) .build() } private fun notImplementedFromResponseFunSpec(adaptedTypeName: TypeName) = FunSpec.builder("fromResponse") .addModifiers(KModifier.OVERRIDE) .addParameter(Identifier.reader, JsonReader::class) .addParameter(responseAdapterCache, ResponseAdapterCache::class.asTypeName()) .returns(adaptedTypeName) .addCode("throw %T(%S)", ClassName("kotlin", "IllegalStateException"), "Input type used in output position") .build() private fun List<NamedType>.writeToResponseFunSpec( context: CgContext, adaptedTypeName: TypeName, ): FunSpec { return FunSpec.builder(toResponse) .addModifiers(KModifier.OVERRIDE) .addParameter(writer, JsonWriter::class.asTypeName()) .addParameter(responseAdapterCache, ResponseAdapterCache::class) .addParameter(value, adaptedTypeName) .addCode(writeToResponseCodeBlock(context)) .build() } private fun List<NamedType>.writeToResponseCodeBlock(context: CgContext): CodeBlock { val builder = CodeBlock.builder() forEach { builder.add(it.writeToResponseCodeBlock(context)) } return builder.build() } private fun NamedType.writeToResponseCodeBlock(context: CgContext): CodeBlock { val adapterInitializer = context.resolver.adapterInitializer(type) val builder = CodeBlock.builder() val propertyName = context.layout.propertyName(graphQlName) if (type is IrOptionalType) { builder.beginControlFlow("if ($value.$propertyName is %T)", Optional.Present::class.asClassName()) } builder.addStatement("$writer.name(%S)", graphQlName) builder.addStatement( "%L.$toResponse($writer, $responseAdapterCache, $value.$propertyName)", adapterInitializer ) if (type is IrOptionalType) { builder.endControlFlow() } return builder.build() }
mit
8f0ac770d0fbbb88fd5449e17204cd99
37.554348
112
0.798421
4.606494
false
false
false
false
MaTriXy/material-dialogs
core/src/main/java/com/afollestad/materialdialogs/list/DialogListExt.kt
2
5101
/** * Designed and developed by Aidan Follestad (@afollestad) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("unused") package com.afollestad.materialdialogs.list import android.content.res.ColorStateList.valueOf import android.graphics.drawable.Drawable import android.graphics.drawable.RippleDrawable import android.os.Build.VERSION.SDK_INT import android.os.Build.VERSION_CODES.LOLLIPOP import android.util.Log import androidx.annotation.ArrayRes import androidx.annotation.CheckResult import androidx.annotation.RestrictTo import androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.LayoutManager import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.R import com.afollestad.materialdialogs.internal.list.PlainListDialogAdapter import com.afollestad.materialdialogs.utils.MDUtil.assertOneSet import com.afollestad.materialdialogs.utils.MDUtil.getStringArray import com.afollestad.materialdialogs.utils.MDUtil.ifNotZero import com.afollestad.materialdialogs.utils.MDUtil.resolveDrawable import com.afollestad.materialdialogs.utils.resolveColor /** * Gets the RecyclerView for a list dialog, if there is one. * * @throws IllegalStateException if the dialog is not a list dialog. */ @CheckResult fun MaterialDialog.getRecyclerView(): RecyclerView { return this.view.contentLayout.recyclerView ?: throw IllegalStateException( "This dialog is not a list dialog." ) } /** A shortcut to [RecyclerView.getAdapter] on [getRecyclerView]. */ @CheckResult fun MaterialDialog.getListAdapter(): RecyclerView.Adapter<*>? { return this.view.contentLayout.recyclerView?.adapter } /** * Sets a custom list adapter to render custom list content. * * Cannot be used in combination with message, input, and some other types of dialogs. */ fun MaterialDialog.customListAdapter( adapter: RecyclerView.Adapter<*>, layoutManager: LayoutManager? = null ): MaterialDialog { this.view.contentLayout.addRecyclerView( dialog = this, adapter = adapter, layoutManager = layoutManager ) return this } /** * @param res The string array resource to populate the list with. * @param items The literal string array to populate the list with. * @param waitForPositiveButton When true, the [selection] listener won't be called until an item * is selected and the positive action button is pressed. Defaults to true if the dialog has buttons. * @param selection A listener invoked when an item in the list is selected. */ @CheckResult fun MaterialDialog.listItems( @ArrayRes res: Int? = null, items: List<CharSequence>? = null, disabledIndices: IntArray? = null, waitForPositiveButton: Boolean = true, selection: ItemListener = null ): MaterialDialog { assertOneSet("listItems", items, res) val array = items ?: windowContext.getStringArray(res).toList() if (getListAdapter() != null) { Log.w("MaterialDialogs", "Prefer calling updateListItems(...) over listItems(...) again.") return updateListItems( res = res, items = items, disabledIndices = disabledIndices, selection = selection ) } return customListAdapter( PlainListDialogAdapter( dialog = this, items = array, disabledItems = disabledIndices, waitForPositiveButton = waitForPositiveButton, selection = selection ) ) } /** * Updates the items, and optionally the disabled indices, of a plain list dialog. * * @author Aidan Follestad (@afollestad) */ fun MaterialDialog.updateListItems( @ArrayRes res: Int? = null, items: List<CharSequence>? = null, disabledIndices: IntArray? = null, selection: ItemListener = null ): MaterialDialog { assertOneSet("updateListItems", items, res) val array = items ?: windowContext.getStringArray(res).toList() val adapter = getListAdapter() check(adapter is PlainListDialogAdapter) { "updateListItems(...) can't be used before you've created a plain list dialog." } adapter.replaceItems(array, selection) disabledIndices?.let(adapter::disableItems) return this } /** @author Aidan Follestad (@afollestad) */ @RestrictTo(LIBRARY_GROUP) fun MaterialDialog.getItemSelector(): Drawable? { val drawable = resolveDrawable(context = context, attr = R.attr.md_item_selector) if (SDK_INT >= LOLLIPOP && drawable is RippleDrawable) { resolveColor(attr = R.attr.md_ripple_color).ifNotZero { drawable.setColor(valueOf(it)) } } return drawable }
apache-2.0
37ad137a7b38651658ba0781d4218a65
34.423611
104
0.750833
4.514159
false
false
false
false
PolymerLabs/arcs
java/arcs/core/host/AbstractArcHost.kt
1
18865
/* * 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.core.host import arcs.core.common.ArcId import arcs.core.data.Plan import arcs.core.entity.Handle import arcs.core.host.api.Particle import arcs.core.storage.StorageKey import arcs.core.util.LruCacheMap import arcs.core.util.Scheduler import arcs.core.util.TaggedLog import arcs.core.util.guardedBy import arcs.core.util.withTaggedTimeout import kotlin.coroutines.CoroutineContext import kotlinx.atomicfu.atomic import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.awaitAll import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock typealias ParticleConstructor = suspend (Plan.Particle?) -> Particle typealias ParticleRegistration = Pair<ParticleIdentifier, ParticleConstructor> /** * Base helper class for [ArcHost] implementations. * * Subclasses of [AbstractArcHost] may provide platform dependent functionality such as for * (JS, Android, WASM). Another type of [ArcHost] are those specialized for different * [Particle] execution environments within a platform such as isolatable [ArcHosts] (dev-mode * and prod-mode), ArcHosts embedded into Android Services, and remote ArcHosts which run on * other devices. * * @property handleManagerFactory An object that builds [HandleManager]s. * @property arcHostContextSerializer Serializing [ArcHostContext]s, often for storage. By default, * it will not serialize. * @param initialParticles The initial set of [Particle]s that this host contains. */ @OptIn(ExperimentalCoroutinesApi::class) abstract class AbstractArcHost( /** * This coroutineContext is used to create a [CoroutineScope] that will be used to launch * Arc resurrection jobs and shut down the Arc when errors occur in different contexts. */ coroutineContext: CoroutineContext, private val handleManagerFactory: HandleManagerFactory, private val arcHostContextSerializer: ArcHostContextSerializer = NoOpArcHostContextSerializer(), vararg initialParticles: ParticleRegistration ) : ArcHost { private val log = TaggedLog { "AbstractArcHost" } private val particleConstructors: MutableMap<ParticleIdentifier, ParticleConstructor> = mutableMapOf() private val cacheMutex = Mutex() /** In memory cache of [ArcHostContext] state. */ private val contextCache: MutableMap<String, ArcHostContext> by guardedBy( cacheMutex, LruCacheMap() ) private val runningMutex = Mutex() /** Arcs currently running in memory. */ private val runningArcs: MutableMap<String, RunningArc> by guardedBy( runningMutex, mutableMapOf() ) private var paused = atomic(false) /** Arcs to be started after unpausing. */ private val pausedArcs: MutableList<Plan.Partition> = mutableListOf() // There can be more then one instance of a host, hashCode is used to disambiguate them. override val hostId = "${this.hashCode()}" // TODO: add lifecycle API for ArcHosts shutting down to cancel running coroutines private val auxiliaryScope = CoroutineScope(coroutineContext) /** * Time limit in milliseconds for all particles to reach the Running state during startup. * Public and mutable for testing. * TODO(mykmartin): use a better approach for this; companion object causes build issues, * ctor argument is awkward to use in individual tests */ var particleStartupTimeoutMs = 60_000L init { initialParticles.toList().associateByTo(particleConstructors, { it.first }, { it.second }) } private suspend fun putContextCache(id: String, context: ArcHostContext) = cacheMutex.withLock { contextCache[id] = context } private suspend fun clearContextCache() = cacheMutex.withLock { contextCache.clear() } private suspend fun removeContextCache(arcId: String) = cacheMutex.withLock { contextCache.remove(arcId) } private suspend fun getContextCache(arcId: String) = cacheMutex.withLock { contextCache[arcId] } /** * Determines if [arcId] is currently running. It's state must be [ArcState.Running] and * it must be memory resident (not serialized and dormant). */ private suspend fun isRunning(arcId: String) = runningMutex.withLock { runningArcs[arcId]?.context?.arcState == ArcState.Running } /** * Lookup the [ArcHostContext] associated with the [ArcId] in [partition] and return its * [ArcState]. **/ override suspend fun lookupArcHostStatus(partition: Plan.Partition) = lookupOrCreateArcHostContext(partition.arcId).arcState override suspend fun pause() { if (!paused.compareAndSet(false, true)) { return } val running = runningMutex.withLock { runningArcs.toMap() } running.forEach { (arcId, runningArc) -> try { val partition = contextToPartition(arcId, runningArc.context) stopArc(partition) pausedArcs.add(partition) } catch (e: Exception) { // TODO(b/160251910): Make logging detail more cleanly conditional. log.debug(e) { "Failure stopping arc." } log.info { "Failure stopping arc." } } } /** Wait until all [runningArcs] are stopped and their [ArcHostContext]s are serialized. */ arcHostContextSerializer.drainSerializations() } override suspend fun unpause() { if (!paused.compareAndSet(true, false)) { return } pausedArcs.forEach { try { startArc(it) } catch (e: Exception) { // TODO(b/160251910): Make logging detail more cleanly conditional. log.debug(e) { "Failure starting arc." } log.info { "Failure starting arc." } } } pausedArcs.clear() /** * Wait until all [pausedArcs]s are started or resurrected and * their [ArcHostContext]s are serialized. */ arcHostContextSerializer.drainSerializations() } override suspend fun shutdown() { pause() runningMutex.withLock { runningArcs.clear() } clearContextCache() pausedArcs.clear() arcHostContextSerializer.cancel() auxiliaryScope.cancel() handleManagerFactory.cancel() } /** * This property is true if this [ArcHost] has no running, memory resident arcs, e.g. * running [Particle]s with active connected [Handle]s. */ protected suspend fun isArcHostIdle() = runningMutex.withLock { runningArcs.isEmpty() } override suspend fun waitForArcIdle(arcId: String) { while (true) { getRunningArc(arcId)?.handleManager?.allStorageProxies()?.forEach { it.waitForIdle() } if (arcIsIdle(arcId)) { return } } } /** * Returns whether or not the arc for a given [arcId] is idle. If the arc is not currently * running, or doesn't exist at all, this method will return true. */ suspend fun arcIsIdle(arcId: String) = getRunningArc(arcId) ?.handleManager ?.allStorageProxies() ?.all { it.isIdle() } ?: true // VisibleForTesting suspend fun clearCache() { // Ensure all contexts are flushed onto storage prior to clear context cache. arcHostContextSerializer.drainSerializations() clearContextCache() runningMutex.withLock { runningArcs.clear() } } /** Used by subclasses to register particles dynamically after [ArcHost] construction */ protected fun registerParticle(particle: ParticleIdentifier, constructor: ParticleConstructor) { particleConstructors.put(particle, constructor) } /** Used by subclasses to unregister particles dynamically after [ArcHost] construction. */ protected fun unregisterParticle(particle: ParticleIdentifier) { particleConstructors.remove(particle) } /** Returns a list of all [ParticleIdentifier]s this [ArcHost] can instantiate. */ override suspend fun registeredParticles(): List<ParticleIdentifier> = particleConstructors.keys.toList() // VisibleForTesting protected suspend fun getArcHostContext(arcId: String) = getContextCache(arcId) protected suspend fun lookupOrCreateArcHostContext( arcId: String ): ArcHostContext = getContextCache(arcId) ?: arcHostContextSerializer.readContextFromStorage( createArcHostContext(arcId), hostId ).also { putContextCache(arcId, it) } suspend fun getRunningArc(arcId: String) = runningMutex.withLock { runningArcs[arcId] } suspend fun removeRunningArc(arcId: String) = runningMutex.withLock { runningArcs.remove(arcId) } private fun createArcHostContext(arcId: String) = ArcHostContext( arcId = arcId ) override suspend fun addOnArcStateChange( arcId: ArcId, block: ArcStateChangeCallback ): ArcStateChangeRegistration { val registration = ArcStateChangeRegistration(arcId, block) val context = lookupOrCreateArcHostContext(arcId.toString()) return context.addOnArcStateChange( registration, block ).also { block(arcId, context.arcState) } } override suspend fun removeOnArcStateChange(registration: ArcStateChangeRegistration) { lookupOrCreateArcHostContext(registration.arcId()).removeOnArcStateChange(registration) } /** * Called to persist [ArcHostContext] after [context] for [arcId] has been modified. */ protected suspend fun updateArcHostContext(arcId: String, runningArc: RunningArc) { val context = runningArc.context putContextCache(arcId, context) arcHostContextSerializer.writeContextToStorage(context, hostId) runningMutex.withLock { if (context.arcState == ArcState.Running) { runningArcs[arcId] = runningArc } else { runningArcs.remove(arcId) } } } override suspend fun startArc(partition: Plan.Partition) { val runningArc = getRunningArc(partition.arcId) ?: run { val context = lookupOrCreateArcHostContext(partition.arcId) RunningArc(context, entityHandleManager(partition.arcId)) } val context = runningArc.context if (paused.value) { pausedArcs.add(partition) return } // If the arc is already running or has been deleted, don't restart it. // TODO: Ensure this can't race once arcs are actually moved to the Deleted state if (isRunning(partition.arcId) || context.arcState == ArcState.Deleted) { return } for (idx in partition.particles.indices) { val particleSpec = partition.particles[idx] val existingParticleContext = context.particles.elementAtOrNull(idx) val particleContext = setUpParticleAndHandles(partition, particleSpec, existingParticleContext, runningArc) if (context.particles.size > idx) { context.setParticle(idx, particleContext) } else { context.addParticle(particleContext) } if (particleContext.particleState.failed) { context.arcState = ArcState.errorWith(particleContext.particleState.cause) break } } // Get each particle running. if (context.arcState != ArcState.Error) { try { performParticleStartup(context.particles, runningArc.handleManager.scheduler()) // TODO(b/164914008): Exceptions in handle lifecycle methods are caught on the // StorageProxy scheduler context, then communicated here via the callback attached with // setErrorCallbackForHandleEvents in setUpParticleAndHandles. Unfortunately that doesn't // prevent the startup process continuing (i.e. the awaiting guard in performParticleStartup // will still be completed), so we need to check for the error state here as well. The // proposed lifecycle refactor should make this much cleaner. if (context.arcState != ArcState.Error) { context.arcState = ArcState.Running // If the platform supports resurrection, request it for this Arc's StorageKeys maybeRequestResurrection(context) } } catch (e: Exception) { context.arcState = ArcState.errorWith(e) // TODO(b/160251910): Make logging detail more cleanly conditional. log.debug(e) { "Failure performing particle startup." } log.info { "Failure performing particle startup." } } } else { stopArc(partition) } updateArcHostContext(partition.arcId, runningArc) } /** * Instantiates a [Particle] by looking up an associated [ParticleConstructor], allocates * all of the [Handle]s connected to it, and returns a [ParticleContext] indicating the * current lifecycle state of the particle. */ protected suspend fun setUpParticleAndHandles( partition: Plan.Partition, spec: Plan.Particle, existingParticleContext: ParticleContext?, runningArc: RunningArc ): ParticleContext { val context = runningArc.context val particle = instantiateParticle(ParticleIdentifier.from(spec.location), spec) val particleContext = existingParticleContext?.copyWith(particle) ?: ParticleContext(particle, spec) if (particleContext.particleState == ParticleState.MaxFailed) { // Don't try recreating the particle anymore. return particleContext } // Create the handles and register them with the ParticleContext. On construction, readable // handles notify their underlying StorageProxy's that they will be synced at a later // time by the ParticleContext state machine. particle.createAndSetHandles(partition, runningArc.handleManager, spec, immediateSync = false) .forEach { handle -> val onError: (Exception) -> Unit = { error -> context.arcState = ArcState.errorWith(error) auxiliaryScope.launch { stopArc(partition) } } particleContext.registerHandle(handle, onError) handle.getProxy().setErrorCallbackForHandleEvents(onError) } return particleContext } /** * Invokes the [Particle] startup lifecycle methods and waits until all particles * have reached the Running state. */ private suspend fun performParticleStartup( particleContexts: Collection<ParticleContext>, scheduler: Scheduler ) { if (particleContexts.isEmpty()) return // Call the lifecycle startup methods. particleContexts.forEach { it.initParticle(scheduler) } val awaiting = particleContexts.map { it.runParticleAsync(scheduler) } withTaggedTimeout(particleStartupTimeoutMs, { "waiting for all particles to be ready" }) { awaiting.awaitAll() } } /** * Lookup [StorageKey]s used in the current [ArcHostContext] and potentially register them * with a [ResurrectorService], so that this [ArcHost] is instructed to automatically * restart in the event of a crash. */ protected open fun maybeRequestResurrection(context: ArcHostContext) = Unit /** * Inform [ResurrectorService] to cancel requests for resurrection for the [StorageKey]s in * this [ArcHostContext]. */ protected open fun maybeCancelResurrection(context: ArcHostContext) = Unit /** Helper used by implementors of [ResurrectableHost]. */ @Suppress("UNUSED_PARAMETER") suspend fun onResurrected(arcId: String, affectedKeys: List<StorageKey>) { if (isRunning(arcId)) { return } val context = lookupOrCreateArcHostContext(arcId) val partition = contextToPartition(arcId, context) startArc(partition) } private fun contextToPartition(arcId: String, context: ArcHostContext) = Plan.Partition( arcId, hostId, context.particles.map { it.planParticle } ) override suspend fun stopArc(partition: Plan.Partition) { val arcId = partition.arcId removeRunningArc(arcId)?.let { runningArc -> when (runningArc.context.arcState) { ArcState.Running, ArcState.Indeterminate -> stopArcInternal(arcId, runningArc) ArcState.NeverStarted -> stopArcError(runningArc, "Arc $arcId was never started") ArcState.Stopped -> stopArcError(runningArc, "Arc $arcId already stopped") ArcState.Deleted -> stopArcError(runningArc, "Arc $arcId is deleted.") ArcState.Error -> stopArcError(runningArc, "Arc $arcId encountered an error.") } } } /** * If an attempt to [ArcHost.stopArc] fails, this method should report the error message. * For example, throw an exception or log. */ @Suppress("UNUSED_PARAMETER", "RedundantSuspendModifier") private suspend fun stopArcError(runningArc: RunningArc, message: String) { log.debug { "Error stopping arc: $message" } val context = runningArc.context try { runningArc.context.particles.forEach { try { it.stopParticle(runningArc.handleManager.scheduler()) } catch (e: Exception) { log.debug(e) { "Error stopping particle $it" } } } maybeCancelResurrection(context) updateArcHostContext(context.arcId, runningArc) } finally { removeContextCache(context.arcId) runningArc.handleManager.close() } } /** * Stops an [Arc], stopping all running [Particle]s, cancelling pending resurrection requests, * releasing [Handle]s, and modifying [ArcState] and [ParticleState] to stopped states. */ private suspend fun stopArcInternal(arcId: String, runningArc: RunningArc) { val context = runningArc.context try { context.particles.forEach { it.stopParticle(runningArc.handleManager.scheduler()) } maybeCancelResurrection(context) context.arcState = ArcState.Stopped updateArcHostContext(arcId, runningArc) } finally { runningArc.handleManager.close() } } override suspend fun isHostForParticle(particle: Plan.Particle) = registeredParticles().contains(ParticleIdentifier.from(particle.location)) /** * Return an instance of [HandleManagerImpl] to be used to create [Handle]s. */ fun entityHandleManager(arcId: String): HandleManager = handleManagerFactory.build(arcId, hostId) /** * Instantiate a [Particle] implementation for a given [ParticleIdentifier]. * * @property identifier a [ParticleIdentifier] from a [Plan.Particle] spec */ open suspend fun instantiateParticle( identifier: ParticleIdentifier, spec: Plan.Particle? ): Particle { return particleConstructors[identifier]?.invoke(spec) ?: throw IllegalArgumentException("Particle $identifier not found.") } /** * A simple structure that combines the [ArcHostContext] of an Arc with its active * [HandleManager], resident in memory. These are maintained in the `residentArcs` structure. */ class RunningArc( val context: ArcHostContext, val handleManager: HandleManager ) }
bsd-3-clause
d6667810067942d0ee3ea17bd09ba439
34.261682
100
0.715028
4.769912
false
false
false
false
abigpotostew/easypolitics
db/src/test/kotlin/bz/bracken/stewart/db/mongodb/DebugDatabase.kt
1
1170
package bz.bracken.stewart.db.mongodb import bz.stewart.bracken.db.bill.data.Bill import bz.stewart.bracken.db.bill.database.mongodb.BillMongoDb import bz.stewart.bracken.db.database.mongo.DefaultMongoClient import mu.KLogging /** * Created by stew on 3/9/17. */ class DebugDatabase(dbName: String = "congress1" ) : BillMongoDb(DefaultMongoClient(dbName)) { override fun getCollectionName(): String { return "bills115" } companion object: KLogging() fun testDbConnection() { logger.info{"============================================================"} logger.info{"Testing DB - Start"} logger.info{"============================================================"} this.queryCollection(getCollectionName(), { val res: Bill? = find()?.first() if (res?.bill_id == "hconres1-115") { logger.info{"SUCCESS -- queried test data"} } //println(res) }) logger.info{"============================================================"} logger.info{"Testing DB - End"} logger.info{"============================================================"} } }
apache-2.0
febcfe626c9f2082929f87066d5ff383
32.457143
81
0.496581
4.661355
false
true
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/JoinParameterListIntention.kt
2
3372
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiComment import com.intellij.psi.PsiDocumentManager import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaContext import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaHelper import org.jetbrains.kotlin.idea.formatter.trailingComma.TrailingCommaState import org.jetbrains.kotlin.idea.util.reformatted import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset abstract class AbstractJoinListIntention<TList : KtElement, TElement : KtElement>( listClass: Class<TList>, elementClass: Class<TElement>, textGetter: () -> String ) : AbstractChopListIntention<TList, TElement>(listClass, elementClass, textGetter) { override fun isApplicableTo(element: TList, caretOffset: Int): Boolean { val elements = element.elements() if (elements.isEmpty()) return false if (!isApplicableCaretOffset(caretOffset, element)) return false return (hasLineBreakBefore(elements.first()) || elements.any { hasLineBreakAfter(it) }) && element.allChildren.none { it is PsiComment && it.node.elementType == KtTokens.EOL_COMMENT } } override fun applyTo(element: TList, editor: Editor?) { val document = editor?.document ?: return val elements = element.elements() val pointer = element.createSmartPointer() elements.forEach { it.reformatted() } nextBreak(elements.last())?.let { document.deleteString(it.startOffset, it.endOffset) } elements.dropLast(1).asReversed().forEach { tElement -> nextBreak(tElement)?.let { document.replaceString(it.startOffset, it.endOffset, " ") } } prevBreak(elements.first())?.let { document.deleteString(it.startOffset, it.endOffset) } val project = element.project val documentManager = PsiDocumentManager.getInstance(project) documentManager.commitDocument(document) val listElement = pointer.element as? KtElement if (listElement != null && TrailingCommaContext.create(listElement).state == TrailingCommaState.REDUNDANT) { TrailingCommaHelper.trailingCommaOrLastElement(listElement)?.delete() } } } class JoinParameterListIntention : AbstractJoinListIntention<KtParameterList, KtParameter>( KtParameterList::class.java, KtParameter::class.java, KotlinBundle.lazyMessage("put.parameters.on.one.line") ) { override fun isApplicableTo(element: KtParameterList, caretOffset: Int): Boolean { if (element.parent is KtFunctionLiteral) return false return super.isApplicableTo(element, caretOffset) } } class JoinArgumentListIntention : AbstractJoinListIntention<KtValueArgumentList, KtValueArgument>( KtValueArgumentList::class.java, KtValueArgument::class.java, KotlinBundle.lazyMessage("put.arguments.on.one.line") )
apache-2.0
e2d1755ae6c0ec4facdd197ad0edbfac
44.567568
158
0.749407
4.702929
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/KotlinTestRunLineMarkerContributor.kt
1
6250
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.highlighter import com.intellij.execution.TestStateStorage import com.intellij.execution.lineMarker.ExecutorAction import com.intellij.execution.lineMarker.RunLineMarkerContributor import com.intellij.psi.PsiElement import com.intellij.util.Function import org.jetbrains.kotlin.idea.base.util.module import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.configuration.isGradleModule import org.jetbrains.kotlin.idea.platform.tooling import org.jetbrains.kotlin.idea.base.lineMarkers.run.KotlinMainFunctionLocatingService import org.jetbrains.kotlin.idea.testIntegration.framework.KotlinTestFramework import org.jetbrains.kotlin.idea.util.isUnderKotlinSourceRootTypes import org.jetbrains.kotlin.konan.target.HostManager import org.jetbrains.kotlin.konan.target.KonanTarget import org.jetbrains.kotlin.platform.SimplePlatform import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.idePlatformKind import org.jetbrains.kotlin.platform.isMultiPlatform import org.jetbrains.kotlin.platform.konan.NativePlatformWithTarget import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClass import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.utils.addToStdlib.safeAs import javax.swing.Icon class KotlinTestRunLineMarkerContributor : RunLineMarkerContributor() { companion object { /** * Users may want to try to run that individual test, for example to check if it still fails because of some third party problem, * but it's not executed when a whole class or test package run. * * On other side Gradle has its own built-in support for JUnit but doesn't allow fine-tuning behaviour. * As of now launching ignored tests (for Gradle) is impossible. */ private fun KtNamedDeclaration.isIgnoredForGradleModule(includeSlowProviders: Boolean): Boolean { val ktNamedFunction = this.safeAs<KtNamedFunction>().takeIf { module?.isGradleModule() == true } ?: return false val testFramework = KotlinTestFramework.getApplicableFor(this, includeSlowProviders) return testFramework?.isIgnoredMethod(ktNamedFunction) == true } fun getTestStateIcon(urls: List<String>, declaration: KtNamedDeclaration): Icon { val testStateStorage = TestStateStorage.getInstance(declaration.project) val isClass = declaration is KtClass val state: TestStateStorage.Record? = run { for (url in urls) { testStateStorage.getState(url)?.let { return@run it } } null } return getTestStateIcon(state, isClass) } fun SimplePlatform.providesRunnableTests(): Boolean { if (this is NativePlatformWithTarget) { return when { HostManager.hostIsMac -> target in listOf( KonanTarget.IOS_X64, KonanTarget.MACOS_X64, KonanTarget.WATCHOS_X64, KonanTarget.WATCHOS_X86, KonanTarget.TVOS_X64 ) HostManager.hostIsLinux -> target == KonanTarget.LINUX_X64 HostManager.hostIsMingw -> target in listOf(KonanTarget.MINGW_X86, KonanTarget.MINGW_X64) else -> false } } return true } fun TargetPlatform.providesRunnableTests(): Boolean = componentPlatforms.any { it.providesRunnableTests() } } override fun getInfo(element: PsiElement): Info? = calculateIcon(element, false) override fun getSlowInfo(element: PsiElement): Info? = calculateIcon(element, true) private fun calculateIcon( element: PsiElement, includeSlowProviders: Boolean ): Info? { val declaration = element.getStrictParentOfType<KtNamedDeclaration>()?.takeIf { it.nameIdentifier == element } ?: return null val targetPlatform = declaration.module?.platform ?: return null if (declaration is KtNamedFunction) { if (declaration.containingClassOrObject == null || targetPlatform.isMultiPlatform() && declaration.containingClass() == null) return null } else { if (declaration !is KtClassOrObject || targetPlatform.isMultiPlatform() && declaration !is KtClass ) return null } if (!targetPlatform.providesRunnableTests()) return null if (!declaration.isUnderKotlinSourceRootTypes()) return null val icon = targetPlatform.idePlatformKind.tooling.getTestIcon( declaration = declaration, descriptorProvider = { declaration.resolveToDescriptorIfAny() }, includeSlowProviders = includeSlowProviders )?.takeUnless { declaration.isIgnoredForGradleModule(includeSlowProviders) } ?: return null return Info( icon, Function { KotlinBundle.message("highlighter.tool.tip.text.run.test") }, *ExecutorAction.getActions(getOrder(declaration)) ) } private fun getOrder(declaration: KtNamedDeclaration): Int { val mainFunctionDetector = KotlinMainFunctionLocatingService.getInstance() if (declaration is KtClassOrObject && mainFunctionDetector.hasMain(declaration.companionObjects)) { return 1 } if (declaration is KtNamedFunction) { val declarations = declaration.containingClassOrObject?.declarations ?: return 0 if (mainFunctionDetector.hasMain(declarations)) return 1 return 0 } val file = declaration.containingFile return if (file is KtFile && mainFunctionDetector.hasMain(file.declarations)) 1 else 0 } }
apache-2.0
c188d9553896aa68d134967391039d94
44.289855
137
0.69312
5.34645
false
true
false
false
EmmanuelMess/AmazeFileManager
app/src/main/java/com/amaze/filemanager/ui/views/preference/PathSwitchPreference.kt
2
2210
/* * Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.ui.views.preference import android.content.Context import android.view.View import androidx.annotation.IdRes import androidx.preference.Preference import androidx.preference.PreferenceViewHolder import com.amaze.filemanager.R /** @author Emmanuel on 17/4/2017, at 22:22. */ class PathSwitchPreference(context: Context?) : Preference(context) { var lastItemClicked = -1 private set init { widgetLayoutResource = R.layout.namepathswitch_preference } override fun onBindViewHolder(holder: PreferenceViewHolder?) { holder?.itemView.let { view -> setListener(view, R.id.edit, EDIT) setListener(view, R.id.delete, DELETE) view?.setOnClickListener(null) } // Keep this before things that need changing what's on screen super.onBindViewHolder(holder) } private fun setListener(v: View?, @IdRes id: Int, elem: Int): View.OnClickListener { val l = View.OnClickListener { lastItemClicked = elem onPreferenceClickListener.onPreferenceClick(this) } v?.findViewById<View>(id)?.setOnClickListener(l) return l } companion object { const val EDIT = 0 const val DELETE = 1 } }
gpl-3.0
3fb6b73bd33b2ab53d2a8051894394b2
33.53125
107
0.70181
4.367589
false
false
false
false
DuncanCasteleyn/DiscordModBot
src/main/kotlin/be/duncanc/discordmodbot/bot/services/IAmRoles.kt
1
20065
/* * Copyright 2018 Duncan Casteleyn * * 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 be.duncanc.discordmodbot.bot.services import be.duncanc.discordmodbot.bot.commands.CommandModule import be.duncanc.discordmodbot.bot.sequences.MessageSequence import be.duncanc.discordmodbot.bot.sequences.Sequence import be.duncanc.discordmodbot.data.entities.IAmRolesCategory import be.duncanc.discordmodbot.data.services.IAmRolesService import be.duncanc.discordmodbot.data.services.UserBlockService import net.dv8tion.jda.api.MessageBuilder import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.MessageChannel import net.dv8tion.jda.api.entities.Role import net.dv8tion.jda.api.entities.TextChannel import net.dv8tion.jda.api.entities.User import net.dv8tion.jda.api.events.ReadyEvent import net.dv8tion.jda.api.events.message.MessageReceivedEvent import net.dv8tion.jda.api.events.role.RoleDeleteEvent import net.dv8tion.jda.api.exceptions.PermissionException import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component import java.util.concurrent.TimeUnit @Component class IAmRoles @Autowired constructor( private val iAmRolesService: IAmRolesService, userBlockService: UserBlockService ) : CommandModule( ALIASES, null, DESCRIPTION, userBlockService = userBlockService ) { companion object { private val ALIASES = arrayOf("IAmRoles") private const val DESCRIPTION = "Controller for IAmRoles." private val ALIASES_I_AM_NOT = arrayOf("IAmNot") private const val DESCRIPTION_I_AM_NOT = "Will start a sequence that allows you to remove roles from yourself." private val ALIASES_I_AM = arrayOf("IAm") private const val DESCRIPTION_I_AM = "Will start a sequence that allows you to assign yourself roles." } private val subCommands = arrayOf(IAm(), IAmNot()) public override fun commandExec(event: MessageReceivedEvent, command: String, arguments: String?) { event.jda.addEventListener(IAmRolesSequence(event.author, event.channel)) } override fun onRoleDelete(event: RoleDeleteEvent) { iAmRolesService.removeRole(event.guild.idLong, event.role.idLong) } inner class IAmRolesSequence internal constructor(user: User, channel: MessageChannel) : Sequence(user, channel), MessageSequence { private var sequenceNumber: Byte = 1 private var newCategoryName: String? = null private var iAmRolesCategory: IAmRolesCategory? = null private val iAmRolesCategories: List<IAmRolesCategory> init { if (channel !is TextChannel) { super.destroy() throw UnsupportedOperationException("This command must be executed in a guild.") } if (channel.guild.getMember(user)?.hasPermission(Permission.MANAGE_ROLES) != true) { throw PermissionException("You do not have permission to modify IAmRoles categories.") } iAmRolesCategories = iAmRolesService.getAllCategoriesForGuild(channel.guild.idLong) super.channel.sendMessage( "Please select which action you want to perform:\n" + "0. Add a new category\n" + "1. Remove an existing category\n" + "2. Modify an existing category" ).queue { message -> super.addMessageToCleaner(message) } } override fun onMessageReceivedDuringSequence(event: MessageReceivedEvent) { when (sequenceNumber) { 1.toByte() -> when (java.lang.Byte.parseByte(event.message.contentRaw)) { 0.toByte() -> { super.channel.sendMessage("Please enter a unique category name.") .queue { message -> super.addMessageToCleaner(message) } sequenceNumber = 2 } 1.toByte() -> { if (iAmRolesCategories.isEmpty()) { throw IllegalStateException("No categories have been set up, there is nothing to delete.") } val deleteCategoryMessage = MessageBuilder().append("Please select which role category you'd like to delete.") for (i in iAmRolesCategories.indices) { deleteCategoryMessage.append('\n').append(i).append(". ") .append(iAmRolesCategories[i].categoryName) } deleteCategoryMessage.buildAll(MessageBuilder.SplitPolicy.NEWLINE).forEach { message -> super.channel.sendMessage(message).queue { message1 -> super.addMessageToCleaner(message1) } } sequenceNumber = 3 } 2.toByte() -> { if (iAmRolesCategories.isEmpty()) { throw IllegalStateException("No categories have been set up, there is nothing to modify.") } val modifyCategoryMessage = MessageBuilder().append("Please select which role category you'd like to modify.") for (i in iAmRolesCategories.indices) { modifyCategoryMessage.append('\n').append(i).append(". ") .append(iAmRolesCategories[i].categoryName) } modifyCategoryMessage.buildAll(MessageBuilder.SplitPolicy.NEWLINE) .forEach { super.channel.sendMessage(it).queue { super.addMessageToCleaner(it) } } sequenceNumber = 4 } else -> channel.sendMessage("Wrong answer please answer with a valid number").queue { super.addMessageToCleaner( it ) } } 2.toByte() -> if (newCategoryName == null) { val existingCategoryNames = iAmRolesService.getExistingCategoryNames(event.guild.idLong) if (existingCategoryNames.contains(event.message.contentRaw)) { throw IllegalArgumentException("The name you provided is already being used.") } newCategoryName = event.message.contentRaw super.channel.sendMessage("Please enter how much roles a user can have from this category? Use 0 for unlimited.") .queue { super.addMessageToCleaner(it) } } else { synchronized(iAmRolesCategories) { iAmRolesService.addNewCategory( event.guild.idLong, newCategoryName!!, event.message.contentRaw.toInt() ) } super.channel.sendMessage(user.asMention + " Successfully added new category.") .queue { message -> message.delete().queueAfter(1, TimeUnit.MINUTES) } super.destroy() } 3.toByte() -> { synchronized(iAmRolesCategories) { iAmRolesService.removeCategory( event.guild.idLong, iAmRolesCategories[event.message.contentRaw.toInt()].categoryId!! ) } super.channel.sendMessage(user.asMention + " Successfully removed the category") .queue { message -> message.delete().queueAfter(1, TimeUnit.MINUTES) } super.destroy() } 4.toByte() -> { iAmRolesCategory = iAmRolesCategories.elementAt(Integer.parseInt(event.message.contentRaw)) super.channel.sendMessage( "Please enter the number of the action you'd like to perform.\n" + "0. Modify the name. Current value: " + iAmRolesCategory!!.categoryName + "\n" + "1. Change how much roles you can assign from the category. Current value: " + iAmRolesCategory!!.allowedRoles + "\n" + "2. Add or remove roles." ).queue { super.addMessageToCleaner(it) } sequenceNumber = 5 } 5.toByte() -> when (java.lang.Byte.parseByte(event.message.contentRaw)) { 0.toByte() -> { super.channel.sendMessage("Please enter a new name for the category.") .queue { message -> super.addMessageToCleaner(message) } sequenceNumber = 6 } 1.toByte() -> { super.channel.sendMessage("Please enter a new value for the amount of allowed roles.") .queue { super.addMessageToCleaner(it) } sequenceNumber = 8 } 2.toByte() -> { super.channel.sendMessage("Please enter the full name of the role you'd like to remove or add. This will automatically detect if the role is already in the list and remove or add it.") .queue { super.addMessageToCleaner(it) } sequenceNumber = 7 } } 6.toByte() -> { iAmRolesService.changeCategoryName( event.guild.idLong, iAmRolesCategory!!.categoryId!!, event.message.contentStripped ) super.channel.sendMessage("Name successfully changed.") .queue { message -> message.delete().queueAfter(1, TimeUnit.MINUTES) } super.destroy() } 7.toByte() -> { val matchedRoles = (super.channel as TextChannel).guild.getRolesByName(event.message.contentRaw, true) when { matchedRoles.size > 1 -> throw IllegalArgumentException("The role name you provided matches multiple roles and is not supported by !IAm and !IaANot") matchedRoles.isEmpty() -> throw IllegalArgumentException("Could not find any roles with that name") else -> { val roleId = matchedRoles[0].idLong when (iAmRolesService.addOrRemoveRole( event.guild.idLong, iAmRolesCategory!!.categoryId!!, roleId )) { false -> super.channel.sendMessage(user.asMention + " The role was successfully removed form the category.") .queue { it.delete().queueAfter(1, TimeUnit.MINUTES) } true -> super.channel.sendMessage(user.asMention + " The role was successfully added to the category.") .queue { it.delete().queueAfter(1, TimeUnit.MINUTES) } } super.destroy() } } } 8.toByte() -> { iAmRolesService.changeAllowedRoles( event.guild.idLong, iAmRolesCategory!!.categoryId!!, event.message.contentRaw.toInt() ) channel.sendMessage(user.asMention + " Allowed roles successfully changed.") .queue { it.delete().queueAfter(1, TimeUnit.MINUTES) } super.destroy() } } } } override fun onReady(event: ReadyEvent) { event.jda.addEventListener(*subCommands) } /** * Iam command to assign yourself roles. */ internal inner class IAm : CommandModule(ALIASES_I_AM, null, DESCRIPTION_I_AM) { public override fun commandExec(event: MessageReceivedEvent, command: String, arguments: String?) { event.jda.addEventListener(RoleModificationSequence(event.author, event.channel, remove = false)) } } /** * I am not command to allow users to remove roles from them self. */ internal inner class IAmNot : CommandModule(ALIASES_I_AM_NOT, null, DESCRIPTION_I_AM_NOT) { public override fun commandExec(event: MessageReceivedEvent, command: String, arguments: String?) { event.jda.addEventListener(RoleModificationSequence(event.author, event.channel, remove = true)) } } internal inner class RoleModificationSequence(user: User, channel: MessageChannel, private val remove: Boolean) : Sequence(user, channel, cleanAfterSequence = true, informUser = true), MessageSequence { private val iAmRolesCategories: List<IAmRolesCategory> private var roles: ArrayList<Long>? = null private var assignedRoles: ArrayList<Role>? = null private var selectedCategory: Int = -1 init { if (channel !is TextChannel) { super.destroy() throw UnsupportedOperationException("This command must be executed in a guild.") } iAmRolesCategories = iAmRolesService.getAllCategoriesForGuild(channel.guild.idLong) val message = MessageBuilder() if (remove) { message.append(user.asMention + " Please select from which category you'd like to remove roles.") } else { message.append(user.asMention + " Please select from which category you'd like to assign (a) role(s).") } for (i in iAmRolesCategories.indices) { message.append('\n').append(i).append(". ").append(iAmRolesCategories[i].categoryName) } message.buildAll(MessageBuilder.SplitPolicy.NEWLINE) .forEach { super.channel.sendMessage(it).queue { super.addMessageToCleaner(it) } } } override fun onMessageReceivedDuringSequence(event: MessageReceivedEvent) { when (roles) { null -> { selectedCategory = event.message.contentRaw.toInt() roles = ArrayList( iAmRolesService.getRoleIds( event.guild.idLong, iAmRolesCategories[selectedCategory].categoryId!! ) ) if (roles!!.isEmpty()) { throw IllegalStateException("There are no roles in this category. Please contact a server admin.") } assignedRoles = ArrayList(event.member!!.roles) val notMutableRoles = roles!! assignedRoles!!.removeIf { assignedRole -> notMutableRoles.none { it == assignedRole.idLong } } roles!!.removeIf { roleId -> assignedRoles!!.any { it.idLong == roleId } } val message = MessageBuilder(user.asMention) message.append(" Please select which role(s) you'd like to ") .append(if (remove) "remove" else "add") .append(". For multiple roles put each number on a new line (shift enter).\n") val maxAssignableRoles = iAmRolesCategories[selectedCategory].allowedRoles - assignedRoles!!.size if (!remove) { message.append("You are allowed to select up to ") .append(if (iAmRolesCategories[selectedCategory].allowedRoles > 0) maxAssignableRoles else "unlimited") .append(" role(s) from this category") } if (remove) { if (assignedRoles!!.isEmpty()) { throw IllegalStateException("You have no roles to remove from this category.") } for (i in assignedRoles!!.indices) { message.append('\n').append(i).append(". ").append(assignedRoles!![i].name) } } else { if (roles!!.isEmpty()) { throw IllegalStateException("You already have all the roles from this category.") } else if (iAmRolesCategories[selectedCategory].allowedRoles > 0 && maxAssignableRoles <= 0) { throw IllegalStateException("You already have the max amount of roles you can assign for this category.") } for (i in roles!!.indices) { val role = (channel as TextChannel).guild.getRoleById(roles!![i]) message.append('\n').append(i).append(". ").append(role?.name) } } message.buildAll(MessageBuilder.SplitPolicy.NEWLINE) .forEach { super.channel.sendMessage(it).queue { super.addMessageToCleaner(it) } } } else -> { val requestedRoles = event.message.contentRaw.split('\n') if (requestedRoles.isEmpty()) { throw IllegalArgumentException("You need to provide at least one role to " + if (remove) "remove" else "assign." + ".") } if (!remove && requestedRoles.size > iAmRolesCategories[selectedCategory].allowedRoles - assignedRoles!!.size && iAmRolesCategories[selectedCategory].allowedRoles > 0) { throw IllegalArgumentException("You listed more roles than allowed.") } val rRoles = HashSet<Role>() requestedRoles.forEach { if (remove) { rRoles.add(assignedRoles!![it.toInt()]) } else { val id = this.roles!![it.toInt()] rRoles.add(event.guild.getRoleById(id)!!) } } val member = event.guild.getMember(user)!! if (remove) { event.guild.modifyMemberRoles(member, null, rRoles).reason("User used !iam command").queue() } else { event.guild.modifyMemberRoles(member, rRoles, null).reason("User used !iam command").queue() } channel.sendMessage(user.asMention + " The requested role(s) were/was " + if (remove) "removed" else "added.") .queue { it.delete().queueAfter(1, TimeUnit.MINUTES) } super.destroy() } } } } }
apache-2.0
bdf624f82ae33d3cf840191168f5dced
52.082011
208
0.540992
5.737775
false
false
false
false
android/architecture-components-samples
PagingWithNetworkSample/lib/src/main/java/com/android/example/paging/pagingwithnetwork/reddit/ui/PostsAdapter.kt
1
2881
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.example.paging.pagingwithnetwork.reddit.ui import android.view.ViewGroup import androidx.paging.PagingDataAdapter import androidx.recyclerview.widget.DiffUtil import com.android.example.paging.pagingwithnetwork.GlideRequests import com.android.example.paging.pagingwithnetwork.reddit.vo.RedditPost /** * A simple adapter implementation that shows Reddit posts. */ class PostsAdapter(private val glide: GlideRequests) : PagingDataAdapter<RedditPost, RedditPostViewHolder>(POST_COMPARATOR) { override fun onBindViewHolder(holder: RedditPostViewHolder, position: Int) { holder.bind(getItem(position)) } override fun onBindViewHolder( holder: RedditPostViewHolder, position: Int, payloads: MutableList<Any> ) { if (payloads.isNotEmpty()) { val item = getItem(position) holder.updateScore(item) } else { onBindViewHolder(holder, position) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RedditPostViewHolder { return RedditPostViewHolder.create(parent, glide) } companion object { private val PAYLOAD_SCORE = Any() val POST_COMPARATOR = object : DiffUtil.ItemCallback<RedditPost>() { override fun areContentsTheSame(oldItem: RedditPost, newItem: RedditPost): Boolean = oldItem == newItem override fun areItemsTheSame(oldItem: RedditPost, newItem: RedditPost): Boolean = oldItem.name == newItem.name override fun getChangePayload(oldItem: RedditPost, newItem: RedditPost): Any? { return if (sameExceptScore(oldItem, newItem)) { PAYLOAD_SCORE } else { null } } } private fun sameExceptScore(oldItem: RedditPost, newItem: RedditPost): Boolean { // DON'T do this copy in a real app, it is just convenient here for the demo :) // because reddit randomizes scores, we want to pass it as a payload to minimize // UI updates between refreshes return oldItem.copy(score = newItem.score) == newItem } } }
apache-2.0
1c9b47fcbcf855a89b2a095453333d26
36.415584
96
0.666435
5.019164
false
false
false
false
npryce/robots
webui/src/main/kotlin/dnd/DragAndDrop.kt
1
7740
package dnd import browser.Touch import browser.TouchEvent import browser.TouchId import browser.TouchList import browser.get import org.w3c.dom.CustomEvent import org.w3c.dom.CustomEventInit import org.w3c.dom.Element import org.w3c.dom.HTMLElement import org.w3c.dom.Node import org.w3c.dom.css.ElementCSSInlineStyle import org.w3c.dom.events.Event import org.w3c.dom.events.MouseEvent import kotlin.browser.document class DragStartDetail( var data: Any? = null, var element: HTMLElement? = null, var elementOrigin: Point? = null, var notifyDragStop: ()->Unit = {} ) class DragInDetail( val data: Any, var acceptable: Boolean = false ) class DropDetail( val data: Any, var accepted: Boolean = false ) internal const val DND_DRAG_START = "dnd-drag-start" internal const val DND_DRAG_IN = "dnd-drag-in" internal const val DND_DRAG_OUT = "dnd-drag-out" internal const val DND_DROP = "dnd-drop" private fun eventInit(detail: Any?) = CustomEventInit(bubbles = true, cancelable = true, detail = detail) @Suppress("FunctionName") fun DragStartEvent(detail: DragStartDetail) = CustomEvent(DND_DRAG_START, eventInit(detail)) @Suppress("FunctionName") fun DragInEvent(detail: DragInDetail) = CustomEvent(DND_DRAG_IN, eventInit(detail)) @Suppress("FunctionName") fun DragOutEvent() = Event(DND_DRAG_OUT, eventInit(true)) @Suppress("FunctionName") fun DropEvent(detail: DropDetail) = CustomEvent(DND_DROP, eventInit(detail)) private fun ElementCSSInlineStyle.setPosition(p: Point) { style.left = "${p.x}px" style.top = "${p.y}px" } private val animationEndEvents = listOf("animationend", "animationcancel", "transitionend", "transitioncancel") private class DragState( val data: Any, val sourceElement: Element, val draggedElement: HTMLElement, val draggedElementOrigin: Point, val gestureOrigin: Point, val touchId: TouchId?, val notifyDragStop: () -> Unit, var dropTarget: Element? = null ) internal inline fun <reified T : Node> T.deepClone() = cloneNode(true) as T object DragAndDrop { private var dragState: DragState? = null private fun startDragging(target: Element, pageX: Double, pageY: Double, touchId: TouchId? = null) = startDragging(target, Point(pageX, pageY), touchId) private fun startDragging(target: Element, startPosition: Point, touchId: TouchId? = null): Boolean { dragState?.draggedElement?.remove() val dragDetail = DragStartDetail() target.dispatchEvent(DragStartEvent(dragDetail)) val draggedData = dragDetail.data ?: return false val draggedElement = dragDetail.element ?: return false val sourcePos = dragDetail.elementOrigin ?: return false draggedElement.apply { classList.add("dragging") setPosition(sourcePos) } dragState = DragState( data = draggedData, sourceElement = target, draggedElement = draggedElement, draggedElementOrigin = sourcePos, gestureOrigin = startPosition, touchId = touchId, notifyDragStop = dragDetail.notifyDragStop) document.body?.appendChild(draggedElement) return true } private fun dragTo(pageX: Double, pageY: Double) { dragTo(Point(pageX, pageY)) } private fun dragTo(pagePos: Point) { val dragState = this.dragState ?: return // if drag_state is null, drag must have been cancelled val dropTarget = dragState.dropTarget dragState.draggedElement.setPosition(dragState.draggedElementOrigin + (pagePos - dragState.gestureOrigin)) val under = document.elementFromPoint(pagePos.x, pagePos.y) if (under == dropTarget) return if (dropTarget != null) { dropTarget.dispatchEvent(DragOutEvent()) dragState.dropTarget = null } if (under != null) { val dragInDetail = DragInDetail(dragState.data) under.dispatchEvent(DragInEvent(dragInDetail)) if (dragInDetail.acceptable) { dragState.dropTarget = under } } } private fun drop() { val dragState = this.dragState ?: return val dropTarget = dragState.dropTarget val draggedElement = dragState.draggedElement val dropIsAccepted = if (dropTarget != null) { val dropDetail = DropDetail(dragState.data) dropTarget.dispatchEvent(DropEvent(dropDetail)) dropDetail.accepted } else { false } animationEndEvents.forEach { eventName -> draggedElement.addEventListener(eventName, {draggedElement.remove()}) } if (dropIsAccepted) { draggedElement.remove() } else { draggedElement.classList.add("rejected") } dragState.notifyDragStop() this.dragState = null } private fun bodyMouseDown(ev: Event) { ev as MouseEvent if (ev.button.toInt() == 0 && startDragging(ev.target as HTMLElement, ev.pageX, ev.pageY)) { ev.preventDefault() document.body?.addEventListener("mousemove", ::bodyMouseDrag, true) } } private fun bodyMouseDrag(ev: Event) { ev as MouseEvent if (dragState != null) { ev.preventDefault() dragTo(ev.pageX, ev.pageY) } } private fun bodyMouseUp(ev: Event) { ev as MouseEvent if (dragState != null) { ev.preventDefault() document.body?.removeEventListener("mousemove", ::bodyMouseDrag, true) drop() } } private fun TouchList.touchWithId(id: TouchId): Touch? { return (0 until length) .map { i -> this[i] } .find { it.identifier == id } } private fun TouchList.containsTouchWithId(id: TouchId): Boolean { return touchWithId(id) != null } private fun bodyTouchStart(ev: Event) { ev as TouchEvent val touch = ev.changedTouches[0] if (startDragging(touch.target, touch.pageX, touch.pageY, touch.identifier)) { ev.preventDefault() document.body?.addEventListener("touchmove", ::bodyTouchDrag, true) } } private fun bodyTouchDrag(ev: Event) { ev as TouchEvent val dragState = this.dragState ?: return val touchId = dragState.touchId ?: return val touch = ev.changedTouches.touchWithId(touchId) ?: return ev.preventDefault() dragTo(touch.pageX, touch.pageY) } private fun bodyTouchEnd(ev: Event) { ev as TouchEvent val dragState = this.dragState ?: return val touchId = dragState.touchId ?: return if (ev.changedTouches.containsTouchWithId(touchId)) { ev.preventDefault() document.body?.removeEventListener("touchmove", ::bodyTouchDrag, true) drop() } } fun activate() { val body = document.body ?: return body.addEventListener("mousedown", ::bodyMouseDown) body.addEventListener("mouseup", ::bodyMouseUp) body.addEventListener("touchstart", ::bodyTouchStart) body.addEventListener("touchend", ::bodyTouchEnd) body.addEventListener("touchcancel", ::bodyTouchEnd) } } internal inline fun <reified T> Event.detail(): T? = (this as? CustomEvent)?.detail as? T
gpl-3.0
2ba52a3e01f53a601f24a266578925d8
29.840637
114
0.622868
4.502618
false
false
false
false
Major-/Vicis
modern/src/test/kotlin/rs/emulate/modern/codec/VersionedContainerTest.kt
1
1694
package rs.emulate.modern.codec import io.netty.buffer.Unpooled import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test import rs.emulate.modern.codec.VersionedContainer.Companion.readVersionedContainer class VersionedContainerTest { @Test fun read() { val data = Unpooled.wrappedBuffer("Hello, world!".toByteArray()) val trailer = Unpooled.buffer() trailer.writeShort(1337) val buf = Unpooled.wrappedBuffer(data, trailer) val container = buf.readVersionedContainer() assertEquals(data, container.getBuffer()) assertEquals(1337, container.version) } @Test fun `read empty`() { assertThrows(IllegalArgumentException::class.java) { Unpooled.EMPTY_BUFFER.readVersionedContainer() } } @Test fun `read single byte`() { val buf = Unpooled.buffer() buf.writeByte(0x00) assertThrows(IllegalArgumentException::class.java) { buf.readVersionedContainer() } } @Test fun write() { val data = Unpooled.wrappedBuffer("Hello, world!".toByteArray()) val trailer = Unpooled.buffer() trailer.writeShort(1337) val buf = Unpooled.wrappedBuffer(data, trailer) val container = VersionedContainer(data, 1337) assertEquals(buf, container.write()) } @Test fun checksum() { val data = Unpooled.wrappedBuffer("The quick brown fox jumps over the lazy dog".toByteArray()) val container = VersionedContainer(data, 0) assertEquals(0x414FA339, container.checksum) } }
isc
768dcb11b676740a253fb3623e777950
26.322581
102
0.664109
4.615804
false
true
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/common/view/PetMessagePopup.kt
1
3204
package io.ipoli.android.common.view import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import io.ipoli.android.R import io.ipoli.android.common.AppSideEffectHandler import io.ipoli.android.common.AppState import io.ipoli.android.common.BaseViewStateReducer import io.ipoli.android.common.redux.Action import io.ipoli.android.common.redux.BaseViewState import io.ipoli.android.pet.AndroidPetAvatar import io.ipoli.android.pet.PetAvatar import io.ipoli.android.player.data.Player import kotlinx.android.synthetic.main.popup_pet_message.view.* import space.traversal.kapsule.required import java.util.concurrent.TimeUnit data class PetMessageViewState( val message: String? = null, val petAvatar: PetAvatar? = null ) : BaseViewState() sealed class PetMessageAction : Action { data class Load(val message: String) : PetMessageAction() data class PlayerLoaded(val player: Player) : PetMessageAction() } object PetMessageSideEffectHandler : AppSideEffectHandler() { private val playerRepository by required { playerRepository } override suspend fun doExecute(action: Action, state: AppState) { if (action is PetMessageAction.Load) { dispatch(PetMessageAction.PlayerLoaded(playerRepository.find()!!)) } } override fun canHandle(action: Action) = action is PetMessageAction.Load } object PetMessageReducer : BaseViewStateReducer<PetMessageViewState>() { override val stateKey = key<PetMessageViewState>() override fun reduce( state: AppState, subState: PetMessageViewState, action: Action ) = when (action) { is PetMessageAction.Load -> subState.copy(message = action.message) is PetMessageAction.PlayerLoaded -> subState.copy(petAvatar = action.player.pet.avatar) else -> subState } override fun defaultState() = PetMessageViewState(message = null, petAvatar = null) } class PetMessagePopup( private val message: String, private val actionListener: () -> Unit = {}, private val actionText: String = "" ) : ReduxPopup<PetMessageAction, PetMessageViewState, PetMessageReducer>( position = ReduxPopup.Position.BOTTOM, isAutoHide = true ) { override val reducer = PetMessageReducer override fun createView(inflater: LayoutInflater): View { @SuppressLint("InflateParams") val v = inflater.inflate(R.layout.popup_pet_message, null) if (actionText.isNotBlank()) { v.petAction.text = actionText } v.petAction.setOnClickListener { actionListener() hide() } return v } override fun onCreateLoadAction() = PetMessageAction.Load(message) override fun onViewShown(contentView: View) { autoHideAfter(TimeUnit.SECONDS.toMillis(3)) } override fun render(state: PetMessageViewState, view: View) { state.message?.let { view.petMessage.text = it } state.petAvatar?.let { val androidAvatar = AndroidPetAvatar.valueOf(it.name) view.petHead.setImageResource(androidAvatar.headImage) } } }
gpl-3.0
3ecf2e99d0e5421e161fc66113888de8
29.235849
99
0.704744
4.677372
false
false
false
false
JavaEden/Orchid-Core
plugins/OrchidWiki/src/main/kotlin/com/eden/orchid/wiki/pages/WikiBookResource.kt
2
1803
package com.eden.orchid.wiki.pages import com.eden.orchid.api.resources.resource.OrchidResource import com.eden.orchid.api.theme.pages.OrchidReference import com.eden.orchid.utilities.convertOutputStream import com.eden.orchid.wiki.model.WikiSection import com.openhtmltopdf.pdfboxout.PdfRendererBuilder import com.openhtmltopdf.svgsupport.BatikSVGDrawer import org.jsoup.Jsoup import org.jsoup.helper.W3CDom import java.io.InputStream import java.util.regex.Pattern class WikiBookResource( reference: OrchidReference, val section: WikiSection ) : OrchidResource(reference) { override fun getContentStream(): InputStream { val wikiBookTemplate = reference.context.getTemplateResourceSource(null, reference.context.theme).getResourceEntry(reference.context, "wiki/book")!! val pdfOutput = wikiBookTemplate.compileContent(reference.context, mapOf( "section" to section, "resource" to this@WikiBookResource )) val doc = Jsoup.parse(pdfOutput) val pdfDoc = W3CDom().fromJsoup(doc) return convertOutputStream(reference.context) { safeOs -> PdfRendererBuilder() .useSVGDrawer(BatikSVGDrawer()) .withW3cDocument(pdfDoc, reference.context.baseUrl) .toStream(safeOs) .run() } } fun replaceBaseUrls(input: String): String { val pattern = "href=\"(${Pattern.quote(reference.context.baseUrl)}(.*?))\"".toRegex() return pattern.replace(input) { match -> val formattedId = match.groupValues[2].replace("/", "_") "href=\"#$formattedId\"" } } fun formatAnchor(input: String): String { return input.replace(reference.context.baseUrl, "").replace("/", "_") } }
mit
37bd41d79f4c93a1404b6507d4d69269
35.06
156
0.678314
4.28266
false
false
false
false
GunoH/intellij-community
python/python-features-trainer/src/com/jetbrains/python/ift/lesson/completion/PythonPostfixCompletionLesson.kt
10
1519
// 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.jetbrains.python.ift.lesson.completion import com.jetbrains.python.ift.PythonLessonsBundle import training.dsl.LearningDslBase import training.dsl.LessonSample import training.dsl.parseLessonSample import training.learn.lesson.general.completion.PostfixCompletionLesson class PythonPostfixCompletionLesson : PostfixCompletionLesson() { override val sample: LessonSample = parseLessonSample(""" movies_dict = { 'title': 'Aviator', 'year': '2005', 'director': 'Martin Scorsese', 'distributor': 'Miramax Films' } movies_dict.get('year')<caret> """.trimIndent()) override val result: String = parseLessonSample(""" movies_dict = { 'title': 'Aviator', 'year': '2005', 'director': 'Martin Scorsese', 'distributor': 'Miramax Films' } if movies_dict.get('year') is not None: <caret> """.trimIndent()).text override val completionSuffix: String = ".if" override val completionItem: String = "ifnn" override fun LearningDslBase.getTypeTaskText(): String { return PythonLessonsBundle.message("python.postfix.completion.type", code(completionSuffix)) } override fun LearningDslBase.getCompleteTaskText(): String { return PythonLessonsBundle.message("python.postfix.completion.complete", code(completionItem), action("EditorChooseLookupItem")) } }
apache-2.0
5282000e355331f7901661fabbc29c53
33.545455
140
0.714944
4.390173
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/projectActions/RemoveSelectedProjectsAction.kt
2
1988
// 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.wm.impl.welcomeScreen.projectActions import com.intellij.ide.IdeBundle import com.intellij.ide.RecentProjectsManager import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.ui.Messages import com.intellij.openapi.wm.impl.welcomeScreen.cloneableProjects.CloneableProjectsService import com.intellij.openapi.wm.impl.welcomeScreen.recentProjects.* /** * @author Konstantin Bulenkov */ internal class RemoveSelectedProjectsAction : RecentProjectsWelcomeScreenActionBase() { init { isEnabledInModalContext = true // To allow to delete items from the Manage Recent Projects modal dialog, see IDEA-302750 } override fun actionPerformed(event: AnActionEvent) { val item = getSelectedItem(event) ?: return removeItem(item) } override fun update(event: AnActionEvent) { event.presentation.isEnabled = getSelectedItem(event) != null } companion object { fun removeItem(item: RecentProjectTreeItem) { val recentProjectsManager = RecentProjectsManager.getInstance() val cloneableProjectsService = CloneableProjectsService.getInstance() val exitCode = Messages.showYesNoDialog( IdeBundle.message("dialog.message.remove.0.from.recent.projects.list", item.displayName()), IdeBundle.message("dialog.title.remove.recent.project"), IdeBundle.message("button.remove"), IdeBundle.message("button.cancel"), Messages.getQuestionIcon() ) if (exitCode == Messages.OK) { when (item) { is ProjectsGroupItem -> recentProjectsManager.removeGroup(item.group) is RecentProjectItem -> recentProjectsManager.removePath(item.projectPath) is CloneableProjectItem -> cloneableProjectsService.removeCloneableProject(item.cloneableProject) is RootItem -> {} } } } } }
apache-2.0
f6d74171f143adb866cbceb35647a360
38
125
0.743964
4.733333
false
false
false
false
CzBiX/v2ex-android
app/src/main/kotlin/com/czbix/v2ex/parser/Parser.kt
1
4818
package com.czbix.v2ex.parser import android.text.Spanned import android.text.style.ImageSpan import androidx.core.text.getSpans import com.czbix.v2ex.BuildConfig import com.czbix.v2ex.db.Member import com.czbix.v2ex.helper.JsoupObjects import com.czbix.v2ex.model.Avatar import com.czbix.v2ex.model.ContentBlock import com.czbix.v2ex.model.Node import com.czbix.v2ex.util.MiscUtils import com.czbix.v2ex.util.ViewUtils import org.jsoup.Jsoup import org.jsoup.nodes.Document import org.jsoup.nodes.Element abstract class Parser { companion object { @JvmStatic fun toDoc(html: String): Document { val document = Jsoup.parse(html) if (!BuildConfig.DEBUG) { val settings = document.outputSettings().prettyPrint(false) document.outputSettings(settings) } return document } @JvmStatic fun parseOnceCode(html: String): String { val doc = toDoc(html) val ele = JsoupObjects(doc).body().child("#Wrapper").child(".content").child(".box") .child(".cell").dfs("form").dfs("input[name=once]").first() return ele.`val`() } @JvmStatic fun parseSignInForm(html: String): SignInFormData { val doc = toDoc(html) val form = JsoupObjects(doc).body().child("#Wrapper").child(".content").child(".box") .child(".cell").dfs("form").first() val name = JsoupObjects(form).dfs("input[type=text]").first() val once = JsoupObjects(form).dfs("input[name=once]").first() val password = once.nextElementSibling() val captcha = JsoupObjects(form).dfs("input.sl").last() check(password.tagName() == "input") return SignInFormData( name.attr("name"), password.attr("name"), once.`val`(), captcha.attr("name") ) } @JvmStatic fun parseNode(nodeEle: Element): Node { val title = nodeEle.text() val url = nodeEle.attr("href") val name = Node.getNameFromUrl(url) return Node.Builder().setTitle(title).setName(name).createNode() } @JvmStatic protected fun parseMember(td: Element): Member { val memberBuilder = Member.Builder() var ele = td.child(0) // get member url check(ele.tagName() == "a") val url = ele.attr("href") memberBuilder.username = Member.getNameFromUrl(url) // get member avatar ele = ele.child(0) val avatarBuilder = Avatar.Builder() check(ele.tagName() == "img") avatarBuilder.setUrl(ele.attr("src")) memberBuilder.avatar = avatarBuilder.build() return memberBuilder.build() } fun parseHtml2Blocks(html: String): List<ContentBlock> { val builder = ViewUtils.parseHtml(html, null, true) if (builder !is Spanned) { val block = ContentBlock.TextBlock(0, builder) return listOf(block) } val spans = builder.getSpans<Any>() var lastEndPos = 0 var index = 0 val blocks = mutableListOf<ContentBlock>() for (span in spans) { if (span !is ImageSpan && span !is PreKind) { continue } val start = builder.getSpanStart(span) val text = builder.subSequence(lastEndPos, start).trim() if (text.isNotEmpty()) { blocks.add(ContentBlock.TextBlock(index++, text)) } val end by lazy { builder.getSpanEnd(span) } if (span is ImageSpan) { val url = MiscUtils.formatUrl(span.source!!) blocks.add(ContentBlock.ImageBlock(index++, url)) } else { val preText = builder.subSequence(start, end - 1) blocks.add(ContentBlock.PreBlock(index++, preText)) } lastEndPos = end } val length = builder.length if (lastEndPos != length) { val text = builder.subSequence(lastEndPos, length).trim() blocks.add(ContentBlock.TextBlock(index, text)) } return blocks } } enum class PageType { Tab, Node, /** * Topic page in mobile style */ Topic, } class PreKind data class SignInFormData(val username: String, val password: String, val once: String, val captcha: String) }
apache-2.0
309df2558f5d6bf56e21cb37e8c11e24
30.907285
97
0.543794
4.6238
false
false
false
false
mdanielwork/intellij-community
jvm/jvm-analysis-kotlin-tests/testData/codeInspection/scheduledForRemoval/ScheduledForRemovalElementsIgnoreImportsTest.kt
1
7175
import pkg.AnnotatedClass import pkg.AnnotatedClass.NON_ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS import pkg.AnnotatedClass.staticNonAnnotatedMethodInAnnotatedClass import pkg.AnnotatedClass.ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS import pkg.AnnotatedClass.staticAnnotatedMethodInAnnotatedClass import pkg.NonAnnotatedClass import pkg.NonAnnotatedClass.NON_ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS import pkg.NonAnnotatedClass.staticNonAnnotatedMethodInNonAnnotatedClass import pkg.NonAnnotatedClass.ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS import pkg.NonAnnotatedClass.staticAnnotatedMethodInNonAnnotatedClass import pkg.AnnotatedEnum import pkg.NonAnnotatedEnum import pkg.AnnotatedEnum.NON_ANNOTATED_VALUE_IN_ANNOTATED_ENUM import pkg.AnnotatedEnum.ANNOTATED_VALUE_IN_ANNOTATED_ENUM import pkg.NonAnnotatedEnum.NON_ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM import pkg.NonAnnotatedEnum.ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM import pkg.AnnotatedAnnotation import pkg.NonAnnotatedAnnotation import annotatedPkg.ClassInAnnotatedPkg @Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE", "UNUSED_VALUE") class ScheduledForRemovalElementsIgnoreImportsTest { fun test() { var s = <warning descr="'AnnotatedClass' is scheduled for removal">AnnotatedClass</warning>.NON_ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS <warning descr="'AnnotatedClass' is scheduled for removal">AnnotatedClass</warning>.staticNonAnnotatedMethodInAnnotatedClass() val annotatedClassInstanceViaNonAnnotatedConstructor : <warning descr="'AnnotatedClass' is scheduled for removal">AnnotatedClass</warning> = AnnotatedClass() s = annotatedClassInstanceViaNonAnnotatedConstructor.nonAnnotatedFieldInAnnotatedClass annotatedClassInstanceViaNonAnnotatedConstructor.nonAnnotatedMethodInAnnotatedClass() s = NON_ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS staticNonAnnotatedMethodInAnnotatedClass() s = <warning descr="'AnnotatedClass' is scheduled for removal">AnnotatedClass</warning>.<warning descr="'ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS' is scheduled for removal">ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS</warning> <warning descr="'AnnotatedClass' is scheduled for removal">AnnotatedClass</warning>.<warning descr="'staticAnnotatedMethodInAnnotatedClass' is scheduled for removal">staticAnnotatedMethodInAnnotatedClass</warning>() val annotatedClassInstanceViaAnnotatedConstructor : <warning descr="'AnnotatedClass' is scheduled for removal">AnnotatedClass</warning> = <warning descr="'AnnotatedClass' is scheduled for removal">AnnotatedClass</warning>("") s = annotatedClassInstanceViaAnnotatedConstructor.<warning descr="'annotatedFieldInAnnotatedClass' is scheduled for removal">annotatedFieldInAnnotatedClass</warning> annotatedClassInstanceViaAnnotatedConstructor.<warning descr="'annotatedMethodInAnnotatedClass' is scheduled for removal">annotatedMethodInAnnotatedClass</warning>() s = <warning descr="'ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS' is scheduled for removal">ANNOTATED_CONSTANT_IN_ANNOTATED_CLASS</warning> <warning descr="'staticAnnotatedMethodInAnnotatedClass' is scheduled for removal">staticAnnotatedMethodInAnnotatedClass</warning>() // --------------------------------- s = NonAnnotatedClass.NON_ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS NonAnnotatedClass.staticNonAnnotatedMethodInNonAnnotatedClass() val nonAnnotatedClassInstanceViaNonAnnotatedConstructor = NonAnnotatedClass() s = nonAnnotatedClassInstanceViaNonAnnotatedConstructor.nonAnnotatedFieldInNonAnnotatedClass nonAnnotatedClassInstanceViaNonAnnotatedConstructor.nonAnnotatedMethodInNonAnnotatedClass() s = NON_ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS staticNonAnnotatedMethodInNonAnnotatedClass() s = NonAnnotatedClass.<warning descr="'ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS' is scheduled for removal">ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS</warning> NonAnnotatedClass.<warning descr="'staticAnnotatedMethodInNonAnnotatedClass' is scheduled for removal">staticAnnotatedMethodInNonAnnotatedClass</warning>() val nonAnnotatedClassInstanceViaAnnotatedConstructor = <warning descr="'NonAnnotatedClass' is scheduled for removal">NonAnnotatedClass</warning>("") s = nonAnnotatedClassInstanceViaAnnotatedConstructor.<warning descr="'annotatedFieldInNonAnnotatedClass' is scheduled for removal">annotatedFieldInNonAnnotatedClass</warning> nonAnnotatedClassInstanceViaAnnotatedConstructor.<warning descr="'annotatedMethodInNonAnnotatedClass' is scheduled for removal">annotatedMethodInNonAnnotatedClass</warning>() s = <warning descr="'ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS' is scheduled for removal">ANNOTATED_CONSTANT_IN_NON_ANNOTATED_CLASS</warning> <warning descr="'staticAnnotatedMethodInNonAnnotatedClass' is scheduled for removal">staticAnnotatedMethodInNonAnnotatedClass</warning>() // --------------------------------- var nonAnnotatedValueInAnnotatedEnum : <warning descr="'AnnotatedEnum' is scheduled for removal">AnnotatedEnum</warning> = <warning descr="'AnnotatedEnum' is scheduled for removal">AnnotatedEnum</warning>.NON_ANNOTATED_VALUE_IN_ANNOTATED_ENUM nonAnnotatedValueInAnnotatedEnum = NON_ANNOTATED_VALUE_IN_ANNOTATED_ENUM var annotatedValueInAnnotatedEnum : <warning descr="'AnnotatedEnum' is scheduled for removal">AnnotatedEnum</warning> = <warning descr="'AnnotatedEnum' is scheduled for removal">AnnotatedEnum</warning>.<warning descr="'ANNOTATED_VALUE_IN_ANNOTATED_ENUM' is scheduled for removal">ANNOTATED_VALUE_IN_ANNOTATED_ENUM</warning> annotatedValueInAnnotatedEnum = <warning descr="'ANNOTATED_VALUE_IN_ANNOTATED_ENUM' is scheduled for removal">ANNOTATED_VALUE_IN_ANNOTATED_ENUM</warning> var nonAnnotatedValueInNonAnnotatedEnum = NonAnnotatedEnum.NON_ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM nonAnnotatedValueInNonAnnotatedEnum = NON_ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM var annotatedValueInNonAnnotatedEnum = NonAnnotatedEnum.<warning descr="'ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM' is scheduled for removal">ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM</warning> annotatedValueInNonAnnotatedEnum = <warning descr="'ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM' is scheduled for removal">ANNOTATED_VALUE_IN_NON_ANNOTATED_ENUM</warning> // --------------------------------- @<warning descr="'AnnotatedAnnotation' is scheduled for removal">AnnotatedAnnotation</warning> class C1 @<warning descr="'AnnotatedAnnotation' is scheduled for removal">AnnotatedAnnotation</warning>(nonAnnotatedAttributeInAnnotatedAnnotation = "123") class C2 @<warning descr="'AnnotatedAnnotation' is scheduled for removal">AnnotatedAnnotation</warning>(<warning descr="'annotatedAttributeInAnnotatedAnnotation' is scheduled for removal">annotatedAttributeInAnnotatedAnnotation</warning> = "123") class C3 @NonAnnotatedAnnotation class C4 @NonAnnotatedAnnotation(nonAnnotatedAttributeInNonAnnotatedAnnotation = "123") class C5 @NonAnnotatedAnnotation(<warning descr="'annotatedAttributeInNonAnnotatedAnnotation' is scheduled for removal">annotatedAttributeInNonAnnotatedAnnotation</warning> = "123") class C6 } }
apache-2.0
77fb6979961773d15ee32f874501c271
85.457831
328
0.813101
5.924855
false
false
false
false
Tickaroo/tikxml
annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/annotationprocessing/attribute/ItemWithGetterSettersDataClass.kt
1
1569
/* * Copyright (C) 2015 Hannes Dorfmann * Copyright (C) 2015 Tickaroo, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.tickaroo.tikxml.annotationprocessing.attribute import com.tickaroo.tikxml.annotation.Attribute import com.tickaroo.tikxml.annotation.Xml import com.tickaroo.tikxml.annotationprocessing.DateConverter import java.util.Date /** * @author Hannes Dorfmann */ @Xml(name = "item") data class ItemWithGetterSettersDataClass ( @field:Attribute var aString: String? = null, @field:Attribute var anInt: Int = 0, @field:Attribute var aBoolean: Boolean = false, @field:Attribute var aDouble: Double = 0.toDouble(), @field:Attribute var aLong: Long = 0, @field:Attribute(converter = DateConverter::class) var aDate: Date? = null, @field:Attribute var intWrapper: Int? = null, @field:Attribute var booleanWrapper: Boolean? = null, @field:Attribute var doubleWrapper: Double? = null, @field:Attribute var longWrapper: Long? = null )
apache-2.0
55374d56069faadc2450af2cf0e81645
25.15
75
0.711281
4.075325
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/tracker/importer/internal/JobQueryCall.kt
1
5948
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.tracker.importer.internal import dagger.Reusable import io.reactivex.Observable import java.util.concurrent.TimeUnit import javax.inject.Inject import org.hisp.dhis.android.core.arch.api.executors.internal.APICallExecutor import org.hisp.dhis.android.core.arch.call.D2Progress import org.hisp.dhis.android.core.arch.call.internal.D2ProgressManager import org.hisp.dhis.android.core.arch.db.querybuilders.internal.WhereClauseBuilder import org.hisp.dhis.android.core.arch.db.stores.internal.ObjectWithoutUidStore import org.hisp.dhis.android.core.maintenance.D2Error import org.hisp.dhis.android.core.maintenance.D2ErrorCode import org.hisp.dhis.android.core.trackedentity.internal.NewTrackerImporterTrackedEntityPostStateManager internal const val ATTEMPTS_AFTER_UPLOAD = 90 internal const val ATTEMPTS_WHEN_QUERYING = 1 internal const val ATTEMPTS_INITIAL_DELAY = 1L internal const val ATTEMPTS_INTERVAL = 2L @Reusable internal class JobQueryCall @Inject internal constructor( private val service: TrackerImporterService, private val apiCallExecutor: APICallExecutor, private val trackerJobObjectStore: ObjectWithoutUidStore<TrackerJobObject>, private val handler: JobReportHandler, private val fileResourceHandler: JobReportFileResourceHandler, private val stateManager: NewTrackerImporterTrackedEntityPostStateManager ) { fun queryPendingJobs(): Observable<D2Progress> { return Observable.just(true) .flatMapIterable { val pendingJobs = trackerJobObjectStore.selectAll() .sortedBy { it.lastUpdated() } .groupBy { it.jobUid() } .toList() pendingJobs.withIndex().map { Triple(it.value.first, it.value.second, it.index == pendingJobs.size - 1) } } .flatMap { queryJobInternal(it.first, it.second, it.third, ATTEMPTS_WHEN_QUERYING) .flatMap { _ -> updateFileResourceStates(it.second) } } } fun queryJob(jobId: String): Observable<D2Progress> { val jobObjects = trackerJobObjectStore.selectWhere(byJobIdClause(jobId)) return queryJobInternal(jobId, jobObjects, true, ATTEMPTS_AFTER_UPLOAD) } fun updateFileResourceStates(jobObjects: List<TrackerJobObject>): Observable<D2Progress> { return fileResourceHandler.updateFileResourceStates(jobObjects) } private fun queryJobInternal( jobId: String, jobObjects: List<TrackerJobObject>, isLastJob: Boolean, attempts: Int ): Observable<D2Progress> { val progressManager = D2ProgressManager(null) @Suppress("TooGenericExceptionCaught") return Observable.interval(ATTEMPTS_INITIAL_DELAY, ATTEMPTS_INTERVAL, TimeUnit.SECONDS) .map { try { downloadAndHandle(jobId, jobObjects) true } catch (e: Throwable) { if (e is D2Error && e.errorCode() == D2ErrorCode.JOB_REPORT_NOT_AVAILABLE) { false } else { handlerError(jobId, jobObjects) true } } } .takeUntil { it } .take(attempts.toLong()) .map { progressManager.increaseProgress( JobReport::class.java, it && isLastJob ) } .flatMap { updateFileResourceStates(jobObjects) } } private fun downloadAndHandle(jobId: String, jobObjects: List<TrackerJobObject>) { val jobReport = apiCallExecutor.executeObjectCallWithErrorCatcher( service.getJobReport(jobId), JobQueryErrorCatcher() ) trackerJobObjectStore.deleteWhere(byJobIdClause(jobId)) handler.handle(jobReport, jobObjects) } private fun handlerError(jobId: String, jobObjects: List<TrackerJobObject>) { trackerJobObjectStore.deleteWhere(byJobIdClause(jobId)) stateManager.restoreStates(jobObjects) } private fun byJobIdClause(jobId: String) = WhereClauseBuilder() .appendKeyStringValue(TrackerJobObjectTableInfo.Columns.JOB_UID, jobId) .build() }
bsd-3-clause
19f73c9a8bcb0ecfd0b20f8caadd598d
43.059259
104
0.688971
4.800646
false
false
false
false