repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
Ekito/koin
koin-projects/koin-logger-slf4j/src/main/kotlin/org/koin/logger/KoinApplicationExt.kt
1
190
package org.koin.logger import org.koin.core.KoinApplication import org.koin.core.logger.Level fun KoinApplication.slf4jLogger(level: Level = Level.INFO) { logger(SLF4JLogger(level)) }
apache-2.0
xfournet/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/GuiTestCase.kt
1
35414
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testGuiFramework.impl import com.intellij.openapi.fileChooser.ex.FileChooserDialogImpl import com.intellij.openapi.ui.ComponentWithBrowseButton import com.intellij.openapi.util.io.FileUtil import com.intellij.testGuiFramework.cellReader.ExtendedJComboboxCellReader import com.intellij.testGuiFramework.cellReader.ExtendedJListCellReader import com.intellij.testGuiFramework.cellReader.ExtendedJTableCellReader import com.intellij.testGuiFramework.fixtures.* import com.intellij.testGuiFramework.fixtures.extended.ExtendedButtonFixture import com.intellij.testGuiFramework.fixtures.extended.ExtendedTableFixture import com.intellij.testGuiFramework.fixtures.extended.ExtendedTreeFixture import com.intellij.testGuiFramework.fixtures.extended.RowFixture import com.intellij.testGuiFramework.fixtures.newProjectWizard.NewProjectWizardFixture import com.intellij.testGuiFramework.framework.GuiTestLocalRunner import com.intellij.testGuiFramework.framework.GuiTestUtil import com.intellij.testGuiFramework.framework.GuiTestUtil.waitUntilFound import com.intellij.testGuiFramework.framework.IdeTestApplication.getTestScreenshotDirPath import com.intellij.testGuiFramework.impl.GuiTestUtilKt.findBoundedComponentByText import com.intellij.testGuiFramework.impl.GuiTestUtilKt.getComponentText import com.intellij.testGuiFramework.impl.GuiTestUtilKt.isTextComponent import com.intellij.testGuiFramework.impl.GuiTestUtilKt.typeMatcher import com.intellij.testGuiFramework.launcher.system.SystemInfo import com.intellij.testGuiFramework.launcher.system.SystemInfo.isMac import com.intellij.testGuiFramework.util.Clipboard import com.intellij.testGuiFramework.util.Key import com.intellij.testGuiFramework.util.Shortcut import com.intellij.ui.CheckboxTree import com.intellij.ui.HyperlinkLabel import com.intellij.ui.components.JBLabel import com.intellij.ui.components.labels.LinkLabel import com.intellij.ui.treeStructure.treetable.TreeTable import com.intellij.util.ui.AsyncProcessIcon import org.fest.swing.exception.ActionFailedException import org.fest.swing.exception.ComponentLookupException import org.fest.swing.exception.WaitTimedOutError import org.fest.swing.fixture.* import org.fest.swing.image.ScreenshotTaker import org.fest.swing.timing.Condition import org.fest.swing.timing.Pause import org.fest.swing.timing.Timeout import org.fest.swing.timing.Timeout.timeout import org.junit.Rule import org.junit.runner.RunWith import java.awt.Component import java.awt.Container import java.io.File import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.TimeUnit import javax.swing.* import javax.swing.text.JTextComponent /** * The main base class that should be extended for writing GUI tests. * * GuiTestCase contains methods of TestCase class like setUp() and tearDown() but also has a set of methods allows to use Kotlin DSL for * writing GUI tests (starts from comment KOTLIN DSL FOR GUI TESTING). The main concept of this DSL is using contexts of the current * component. Kotlin language gives us an opportunity to omit fixture instances to perform their methods, therefore code looks simpler and * more clear. Just use contexts functions to find appropriate fixtures and to operate with them: * * {@code <code> * welcomeFrame { // <- context of WelcomeFrameFixture * createNewProject() * dialog("New Project Wizard") { * // context of DialogFixture of dialog with title "New Project Wizard" * } * } * </code>} * * All fixtures (or DSL methods for theese fixtures) has a timeout to find component on screen and equals to #defaultTimeout. To check existence * of specific component by its fixture use exists lambda function with receiver. * * The more descriptive documentation about entire framework could be found in the root of testGuiFramework (HowToUseFramework.md) * */ @RunWith(GuiTestLocalRunner::class) open class GuiTestCase { @Rule @JvmField val guiTestRule = GuiTestRule() /** * default timeout to find target component for fixture. Using seconds as time unit. */ var defaultTimeout = 120L val settingsTitle: String = if (isMac()) "Preferences" else "Settings" val defaultSettingsTitle: String = if (isMac()) "Default Preferences" else "Default Settings" val slash: String = File.separator fun robot() = guiTestRule.robot() //********************KOTLIN DSL FOR GUI TESTING************************* //*********CONTEXT LAMBDA FUNCTIONS WITH RECEIVERS*********************** /** * Context function: finds welcome frame and creates WelcomeFrameFixture instance as receiver object. Code block after it call methods on * the receiver object (WelcomeFrameFixture instance). */ open fun welcomeFrame(func: WelcomeFrameFixture.() -> Unit) { func(guiTestRule.findWelcomeFrame()) } /** * Context function: finds IDE frame and creates IdeFrameFixture instance as receiver object. Code block after it call methods on the * receiver object (IdeFrameFixture instance). */ fun ideFrame(func: IdeFrameFixture.() -> Unit) { func(guiTestRule.findIdeFrame()) } /** * Context function: finds dialog with specified title and creates JDialogFixture instance as receiver object. Code block after it call * methods on the receiver object (JDialogFixture instance). * * @title title of searching dialog window. If dialog should be only one title could be omitted or set to null. * @needToKeepDialog is true if no need to wait when dialog is closed * @timeout time in seconds to find dialog in GUI hierarchy. */ fun dialog(title: String? = null, ignoreCaseTitle: Boolean = false, timeout: Long = defaultTimeout, needToKeepDialog: Boolean = false, func: JDialogFixture.() -> Unit) { val dialog = dialog(title, ignoreCaseTitle, timeout) func(dialog) if (!needToKeepDialog) dialog.waitTillGone() } /** * Waits for a native file chooser, types the path in a textfield and closes it by clicking OK button. Or runs AppleScript if the file chooser * is a Mac native. */ fun chooseFileInFileChooser(path: String, timeout: Long = defaultTimeout) { val macNativeFileChooser = SystemInfo.isMac() && (System.getProperty("ide.mac.file.chooser.native", "true").toLowerCase() == "false") if (macNativeFileChooser) { MacFileChooserDialogFixture(robot()).selectByPath(path) } else { val fileChooserDialog: JDialog try { fileChooserDialog = GuiTestUtilKt.withPauseWhenNull(timeout.toInt()) { robot().finder() .findAll(GuiTestUtilKt.typeMatcher(JDialog::class.java) { true }) .firstOrNull { GuiTestUtilKt.findAllWithBFS(it, JPanel::class.java).any { it.javaClass.name.contains(FileChooserDialogImpl::class.java.simpleName) } } } } catch (timeoutError: WaitTimedOutError) { throw ComponentLookupException("Unable to find file chooser dialog in ${timeout.toInt()} seconds") } val dialogFixture = JDialogFixture(robot(), fileChooserDialog) with(dialogFixture) { asyncProcessIcon().waitUntilStop(20) textfield("") invokeAction("\$SelectAll") typeText(path) button("OK").clickWhenEnabled() waitTillGone() } } } /** * Context function: imports a simple project to skip steps of creation, creates IdeFrameFixture instance as receiver object when project * is loaded. Code block after it call methods on the receiver object (IdeFrameFixture instance). */ fun simpleProject(func: IdeFrameFixture.() -> Unit) { func(guiTestRule.importSimpleProject()) } /** * Context function: finds dialog "New Project Wizard" and creates NewProjectWizardFixture instance as receiver object. Code block after * it call methods on the receiver object (NewProjectWizardFixture instance). */ fun projectWizard(func: NewProjectWizardFixture.() -> Unit) { func(guiTestRule.findNewProjectWizard()) } /** * Context function for IdeFrame: activates project view in IDE and creates ProjectViewFixture instance as receiver object. Code block after * it call methods on the receiver object (ProjectViewFixture instance). */ fun IdeFrameFixture.projectView(func: ProjectViewFixture.() -> Unit) { func(this.projectView) } /** * Context function for IdeFrame: activates toolwindow view in IDE and creates CustomToolWindowFixture instance as receiver object. Code * block after it call methods on the receiver object (CustomToolWindowFixture instance). * * @id - a toolwindow id. */ fun IdeFrameFixture.toolwindow(id: String, func: CustomToolWindowFixture.() -> Unit) { func(CustomToolWindowFixture(id, this)) } //*********FIXTURES METHODS WITHOUT ROBOT and TARGET; KOTLIN ONLY /** * Finds a JList component in hierarchy of context component with a containingItem and returns JListFixture. * * @timeout in seconds to find JList component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.jList(containingItem: String? = null, timeout: Long = defaultTimeout): JListFixture = if (target() is Container) { val extCellReader = ExtendedJListCellReader() val myJList = waitUntilFound(target() as Container, JList::class.java, timeout) { jList -> if (containingItem == null) true //if were searching for any jList() else { val elements = (0 until jList.model.size).map { it -> extCellReader.valueAt(jList, it) } elements.any { it.toString() == containingItem } && jList.isShowing } } val jListFixture = JListFixture(guiTestRule.robot(), myJList) jListFixture.replaceCellReader(extCellReader) jListFixture } else throw unableToFindComponent("JList") /** * Finds a JButton component in hierarchy of context component with a name and returns ExtendedButtonFixture. * * @timeout in seconds to find JButton component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.button(name: String, timeout: Long = defaultTimeout): ExtendedButtonFixture = if (target() is Container) { val jButton = waitUntilFound(target() as Container, JButton::class.java, timeout) { it.isShowing && it.isVisible && it.text == name } ExtendedButtonFixture(guiTestRule.robot(), jButton) } else throw unableToFindComponent("""JButton named by $name""") fun <S, C : Component> ComponentFixture<S, C>.componentWithBrowseButton(boundedLabelText: String, timeout: Long = defaultTimeout): ComponentWithBrowseButtonFixture { if (target() is Container) { val boundedLabel = waitUntilFound(target() as Container, JLabel::class.java, timeout) { it.text == boundedLabelText && it.isShowing } val component = boundedLabel.labelFor if (component is ComponentWithBrowseButton<*>) { return ComponentWithBrowseButtonFixture(component, guiTestRule.robot()) } } throw unableToFindComponent("ComponentWithBrowseButton with labelFor=$boundedLabelText") } fun <S, C : Component> ComponentFixture<S, C>.treeTable(timeout: Long = defaultTimeout): TreeTableFixture { if (target() is Container) { val table = waitUntilFound(guiTestRule.robot(), target() as Container, typeMatcher(TreeTable::class.java) { true }, timeout.toFestTimeout() ) return TreeTableFixture(guiTestRule.robot(), table) } else throw UnsupportedOperationException( "Sorry, unable to find inspections tree with ${target()} as a Container") } fun <S, C : Component> ComponentFixture<S, C>.spinner(boundedLabelText: String, timeout: Long = defaultTimeout): JSpinnerFixture { if (target() is Container) { val boundedLabel = waitUntilFound(target() as Container, JLabel::class.java, timeout) { it.text == boundedLabelText } val component = boundedLabel.labelFor if (component is JSpinner) return JSpinnerFixture(guiTestRule.robot(), component) } throw unableToFindComponent("""JSpinner with $boundedLabelText bounded label""") } /** * Finds a JComboBox component in hierarchy of context component by text of label and returns ComboBoxFixture. * * @timeout in seconds to find JComboBox component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.combobox(labelText: String, timeout: Long = defaultTimeout): ComboBoxFixture = if (target() is Container) { try { waitUntilFound(target() as Container, Component::class.java, timeout) { it.isShowing && it.isTextComponent() && it.getComponentText() == labelText } } catch (e: WaitTimedOutError) { throw ComponentLookupException("Unable to find label for a combobox with text \"$labelText\" in $timeout seconds") } val comboBox = findBoundedComponentByText(guiTestRule.robot(), target() as Container, labelText, JComboBox::class.java) val comboboxFixture = ComboBoxFixture(guiTestRule.robot(), comboBox) comboboxFixture.replaceCellReader(ExtendedJComboboxCellReader()) comboboxFixture } else throw unableToFindComponent("""JComboBox near label by "$labelText"""") /** * Finds a JCheckBox component in hierarchy of context component by text of label and returns CheckBoxFixture. * * @timeout in seconds to find JCheckBox component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.checkbox(labelText: String, timeout: Long = defaultTimeout): CheckBoxFixture = if (target() is Container) { val jCheckBox = waitUntilFound(target() as Container, JCheckBox::class.java, timeout) { it.isShowing && it.isVisible && it.text == labelText } CheckBoxFixture(guiTestRule.robot(), jCheckBox) } else throw unableToFindComponent("""JCheckBox label by "$labelText""") /** * Finds a ActionLink component in hierarchy of context component by name and returns ActionLinkFixture. * * @timeout in seconds to find ActionLink component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.actionLink(name: String, timeout: Long = defaultTimeout): ActionLinkFixture = if (target() is Container) { ActionLinkFixture.findActionLinkByName(name, guiTestRule.robot(), target() as Container, timeout.toFestTimeout()) } else throw unableToFindComponent("""ActionLink by name "$name"""") /** * Finds a ActionButton component in hierarchy of context component by action name and returns ActionButtonFixture. * * @actionName text or action id of an action button (@see com.intellij.openapi.actionSystem.ActionManager#getId()) * @timeout in seconds to find ActionButton component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.actionButton(actionName: String, timeout: Long = defaultTimeout): ActionButtonFixture = if (target() is Container) { try { ActionButtonFixture.findByText(actionName, guiTestRule.robot(), target() as Container, timeout.toFestTimeout()) } catch (componentLookupException: ComponentLookupException) { ActionButtonFixture.findByActionId(actionName, guiTestRule.robot(), target() as Container, timeout.toFestTimeout()) } } else throw unableToFindComponent("""ActionButton by action name "$actionName"""") /** * Finds a ActionButton component in hierarchy of context component by action class name and returns ActionButtonFixture. * * @actionClassName qualified name of class for action * @timeout in seconds to find ActionButton component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.actionButtonByClass(actionClassName: String, timeout: Long = defaultTimeout): ActionButtonFixture = if (target() is Container) { ActionButtonFixture.findByActionClassName(actionClassName, guiTestRule.robot(), target() as Container, timeout.toFestTimeout()) } else throw unableToFindComponent("""ActionButton by action class name "$actionClassName"""") /** * Finds a JRadioButton component in hierarchy of context component by label text and returns JRadioButtonFixture. * * @timeout in seconds to find JRadioButton component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.radioButton(textLabel: String, timeout: Long = defaultTimeout): RadioButtonFixture = if (target() is Container) GuiTestUtil.findRadioButton(guiTestRule.robot(), target() as Container, textLabel, timeout.toFestTimeout()) else throw unableToFindComponent("""RadioButton by label "$textLabel"""") /** * Finds a JTextComponent component (JTextField) in hierarchy of context component by text of label and returns JTextComponentFixture. * * @textLabel could be a null if label is absent * @timeout in seconds to find JTextComponent component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.textfield(textLabel: String?, timeout: Long = defaultTimeout): JTextComponentFixture { val target = target() if (target is Container) { return textfield(textLabel, target, timeout) } else throw unableToFindComponent("""JTextComponent (JTextField) by label "$textLabel"""") } fun textfield(textLabel: String?, container: Container, timeout: Long): JTextComponentFixture { if (textLabel.isNullOrEmpty()) { val jTextField = waitUntilFound(container, JTextField::class.java, timeout) { jTextField -> jTextField.isShowing } return JTextComponentFixture(guiTestRule.robot(), jTextField) } //wait until label has appeared waitUntilFound(container, Component::class.java, timeout) { it.isShowing && it.isVisible && it.isTextComponent() && it.getComponentText() == textLabel } val jTextComponent = findBoundedComponentByText(guiTestRule.robot(), container, textLabel!!, JTextComponent::class.java) return JTextComponentFixture(guiTestRule.robot(), jTextComponent) } /** * Finds a JTree component in hierarchy of context component by a path and returns ExtendedTreeFixture. * * @pathStrings comma separated array of Strings, representing path items: jTree("myProject", "src", "Main.java") * @timeout in seconds to find JTree component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.jTree(vararg pathStrings: String, timeout: Long = defaultTimeout): ExtendedTreeFixture = if (target() is Container) jTreePath(target() as Container, timeout, *pathStrings) else throw unableToFindComponent("""JTree "${if (pathStrings.isNotEmpty()) "by path $pathStrings" else ""}"""") /** * Finds a CheckboxTree component in hierarchy of context component by a path and returns CheckboxTreeFixture. * * @pathStrings comma separated array of Strings, representing path items: checkboxTree("JBoss", "JBoss Drools") * @timeout in seconds to find JTree component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.checkboxTree(vararg pathStrings: String, timeout: Long = defaultTimeout): CheckboxTreeFixture = if (target() is Container) { val extendedTreeFixture = jTreePath(target() as Container, timeout, *pathStrings) if (extendedTreeFixture.tree !is CheckboxTree) throw ComponentLookupException("Found JTree but not a CheckboxTree") CheckboxTreeFixture(guiTestRule.robot(), extendedTreeFixture.tree) } else throw unableToFindComponent("""CheckboxTree "${if (pathStrings.isNotEmpty()) "by path $pathStrings" else ""}"""") /** * Finds a JTable component in hierarchy of context component by a cellText and returns JTableFixture. * * @timeout in seconds to find JTable component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.table(cellText: String, timeout: Long = defaultTimeout): JTableFixture = if (target() is Container) { val jTable = waitUntilFound(target() as Container, JTable::class.java, timeout) { val jTableFixture = JTableFixture(guiTestRule.robot(), it) jTableFixture.replaceCellReader(ExtendedJTableCellReader()) try { jTableFixture.cell(cellText) true } catch (e: ActionFailedException) { false } } JTableFixture(guiTestRule.robot(), jTable) } else throw unableToFindComponent("""JTable with cell text "$cellText"""") /** * Finds popup on screen with item (itemName) and clicks on it item * * @timeout timeout in seconds to find JTextComponent component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.popupClick(itemName: String, timeout: Long = defaultTimeout) = if (target() is Container) { JBListPopupFixture.clickPopupMenuItem(itemName, false, target() as Container, guiTestRule.robot(), timeout.toFestTimeout()) } else throw unableToFindComponent("Popup") /** * Finds a LinkLabel component in hierarchy of context component by a link name and returns fixture for it. * * @timeout in seconds to find LinkLabel component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.linkLabel(linkName: String, timeout: Long = defaultTimeout) = if (target() is Container) { val myLinkLabel = waitUntilFound( guiTestRule.robot(), target() as Container, typeMatcher(LinkLabel::class.java) { it.isShowing && (it.text == linkName) }, timeout.toFestTimeout()) ComponentFixture(ComponentFixture::class.java, guiTestRule.robot(), myLinkLabel) } else throw unableToFindComponent("LinkLabel") fun <S, C : Component> ComponentFixture<S, C>.hyperlinkLabel(labelText: String, timeout: Long = defaultTimeout): HyperlinkLabelFixture = if (target() is Container) { val hyperlinkLabel = waitUntilFound(guiTestRule.robot(), target() as Container, typeMatcher(HyperlinkLabel::class.java) { it.isShowing && (it.text == labelText) }, timeout.toFestTimeout()) HyperlinkLabelFixture(guiTestRule.robot(), hyperlinkLabel) } else throw unableToFindComponent("""HyperlinkLabel by label text: "$labelText"""") /** * Finds a table of plugins component in hierarchy of context component by a link name and returns fixture for it. * * @timeout in seconds to find table of plugins component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.pluginTable(timeout: Long = defaultTimeout) = if (target() is Container) PluginTableFixture.find(guiTestRule.robot(), target() as Container, timeout.toFestTimeout()) else throw unableToFindComponent("PluginTable") /** * Finds a Message component in hierarchy of context component by a title MessageFixture. * * @timeout in seconds to find component for Message * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.message(title: String, timeout: Long = defaultTimeout) = if (target() is Container) MessagesFixture.findByTitle(guiTestRule.robot(), target() as Container, title, timeout.toFestTimeout()) else throw unableToFindComponent("Message") /** * Finds a Message component in hierarchy of context component by a title MessageFixture. * * @timeout in seconds to find component for Message * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.message(title: String, timeout: Long = defaultTimeout, func: MessagesFixture.() -> Unit) { if (target() is Container) func(MessagesFixture.findByTitle(guiTestRule.robot(), target() as Container, title, timeout.toFestTimeout())) else throw unableToFindComponent("Message") } /** * Finds a JBLabel component in hierarchy of context component by a label name and returns fixture for it. * * @timeout in seconds to find JBLabel component * @throws ComponentLookupException if component has not been found or timeout exceeded */ fun <S, C : Component> ComponentFixture<S, C>.label(labelName: String, timeout: Long = defaultTimeout): JLabelFixture = if (target() is Container) { val jbLabel = waitUntilFound( guiTestRule.robot(), target() as Container, typeMatcher(JBLabel::class.java) { it.isShowing && (it.text == labelName || labelName in it.text) }, timeout.toFestTimeout()) JLabelFixture(guiTestRule.robot(), jbLabel) } else throw unableToFindComponent("JBLabel") private fun <S, C : Component> ComponentFixture<S, C>.unableToFindComponent(component: String): ComponentLookupException = ComponentLookupException("""Sorry, unable to find $component component with ${target()} as a Container""") /** * Find an AsyncProcessIcon component in a current context (gets by receiver) and returns a fixture for it. * * @timeout timeout in seconds to find AsyncProcessIcon */ fun <S, C : Component> ComponentFixture<S, C>.asyncProcessIcon(timeout: Long = defaultTimeout): AsyncProcessIconFixture { val asyncProcessIcon = waitUntilFound( guiTestRule.robot(), target() as Container, typeMatcher(AsyncProcessIcon::class.java) { it.isShowing && it.isVisible }, timeout.toFestTimeout()) return AsyncProcessIconFixture(guiTestRule.robot(), asyncProcessIcon) } //*********FIXTURES METHODS FOR IDEFRAME WITHOUT ROBOT and TARGET /** * Context function for IdeFrame: get current editor and create EditorFixture instance as a receiver object. Code block after * it call methods on the receiver object (EditorFixture instance). */ fun IdeFrameFixture.editor(func: FileEditorFixture.() -> Unit) { func(this.editor) } /** * Context function for IdeFrame: get the tab with specific opened file and create EditorFixture instance as a receiver object. Code block after * it call methods on the receiver object (EditorFixture instance). */ fun IdeFrameFixture.editor(tabName: String, func: FileEditorFixture.() -> Unit) { val editorFixture = this.editor.selectTab(tabName) func(editorFixture) } /** * Context function for IdeFrame: creates a MainToolbarFixture instance as receiver object. Code block after * it call methods on the receiver object (MainToolbarFixture instance). */ fun IdeFrameFixture.toolbar(func: MainToolbarFixture.() -> Unit) { func(this.toolbar) } /** * Context function for IdeFrame: creates a NavigationBarFixture instance as receiver object. Code block after * it call methods on the receiver object (NavigationBarFixture instance). */ fun IdeFrameFixture.navigationBar(func: NavigationBarFixture.() -> Unit) { func(this.navigationBar) } fun IdeFrameFixture.configurationList(func: RunConfigurationListFixture.() -> Unit) { func(this.runConfigurationList) } /** * Extension function for IDE to iterate through the menu. * * @path items like: popup("New", "File") */ fun IdeFrameFixture.popup(vararg path: String) = this.invokeMenuPath(*path) fun CustomToolWindowFixture.ContentFixture.editor(func: EditorFixture.() -> Unit) { func(this.editor()) } //*********COMMON FUNCTIONS WITHOUT CONTEXT /** * Type text by symbol with a constant delay. Generate system key events, so entered text will aply to a focused component. */ fun typeText(text: String) = GuiTestUtil.typeText(text, guiTestRule.robot(), 10) /** * @param keyStroke should follow {@link KeyStrokeAdapter#getKeyStroke(String)} instructions and be generated by {@link KeyStrokeAdapter#toString(KeyStroke)} preferably * * examples: shortcut("meta comma"), shortcut("ctrl alt s"), shortcut("alt f11") * modifiers order: shift | ctrl | control | meta | alt | altGr | altGraph */ fun shortcut(keyStroke: String) = GuiTestUtil.invokeActionViaShortcut(guiTestRule.robot(), keyStroke) fun shortcut(shortcut: Shortcut) = shortcut(shortcut.getKeystroke()) fun shortcut(key: Key) = shortcut(key.name) /** * copies a given string to a system clipboard */ fun copyToClipboard(string: String) = Clipboard.copyToClipboard(string) /** * Invoke action by actionId through its keystroke */ fun invokeAction(actionId: String) = GuiTestUtil.invokeAction(guiTestRule.robot(), actionId) /** * Take a screenshot for a specific component. Screenshot remain scaling and represent it in name of file. */ fun screenshot(component: Component, screenshotName: String) { val extension = "${getScaleSuffix()}.png" val pathWithTestFolder = getTestScreenshotDirPath().path + slash + this.guiTestRule.getTestName() val fileWithTestFolder = File(pathWithTestFolder) FileUtil.ensureExists(fileWithTestFolder) var screenshotFilePath = File(fileWithTestFolder, screenshotName + extension) if (screenshotFilePath.isFile) { val format = SimpleDateFormat("MM-dd-yyyy.HH.mm.ss") val now = format.format(GregorianCalendar().time) screenshotFilePath = File(fileWithTestFolder, screenshotName + "." + now + extension) } ScreenshotTaker().saveComponentAsPng(component, screenshotFilePath.path) println(message = "Screenshot for a component \"$component\" taken and stored at ${screenshotFilePath.path}") } /** * Finds JDialog with a specific title (if title is null showing dialog should be only one) and returns created JDialogFixture */ fun dialog(title: String? = null, ignoreCaseTitle: Boolean, timeoutInSeconds: Long): JDialogFixture { if (title == null) { val jDialog = waitUntilFound(null, JDialog::class.java, timeoutInSeconds) { true } return JDialogFixture(guiTestRule.robot(), jDialog) } else { try { val dialog = GuiTestUtilKt.withPauseWhenNull(timeoutInSeconds.toInt()) { val allMatchedDialogs = guiTestRule.robot().finder().findAll(typeMatcher(JDialog::class.java) { if (ignoreCaseTitle) it.title.toLowerCase() == title.toLowerCase() else it.title == title }).filter { it.isShowing && it.isEnabled && it.isVisible } if (allMatchedDialogs.size > 1) throw Exception( "Found more than one (${allMatchedDialogs.size}) dialogs matched title \"$title\"") allMatchedDialogs.firstOrNull() } return JDialogFixture(guiTestRule.robot(), dialog) } catch (timeoutError: WaitTimedOutError) { throw ComponentLookupException("Timeout error for finding JDialog by title \"$title\" for $timeoutInSeconds seconds") } } } private fun Long.toFestTimeout(): Timeout = if (this == 0L) timeout(50, TimeUnit.MILLISECONDS) else timeout(this, TimeUnit.SECONDS) private fun jTreePath(container: Container, timeout: Long, vararg pathStrings: String): ExtendedTreeFixture { val myTree: JTree? val pathList = pathStrings.toList() myTree = if (pathList.isEmpty()) { waitUntilFound(guiTestRule.robot(), container, typeMatcher(JTree::class.java) { true }, timeout.toFestTimeout()) } else { waitUntilFound(guiTestRule.robot(), container, typeMatcher(JTree::class.java) { ExtendedTreeFixture(guiTestRule.robot(), it).hasPath(pathList) }, timeout.toFestTimeout()) } return ExtendedTreeFixture(guiTestRule.robot(), myTree) } fun exists(fixture: () -> AbstractComponentFixture<*, *, *>): Boolean { val tmp = defaultTimeout defaultTimeout = 0 try { fixture.invoke() defaultTimeout = tmp } catch (ex: Exception) { when (ex) { is ComponentLookupException, is WaitTimedOutError -> { defaultTimeout = tmp; return false } else -> throw ex } } return true } //*********SOME EXTENSION FUNCTIONS FOR FIXTURES fun JListFixture.doubleClickItem(itemName: String) { this.item(itemName).doubleClick() } //necessary only for Windows private fun getScaleSuffix(): String? { val scaleEnabled: Boolean = (GuiTestUtil.getSystemPropertyOrEnvironmentVariable("sun.java2d.uiScale.enabled")?.toLowerCase().equals( "true")) if (!scaleEnabled) return "" val uiScaleVal = GuiTestUtil.getSystemPropertyOrEnvironmentVariable("sun.java2d.uiScale") ?: return "" return "@${uiScaleVal}x" } fun <ComponentType : Component> waitUntilFound(container: Container?, componentClass: Class<ComponentType>, timeout: Long, matcher: (ComponentType) -> Boolean): ComponentType { return GuiTestUtil.waitUntilFound(guiTestRule.robot(), container, typeMatcher(componentClass) { matcher(it) }, timeout.toFestTimeout()) } fun pause(condition: String = "Unspecified condition", timeoutSeconds: Long = 120, testFunction: () -> Boolean) { Pause.pause(object : Condition(condition) { override fun test() = testFunction() }, Timeout.timeout(timeoutSeconds, TimeUnit.SECONDS)) } fun tableRowValues(table: JTableFixture, rowIndex: Int): List<String> { val fixture = ExtendedTableFixture(guiTestRule.robot(), table.target()) return RowFixture(rowIndex, fixture).values() } fun tableRowCount(table: JTableFixture): Int { val fixture = ExtendedTableFixture(guiTestRule.robot(), table.target()) return fixture.rowCount() } }
apache-2.0
Agusyc/DayCounter
app/src/main/java/com/agusyc/daycounter/Counter.kt
1
1017
package com.agusyc.daycounter import android.content.Context import android.content.SharedPreferences // This class represents a Counter internal class Counter (context: Context, val id: Int, val isWidget: Boolean) { // We declare all the needed variables val label: String val date: Long val color: Int val colorIndex: Int val notification: Boolean init { // We get the right prefs file, according to the isWidget variable, and we parse all the needed data val prefs: SharedPreferences = if (isWidget) context.getSharedPreferences("DaysPrefs", Context.MODE_PRIVATE) else context.getSharedPreferences("ListDaysPrefs", Context.MODE_PRIVATE) label = prefs.getString(id.toString() + "label", "") date = prefs.getLong(id.toString() + "date", 0) color = prefs.getInt(id.toString() + "color", 0) colorIndex = prefs.getInt(id.toString() + "color_index", 0) notification = prefs.getBoolean(id.toString() + "notification", false) } }
mit
vshkl/Pik
app/src/main/java/by/vshkl/android/pik/ui/albums/AlbumsListener.kt
1
242
package by.vshkl.android.pik.ui.albums import by.vshkl.android.pik.model.Album interface AlbumsListener { fun onAlbumClicked(album: Album?) fun onAlbumSelectionClicked(index: Int) fun onAlbumSelectionLongClicked(index: Int) }
apache-2.0
googlecodelabs/android-testing
app/src/main/java/com/example/android/architecture/blueprints/todoapp/tasks/TasksActivity.kt
1
2842
/* * 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.architecture.blueprints.todoapp.tasks import android.app.Activity import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.drawerlayout.widget.DrawerLayout import androidx.navigation.NavController import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import com.example.android.architecture.blueprints.todoapp.R import com.google.android.material.navigation.NavigationView /** * Main activity for the todoapp. Holds the Navigation Host Fragment and the Drawer, Toolbar, etc. */ class TasksActivity : AppCompatActivity() { private lateinit var drawerLayout: DrawerLayout private lateinit var appBarConfiguration: AppBarConfiguration override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.tasks_act) setupNavigationDrawer() setSupportActionBar(findViewById(R.id.toolbar)) val navController: NavController = findNavController(R.id.nav_host_fragment) appBarConfiguration = AppBarConfiguration.Builder(R.id.tasks_fragment_dest, R.id.statistics_fragment_dest) .setOpenableLayout(drawerLayout) .build() setupActionBarWithNavController(navController, appBarConfiguration) findViewById<NavigationView>(R.id.nav_view) .setupWithNavController(navController) } override fun onSupportNavigateUp(): Boolean { return findNavController(R.id.nav_host_fragment).navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } private fun setupNavigationDrawer() { drawerLayout = (findViewById<DrawerLayout>(R.id.drawer_layout)) .apply { setStatusBarBackground(R.color.colorPrimaryDark) } } } // Keys for navigation const val ADD_EDIT_RESULT_OK = Activity.RESULT_FIRST_USER + 1 const val DELETE_RESULT_OK = Activity.RESULT_FIRST_USER + 2 const val EDIT_RESULT_OK = Activity.RESULT_FIRST_USER + 3
apache-2.0
notion/Plumb
compiler/src/test/kotlin/rxjoin/internal/codegen/writer/JoinerWriterTest.kt
2
4544
package rxjoin.internal.codegen.writer import com.google.common.truth.Truth.assertAbout import com.google.testing.compile.JavaFileObjects import com.google.testing.compile.JavaSourceSubjectFactory import org.junit.Test import rxjoin.internal.codegen.RxJoinProcessor class JoinerWriterTest { private val singleClassSource = JavaFileObjects.forSourceLines("rxjoin.example.JoinedClassA", "package rxjoin.example;", "import rx.Observable;", "import rx.subjects.BehaviorSubject;", "import rxjoin.annotation.*;", "@Joined(JoinedClassA.JoinedViewModelA.class)", "public class JoinedClassA {", " JoinedViewModelA viewModel = new JoinedViewModelA();", " @Out(\"integer\")", " public Observable<Integer> integerObservable;", " @In(\"string\")", " public BehaviorSubject<String> stringSubject = BehaviorSubject.create();", " public class JoinedViewModelA {", " @In(\"integer\")", " public BehaviorSubject<Integer> integerSubject = BehaviorSubject.create();", " @In(\"string\")", " public BehaviorSubject<String> stringSubject = BehaviorSubject.create();", " @Out(\"string\")", " public Observable<String> stringObservable;", " }", "}") private val invalidSourceWithInAsObserver = JavaFileObjects.forSourceLines("rxjoin.example.JoinedClassA", "package rxjoin.example;", "import rx.Observable;", "import rx.Observer;", "import rx.subjects.BehaviorSubject;", "import rxjoin.annotation.*;", "@Joined(JoinedClassA.JoinedViewModelA.class)", "public class JoinedClassA {", " JoinedViewModelA viewModel = new JoinedViewModelA();", " @Out(\"integer\")", " public Observable<Integer> integerObservable;", " @In(\"string\")", " public BehaviorSubject<String> stringSubject = BehaviorSubject.create();", " public class JoinedViewModelA {", " @In(\"integer\")", " public Observer<Integer> integerObserver = BehaviorSubject.create();", " @In(\"string\")", " public BehaviorSubject<String> stringSubject = BehaviorSubject.create();", " @Out(\"string\")", " public Observable<String> stringObservable;", " }", "}") private val joinedClassAJoiner = JavaFileObjects.forSourceLines("rxjoin.JoinedClassA_Joiner", "package rxjoin;", "", "import java.lang.Override;", "import rx.subscriptions.CompositeSubscription;", "import rxjoin.example.JoinedClassA;", "", "public class JoinedClassA_Joiner implements Joiner<JoinedClassA, JoinedClassA.JoinedViewModelA> {", " private CompositeSubscription subscriptions;", "", " @Override", " public void join(JoinedClassA joined, JoinedClassA.JoinedViewModelA joinedTo) {", " if (subscriptions != null && !subscriptions.isUnsubscribed()) {", " subscriptions.unsubscribe();", " }", " subscriptions = new CompositeSubscription();", " subscriptions.add(Utils.replicate(joined.integerObservable, joinedTo.integerSubject));", " subscriptions.add(Utils.replicate(joinedTo.stringObservable, joinedTo.stringSubject));", " subscriptions.add(Utils.replicate(joinedTo.stringObservable, joined.stringSubject));", " }", "", " @Override", " public void demolish() {", " subscriptions.unsubscribe();", " }", "}" ) @Test fun test_compile_simpleCase() { assertAbout(JavaSourceSubjectFactory.javaSource()) .that(singleClassSource) .processedWith(RxJoinProcessor()) .compilesWithoutError() .and() .generatesSources(joinedClassAJoiner) } @Test fun test_invalidViewmodelThrowsError() { assertAbout(JavaSourceSubjectFactory.javaSource()) .that(invalidSourceWithInAsObserver) .processedWith(RxJoinProcessor()) .failsToCompile() .withErrorContaining("@In-annotated element integerObserver must extend Subject<*, *>.") } }
apache-2.0
vase4kin/TeamCityApp
app/src/main/java/com/github/vase4kin/teamcityapp/changes/view/ChangesFragment.kt
1
2039
/* * Copyright 2016 Andrey Tolpeev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.changes.view import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.github.vase4kin.teamcityapp.R import com.github.vase4kin.teamcityapp.base.extractor.BundleExtractorValues import com.github.vase4kin.teamcityapp.changes.presenter.ChangesPresenterImpl import dagger.android.support.AndroidSupportInjection import javax.inject.Inject /** * Fragment to manage changes */ class ChangesFragment : Fragment() { @Inject lateinit var presenter: ChangesPresenterImpl override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_list, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) AndroidSupportInjection.inject(this) presenter.onViewsCreated() } override fun onDestroyView() { super.onDestroyView() presenter.onViewsDestroyed() } companion object { fun newInstance(url: String): Fragment { val fragment = ChangesFragment() val args = Bundle() args.putString(BundleExtractorValues.URL, url) fragment.arguments = args return fragment } } }
apache-2.0
google/ksp
test-utils/testData/api/javaModifiers.kt
1
10036
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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. */ // TEST PROCESSOR: JavaModifierProcessor // EXPECTED: // C: ABSTRACT PUBLIC : ABSTRACT PUBLIC // C.staticStr: PRIVATE : PRIVATE // C.s1: FINAL JAVA_TRANSIENT : FINAL JAVA_TRANSIENT // C.i1: JAVA_STATIC JAVA_VOLATILE PROTECTED : JAVA_STATIC JAVA_VOLATILE PROTECTED // C.NestedC: JAVA_STATIC PUBLIC : JAVA_STATIC PUBLIC // NestedC.<init>: FINAL PUBLIC : FINAL PUBLIC // C.InnerC: PUBLIC : PUBLIC // InnerC.<init>: FINAL PUBLIC : FINAL PUBLIC // C.intFun: JAVA_DEFAULT JAVA_SYNCHRONIZED : JAVA_DEFAULT JAVA_SYNCHRONIZED // C.foo: ABSTRACT JAVA_STRICT : ABSTRACT JAVA_STRICT // C.<init>: FINAL PUBLIC : FINAL PUBLIC // OuterJavaClass: PUBLIC : PUBLIC // OuterJavaClass.staticPublicField: JAVA_STATIC PUBLIC : JAVA_STATIC PUBLIC // OuterJavaClass.staticPackageProtectedField: JAVA_STATIC : JAVA_STATIC // OuterJavaClass.staticProtectedField: JAVA_STATIC PROTECTED : JAVA_STATIC PROTECTED // OuterJavaClass.staticPrivateField: JAVA_STATIC PRIVATE : JAVA_STATIC PRIVATE // OuterJavaClass.InnerJavaClass: PUBLIC : PUBLIC // InnerJavaClass.<init>: FINAL PUBLIC : FINAL PUBLIC // OuterJavaClass.NestedJavaClass: JAVA_STATIC PUBLIC : JAVA_STATIC PUBLIC // NestedJavaClass.<init>: FINAL PUBLIC : FINAL PUBLIC // OuterJavaClass.staticPublicMethod: JAVA_STATIC PUBLIC : JAVA_STATIC PUBLIC // OuterJavaClass.staticPackageProtectedMethod: JAVA_STATIC : JAVA_STATIC // OuterJavaClass.staticProtectedMethod: JAVA_STATIC PROTECTED : JAVA_STATIC PROTECTED // OuterJavaClass.staticPrivateMethod: JAVA_STATIC PRIVATE : JAVA_STATIC PRIVATE // OuterJavaClass.<init>: FINAL PUBLIC : FINAL PUBLIC // OuterKotlinClass: OPEN : PUBLIC // OuterKotlinClass.InnerKotlinClass: INNER : FINAL PUBLIC // InnerKotlinClass.<init>: FINAL PUBLIC : FINAL PUBLIC // OuterKotlinClass.NestedKotlinClass: OPEN : PUBLIC // NestedKotlinClass.<init>: FINAL PUBLIC : FINAL PUBLIC // OuterKotlinClass.Companion: : FINAL JAVA_STATIC PUBLIC // Companion.companionMethod: : FINAL PUBLIC // Companion.companionField: CONST : FINAL PUBLIC // Companion.privateCompanionMethod: PRIVATE : FINAL PRIVATE // Companion.privateCompanionField: PRIVATE : FINAL PRIVATE // Companion.jvmStaticCompanionMethod: : FINAL JAVA_STATIC PUBLIC // Companion.jvmStaticCompanionField: : FINAL JAVA_STATIC PUBLIC // Companion.customJvmStaticCompanionMethod: : FINAL PUBLIC // Companion.customJvmStaticCompanionField: : FINAL PUBLIC // Companion.<init>: FINAL PUBLIC : FINAL PUBLIC // OuterKotlinClass.transientProperty: : FINAL JAVA_TRANSIENT PUBLIC // OuterKotlinClass.volatileProperty: : FINAL JAVA_VOLATILE PUBLIC // OuterKotlinClass.strictfpFun: : FINAL JAVA_STRICT PUBLIC // OuterKotlinClass.synchronizedFun: : FINAL JAVA_SYNCHRONIZED PUBLIC // OuterKotlinClass.<init>: FINAL PUBLIC : FINAL PUBLIC // DependencyOuterJavaClass: OPEN PUBLIC : PUBLIC // DependencyOuterJavaClass.DependencyNestedJavaClass: OPEN PUBLIC : PUBLIC // DependencyNestedJavaClass.<init>: FINAL PUBLIC : FINAL PUBLIC // DependencyOuterJavaClass.DependencyInnerJavaClass: INNER OPEN PUBLIC : PUBLIC // DependencyInnerJavaClass.<init>: FINAL PUBLIC : FINAL PUBLIC // DependencyOuterJavaClass.synchronizedFun: JAVA_SYNCHRONIZED OPEN : JAVA_SYNCHRONIZED // DependencyOuterJavaClass.strictfpFun: JAVA_STRICT OPEN : JAVA_STRICT // DependencyOuterJavaClass.transientField: FINAL JAVA_TRANSIENT : FINAL JAVA_TRANSIENT // DependencyOuterJavaClass.volatileField: FINAL JAVA_VOLATILE : FINAL JAVA_VOLATILE // DependencyOuterJavaClass.staticPublicMethod: JAVA_STATIC PUBLIC : JAVA_STATIC PUBLIC // DependencyOuterJavaClass.staticPackageProtectedMethod: JAVA_STATIC : JAVA_STATIC // DependencyOuterJavaClass.staticProtectedMethod: JAVA_STATIC PROTECTED : JAVA_STATIC PROTECTED // DependencyOuterJavaClass.staticPrivateMethod: JAVA_STATIC PRIVATE : JAVA_STATIC PRIVATE // DependencyOuterJavaClass.staticPublicField: FINAL JAVA_STATIC PUBLIC : FINAL JAVA_STATIC PUBLIC // DependencyOuterJavaClass.staticPackageProtectedField: FINAL JAVA_STATIC : FINAL JAVA_STATIC // DependencyOuterJavaClass.staticProtectedField: FINAL JAVA_STATIC PROTECTED : FINAL JAVA_STATIC PROTECTED // DependencyOuterJavaClass.staticPrivateField: FINAL JAVA_STATIC PRIVATE : FINAL JAVA_STATIC PRIVATE // DependencyOuterJavaClass.<init>: FINAL PUBLIC : FINAL PUBLIC // DependencyOuterKotlinClass: OPEN PUBLIC : PUBLIC // DependencyOuterKotlinClass.transientProperty: FINAL PUBLIC : FINAL JAVA_TRANSIENT PUBLIC // DependencyOuterKotlinClass.volatileProperty: FINAL PUBLIC : FINAL JAVA_VOLATILE PUBLIC // DependencyOuterKotlinClass.strictfpFun: FINAL PUBLIC : FINAL JAVA_STRICT PUBLIC // DependencyOuterKotlinClass.synchronizedFun: FINAL PUBLIC : FINAL JAVA_SYNCHRONIZED PUBLIC // DependencyOuterKotlinClass.Companion: FINAL PUBLIC : FINAL PUBLIC // Companion.companionField: FINAL PUBLIC : FINAL PUBLIC // Companion.customJvmStaticCompanionField: FINAL PUBLIC : FINAL PUBLIC // Companion.jvmStaticCompanionField: FINAL PUBLIC : FINAL PUBLIC // Companion.privateCompanionField: FINAL PUBLIC : FINAL PUBLIC // Companion.companionMethod: FINAL PUBLIC : FINAL PUBLIC // Companion.customJvmStaticCompanionMethod: FINAL PUBLIC : FINAL PUBLIC // Companion.jvmStaticCompanionMethod: FINAL PUBLIC : FINAL PUBLIC // Companion.privateCompanionMethod: FINAL PRIVATE : FINAL PRIVATE // Companion.<init>: FINAL PRIVATE : FINAL PRIVATE // DependencyOuterKotlinClass.DependencyInnerKotlinClass: FINAL INNER PUBLIC : FINAL PUBLIC // DependencyInnerKotlinClass.<init>: FINAL PUBLIC : FINAL PUBLIC // DependencyOuterKotlinClass.DependencyNestedKotlinClass: OPEN PUBLIC : PUBLIC // DependencyNestedKotlinClass.<init>: FINAL PUBLIC : FINAL PUBLIC // DependencyOuterKotlinClass.<init>: FINAL PUBLIC : FINAL PUBLIC // END // MODULE: module1 // FILE: DependencyOuterJavaClass.java public class DependencyOuterJavaClass { public class DependencyInnerJavaClass {} public static class DependencyNestedJavaClass {} public static void staticPublicMethod() {} public static String staticPublicField; static void staticPackageProtectedMethod() {} static String staticPackageProtectedField; protected static void staticProtectedMethod() {} protected static String staticProtectedField; private static void staticPrivateMethod() {} private static String staticPrivateField; transient String transientField = ""; volatile String volatileField = ""; synchronized String synchronizedFun() { return ""; } strictfp String strictfpFun() { return ""; } } // FILE: DependencyOuterKotlinClass.kt typealias DependencyCustomJvmStatic=JvmStatic open class DependencyOuterKotlinClass { inner class DependencyInnerKotlinClass open class DependencyNestedKotlinClass companion object { fun companionMethod() {} val companionField:String = "" private fun privateCompanionMethod() {} val privateCompanionField:String = "" @JvmStatic fun jvmStaticCompanionMethod() {} @JvmStatic val jvmStaticCompanionField:String = "" @DependencyCustomJvmStatic fun customJvmStaticCompanionMethod() {} @DependencyCustomJvmStatic val customJvmStaticCompanionField:String = "" } @Transient val transientProperty: String = "" @Volatile var volatileProperty: String = "" @Strictfp fun strictfpFun(): String = "" @Synchronized fun synchronizedFun(): String = "" } // MODULE: main(module1) // FILE: a.kt annotation class Test @Test class Foo : C() { } @Test class Bar : OuterJavaClass() @Test class Baz : OuterKotlinClass() @Test class JavaDependency : DependencyOuterJavaClass() @Test class KotlinDependency : DependencyOuterKotlinClass() // FILE: C.java public abstract class C { private String staticStr = "str" final transient String s1; protected static volatile int i1; default synchronized int intFun() { return 1; } abstract strictfp void foo() {} public static class NestedC { } public class InnerC { } } // FILE: OuterJavaClass.java public class OuterJavaClass { public class InnerJavaClass {} public static class NestedJavaClass {} public static void staticPublicMethod() {} public static String staticPublicField; static void staticPackageProtectedMethod() {} static String staticPackageProtectedField; protected static void staticProtectedMethod() {} protected static String staticProtectedField; private static void staticPrivateMethod() {} private static String staticPrivateField; } // FILE: OuterKotlinClass.kt typealias CustomJvmStatic=JvmStatic open class OuterKotlinClass { inner class InnerKotlinClass open class NestedKotlinClass companion object { fun companionMethod() {} const val companionField:String = "" private fun privateCompanionMethod() {} private val privateCompanionField:String = "" @JvmStatic fun jvmStaticCompanionMethod() {} @JvmStatic val jvmStaticCompanionField:String = "" @CustomJvmStatic fun customJvmStaticCompanionMethod() {} @CustomJvmStatic val customJvmStaticCompanionField:String = "" } @Transient val transientProperty: String = "" @Volatile var volatileProperty: String = "" @Strictfp fun strictfpFun(): String = "" @Synchronized fun synchronizedFun(): String = "" }
apache-2.0
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/flex/intentions/AddTestSpecExampleIntention.kt
1
2415
// Copyright (c) 2017-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.flex.intentions import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement import com.intellij.psi.PsiPlainText import com.vladsch.flexmark.test.util.spec.SpecReader import com.vladsch.md.nav.flex.psi.FlexmarkExampleSection import com.vladsch.md.nav.psi.element.MdBlankLine import com.vladsch.md.nav.psi.element.MdParagraph import com.vladsch.md.nav.psi.element.MdTextBlock import com.vladsch.md.nav.util.PsiElementPredicateWithEditor import com.vladsch.plugin.util.nullIf class AddTestSpecExampleIntention : InsertOrReplaceCaretTextIntention() { override fun getText(element: PsiElement, documentChars: CharSequence, selectionStart: Int, selectionEnd: Int): String { val isExampleSection = element.toString() != "PsiJavaToken:STRING_LITERAL" && (element is FlexmarkExampleSection || element.containingFile.context is FlexmarkExampleSection) val isStartOfLine = selectionStart > 0 && documentChars[selectionStart - 1] == '\n' val isEndOfLine = selectionEnd < documentChars.length && documentChars[selectionEnd] == '\n' val text = SpecReader.EXAMPLE_TEST_START + "\n" + SpecReader.SECTION_TEST_BREAK + "\n" + SpecReader.EXAMPLE_TEST_BREAK return if (isExampleSection) "\n".nullIf(isStartOfLine).orEmpty() + text + "\n".nullIf(isEndOfLine).orEmpty() else text } override fun getElementPredicate(): PsiElementPredicateWithEditor { return object : PsiElementPredicateWithEditor { override fun satisfiedBy(editor: Editor, selectionStart: Int, selectionEnd: Int): Boolean { return true } override fun satisfiedBy(element: PsiElement): Boolean { return element is PsiPlainText || element is MdParagraph || element.parent is MdTextBlock || element is MdBlankLine || element is FlexmarkExampleSection || element.containingFile.context is FlexmarkExampleSection || element.toString() == "PsiJavaToken:STRING_LITERAL" || element.toString() == "PsiJavaToken:CHARACTER_LITERAL" } } } }
apache-2.0
alygin/intellij-rust
src/main/kotlin/org/rust/lang/core/resolve/ref/RsModReferenceImpl.kt
2
866
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.resolve.ref import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RsModDeclItem import org.rust.lang.core.psi.ext.RsCompositeElement import org.rust.lang.core.resolve.* import org.rust.lang.core.types.BoundElement class RsModReferenceImpl( modDecl: RsModDeclItem ) : RsReferenceBase<RsModDeclItem>(modDecl), RsReference { override val RsModDeclItem.referenceAnchor: PsiElement get() = identifier override fun getVariants(): Array<out Any> = collectCompletionVariants { processModDeclResolveVariants(element, it) } override fun resolveInner(): List<BoundElement<RsCompositeElement>> = collectResolveVariants(element.referenceName) { processModDeclResolveVariants(element, it) } }
mit
jrasmuson/Shaphat
src/test/kotlin/DynamoIntegrationSpec.kt
1
2673
import DynamoUtils.createNewTable import DynamoUtils.tableName import com.amazonaws.client.builder.AwsClientBuilder import com.amazonaws.services.dynamodbv2.AmazonDynamoDB import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper import com.amazonaws.services.dynamodbv2.local.embedded.DynamoDBEmbedded import models.AlreadyFinishedRequest import models.ModerationResult import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import kotlin.test.assertEquals // Spek can't give jvm arguments to test so have to use junit //Also Spek is having problems stopping the database so the test keeps running //object DynamoIntegrationSpec : Spek({ // var amazonDynamoDB:AmazonDynamoDB? = DynamoDBEmbedded.create().amazonDynamoDB() // createNewTable(amazonDynamoDB) // val dynamoClient = DynamoClient(DynamoDBMapper(amazonDynamoDB), tableName) // given("a dynamo connection") { // // val endpoint = AwsClientBuilder.EndpointConfiguration("http://localhost:8000", "") //// val amazonDynamoDB = AmazonDynamoDBClientBuilder.standard().withEndpointConfiguration(endpoint).build() // // //// on("creating a table") { //// it("returns success") { //// val createNewTable = createNewTable(amazonDynamoDB) //// assertEquals(tableName, createNewTable.tableName) //// } //// } // // on("loading an empty list") { // it("doesn't have any failed batches") { // val batchWrite = dynamoClient.batchWrite(emptyList<ModerationResult>()) // assertEquals(0, batchWrite.size) // } // } // // on("loading one item") { // val result = ModerationResult("test.com", "http://test.com/image1") // it("load successfully") { // val batchWrite = dynamoClient.batchWrite(listOf(result)) // assertEquals(0, batchWrite.size) // } // } // on("get back the request") { // val request = AlreadyFinishedRequest("test.com", "http://test.com/insertedImage.jpg") // dynamoClient.batchWrite(listOf(request)) // it("get the one result") { // val batchWrite = dynamoClient.batchGet(listOf(request)) // assertEquals(1, batchWrite?.size) // } // } // // } // afterGroup{ // println("before shut") // amazonDynamoDB?.shutdown() // amazonDynamoDB=null // println("after shut") // } //})
apache-2.0
JimSeker/ui
Navigation/MenuDemo_kt/app/src/main/java/edu/cs4730/menudemo_kt/MainActivity.kt
1
2247
package edu.cs4730.menudemo_kt import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.PopupMenu class MainActivity : AppCompatActivity() { lateinit var popup: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) popup = findViewById<View>(R.id.label2) as TextView popup.setOnClickListener { v -> showPopupMenu(v) //this is to the code below, not an API call. } } private fun showPopupMenu(v: View) { val popupM = PopupMenu( this, v ) //note "this" is the activity context, if you are using this in a fragment. using getActivity() popupM.inflate(R.menu.popup) popupM.setOnMenuItemClickListener { item -> Toast.makeText(applicationContext, item.toString(), Toast.LENGTH_LONG).show() true } popupM.show() } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. val id = item.itemId if (id == R.id.menuandfragdemo) { startActivity(Intent(this@MainActivity, FragMenuActivity::class.java)) return true } else if (id == R.id.actbaritemsdemo) { startActivity(Intent(this@MainActivity, ActionMenuActivity::class.java)) return true } else if (id == R.id.viewpagerbuttondemo) { startActivity(Intent(this@MainActivity, ViewPagerButtonMenuActivity::class.java)) return true } return super.onOptionsItemSelected(item) } }
apache-2.0
paronos/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/recently_read/RecentlyReadController.kt
3
3892
package eu.kanade.tachiyomi.ui.recently_read import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import eu.davidea.flexibleadapter.FlexibleAdapter import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.models.History import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.ui.base.controller.NucleusController import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction import eu.kanade.tachiyomi.ui.manga.MangaController import eu.kanade.tachiyomi.ui.reader.ReaderActivity import eu.kanade.tachiyomi.util.toast import kotlinx.android.synthetic.main.recently_read_controller.* /** * Fragment that shows recently read manga. * Uses R.layout.fragment_recently_read. * UI related actions should be called from here. */ class RecentlyReadController : NucleusController<RecentlyReadPresenter>(), FlexibleAdapter.OnUpdateListener, RecentlyReadAdapter.OnRemoveClickListener, RecentlyReadAdapter.OnResumeClickListener, RecentlyReadAdapter.OnCoverClickListener, RemoveHistoryDialog.Listener { /** * Adapter containing the recent manga. */ var adapter: RecentlyReadAdapter? = null private set override fun getTitle(): String? { return resources?.getString(R.string.label_recent_manga) } override fun createPresenter(): RecentlyReadPresenter { return RecentlyReadPresenter() } override fun inflateView(inflater: LayoutInflater, container: ViewGroup): View { return inflater.inflate(R.layout.recently_read_controller, container, false) } /** * Called when view is created * * @param view created view */ override fun onViewCreated(view: View) { super.onViewCreated(view) // Initialize adapter recycler.layoutManager = LinearLayoutManager(view.context) adapter = RecentlyReadAdapter(this@RecentlyReadController) recycler.setHasFixedSize(true) recycler.adapter = adapter } override fun onDestroyView(view: View) { adapter = null super.onDestroyView(view) } /** * Populate adapter with chapters * * @param mangaHistory list of manga history */ fun onNextManga(mangaHistory: List<RecentlyReadItem>) { adapter?.updateDataSet(mangaHistory) } override fun onUpdateEmptyView(size: Int) { if (size > 0) { empty_view.hide() } else { empty_view.show(R.drawable.ic_glasses_black_128dp, R.string.information_no_recent_manga) } } override fun onResumeClick(position: Int) { val activity = activity ?: return val (manga, chapter, _) = adapter?.getItem(position)?.mch ?: return val nextChapter = presenter.getNextChapter(chapter, manga) if (nextChapter != null) { val intent = ReaderActivity.newIntent(activity, manga, nextChapter) startActivity(intent) } else { activity.toast(R.string.no_next_chapter) } } override fun onRemoveClick(position: Int) { val (manga, _, history) = adapter?.getItem(position)?.mch ?: return RemoveHistoryDialog(this, manga, history).showDialog(router) } override fun onCoverClick(position: Int) { val manga = adapter?.getItem(position)?.mch?.manga ?: return router.pushController(MangaController(manga).withFadeTransaction()) } override fun removeHistory(manga: Manga, history: History, all: Boolean) { if (all) { // Reset last read of chapter to 0L presenter.removeAllFromHistory(manga.id!!) } else { // Remove all chapters belonging to manga from library presenter.removeFromHistory(history) } } }
apache-2.0
dataloom/conductor-client
src/main/kotlin/com/openlattice/data/storage/SqlBinder.kt
1
370
package com.openlattice.data.storage import com.openlattice.analysis.SqlBindInfo import java.sql.PreparedStatement /** * * @author Matthew Tamayo-Rios &lt;[email protected]&gt; */ data class SqlBinder(val bindInfo: SqlBindInfo, val binding: (PreparedStatement, SqlBindInfo) -> Unit) { fun bind(ps:PreparedStatement) { binding(ps, bindInfo) } }
gpl-3.0
http4k/http4k
http4k-core/src/main/kotlin/org/http4k/KotlinExtensions.kt
1
1401
package org.http4k import java.net.URLEncoder import java.nio.ByteBuffer import java.util.Base64 fun ByteBuffer.length() = limit() - position() fun ByteBuffer.asString(): String = String(array(), position(), length()) fun ByteBuffer.base64Encode() : String = Base64.getEncoder().encodeToString(array()) fun String.asByteBuffer(): ByteBuffer = ByteBuffer.wrap(toByteArray()) fun String.quoted() = "\"${replace("\"", "\\\"")}\"" fun String.unquoted(): String = replaceFirst("^\"".toRegex(), "").replaceFirst("\"$".toRegex(), "").replace("\\\"", "\"") fun StringBuilder.appendIfNotBlank(valueToCheck: String, vararg toAppend: String): StringBuilder = appendIf({ valueToCheck.isNotBlank() }, *toAppend) fun StringBuilder.appendIfNotEmpty(valueToCheck: List<Any>, vararg toAppend: String): StringBuilder = appendIf({ valueToCheck.isNotEmpty() }, *toAppend) fun StringBuilder.appendIfPresent(valueToCheck: Any?, vararg toAppend: String): StringBuilder = appendIf({ valueToCheck != null }, *toAppend) fun StringBuilder.appendIf(condition: () -> Boolean, vararg toAppend: String): StringBuilder = apply { if (condition()) toAppend.forEach { append(it) } } fun String.base64Decoded(): String = String(Base64.getDecoder().decode(this)) fun String.base64Encode() = String(Base64.getEncoder().encode(toByteArray())) fun String.urlEncoded(): String = URLEncoder.encode(this, "utf-8")
apache-2.0
Zukkari/nirdizati-training-ui
src/main/kotlin/cs/ut/logging/UserIdentifier.kt
1
919
package cs.ut.logging import org.apache.logging.log4j.core.LogEvent import org.apache.logging.log4j.core.config.plugins.Plugin import org.apache.logging.log4j.core.pattern.ConverterKeys import org.apache.logging.log4j.core.pattern.LogEventPatternConverter import java.lang.StringBuilder @Plugin(name = "connId", category = "Converter") @ConverterKeys("connId") class UserIdentifier : LogEventPatternConverter("userId", "userId") { override fun format(logEvent: LogEvent, buffer: StringBuilder) { val key = logEvent.contextData.getValue<String>("${logEvent.threadName}-connId") ?: "" buffer.append("[") buffer.append(if (key.isBlank()) "SYSTEM" else key) buffer.append("]") } companion object { const val CONN_ID = "connId" @JvmStatic fun newInstance(options: Array<String>): UserIdentifier { return UserIdentifier() } } }
lgpl-3.0
Retronic/life-in-space
core/src/main/kotlin/com/retronicgames/lis/mission/resources/ResourceManager.kt
1
1580
/** * Copyright (C) 2015 Oleg Dolya * Copyright (C) 2015 Eduardo Garcia * * This file is part of Life in Space, by Retronic Games * * Life in Space 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. * * Life in Space 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 Life in Space. If not, see <http://www.gnu.org/licenses/>. */ package com.retronicgames.lis.mission.resources import com.badlogic.gdx.utils.ObjectMap import com.badlogic.gdx.utils.OrderedMap import com.retronicgames.gdx.set import com.retronicgames.lis.mission.Mission import com.retronicgames.utils.value.MutableValue class ResourceManager(mission: Mission):Iterable<ObjectMap.Entry<ResourceType, MutableValue<Int>>> { private val resources = OrderedMap<ResourceType, MutableValue<Int>>(ResourceType.values().size) init { ResourceType.values().forEach { resourceType -> resources[resourceType] = MutableValue(0) } mission.initialResources().forEach { entry -> resources[entry.key].value = entry.value } } override fun iterator() = resources.iterator() fun getResourceQuantity(type: ResourceType) = resources.get(type).value }
gpl-3.0
adammurdoch/native-platform
.teamcity/NativePlatformCompatibilityTest.kt
1
1484
import jetbrains.buildServer.configs.kotlin.v2019_2.BuildType import jetbrains.buildServer.configs.kotlin.v2019_2.DslContext import jetbrains.buildServer.configs.kotlin.v2019_2.FailureAction import jetbrains.buildServer.configs.kotlin.v2019_2.RelativeId import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.gradle class NativePlatformCompatibilityTest(agent: Agent, buildDependencies: List<BuildType>, init: BuildType.() -> Unit = {}) : BuildType({ name = "Compatibility test on $agent" id = RelativeId("CompatibilityTest$agent") runOn(agent) steps { gradle { tasks = "clean :native-platform:test :file-events:test -PtestVersionFromLocalRepository" buildFile = "" } } vcs { root(DslContext.settingsRoot) } features { publishCommitStatus() lowerRequiredFreeDiskSpace() } failureConditions { testFailure = false executionTimeoutMin = 15 } artifactRules = """ hs_err* **/build/**/output.txt """.trimIndent() + "\n$archiveReports" dependencies { buildDependencies.forEach { snapshot(it) { onDependencyFailure = FailureAction.FAIL_TO_START } dependency(it) { artifacts { cleanDestination = true artifactRules = "repo => incoming-repo/" } } } } init(this) })
apache-2.0
bertilxi/Chilly_Willy_Delivery
mobile/app/src/main/java/dam/isi/frsf/utn/edu/ar/delivery/model/Deal.kt
1
1494
package dam.isi.frsf.utn.edu.ar.delivery.model import android.os.Parcel import android.os.Parcelable import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName data class Deal( @SerializedName("title") @Expose var title: String = "", @SerializedName("description") @Expose var description: String = "", @SerializedName("isLastDeal") @Expose var isLastDeal: Boolean = false ) : Parcelable { fun withTitle(title: String): Deal { this.title = title return this } fun withDescription(description: String): Deal { this.description = description return this } fun withIsLastDeal(isLastDeal: Boolean): Deal { this.isLastDeal = isLastDeal return this } companion object { @JvmField val CREATOR: Parcelable.Creator<Deal> = object : Parcelable.Creator<Deal> { override fun createFromParcel(source: Parcel): Deal = Deal(source) override fun newArray(size: Int): Array<Deal?> = arrayOfNulls(size) } } constructor(source: Parcel) : this( source.readString(), source.readString(), 1 == source.readInt() ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(title) dest.writeString(description) dest.writeInt((if (isLastDeal) 1 else 0)) } }
mit
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/async/TaskManager.kt
1
6993
/**************************************************************************************** * Copyright (c) 2021 Arthur Milchior <[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.async import android.content.res.Resources import androidx.annotation.VisibleForTesting /** * The TaskManager has two related purposes. * * A concrete TaskManager's mission is to take a TaskDelegate, potentially a CollectionListener, and execute them. * Currently, the default TaskManager is SingleTaskManager, which executes the tasks in order in which they are generated. It essentially consists in using basic AsyncTask properties with CollectionTask. * It should eventually be replaced by non deprecated system. * * The only other TaskManager currently is ForegroundTaskManager, which runs everything foreground and is used for unit testings. * * The class itself contains a static element which is the currently used TaskManager. Tasks can be executed on the current TaskManager with the static method launchTaskManager. */ abstract class TaskManager { protected abstract fun removeTaskConcrete(task: CollectionTask<*, *>): Boolean abstract fun <Progress, Result> launchCollectionTaskConcrete(task: TaskDelegateBase<Progress, Result>): Cancellable protected abstract fun setLatestInstanceConcrete(task: CollectionTask<*, *>) abstract fun <Progress, Result> launchCollectionTaskConcrete( task: TaskDelegateBase<Progress, Result>, listener: TaskListener<in Progress, in Result?>? ): Cancellable abstract fun waitToFinishConcrete() abstract fun waitToFinishConcrete(timeoutSeconds: Int?): Boolean abstract fun cancelCurrentlyExecutingTaskConcrete() abstract fun cancelAllTasksConcrete(taskType: Class<*>) abstract fun waitForAllToFinishConcrete(timeoutSeconds: Int): Boolean /** * Helper class for allowing inner function to publish progress of an AsyncTask. */ @Suppress("SENSELESS_COMPARISON") class ProgressCallback<Progress>(task: ProgressSender<Progress>, val resources: Resources) { private var mTask: ProgressSender<Progress>? = null fun publishProgress(value: Progress) { mTask?.doProgress(value) } init { if (resources != null) { mTask = task } else { mTask = null } } } companion object { private var sTaskManager: TaskManager = SingleTaskManager() /** * @param tm The new task manager * @return The previous one. It may still have tasks running */ @VisibleForTesting fun setTaskManager(tm: TaskManager): TaskManager { val previous = sTaskManager sTaskManager = tm return previous } fun removeTask(task: CollectionTask<*, *>): Boolean { return sTaskManager.removeTaskConcrete(task) } /** * Starts a new [CollectionTask], with no listener * * * Tasks will be executed serially, in the order in which they are started. * * * This method must be called on the main thread. * * @param task the task to execute * @return the newly created task */ fun setLatestInstance(task: CollectionTask<*, *>) { sTaskManager.setLatestInstanceConcrete(task) } fun <Progress, Result> launchCollectionTask(task: TaskDelegateBase<Progress, Result>): Cancellable { return sTaskManager.launchCollectionTaskConcrete(task) } /** * Starts a new [CollectionTask], with a listener provided for callbacks during execution * * * Tasks will be executed serially, in the order in which they are started. * * * This method must be called on the main thread. * * @param task the task to execute * @param listener to the status and result of the task, may be null * @return the newly created task */ fun <Progress, Result> launchCollectionTask( task: TaskDelegateBase<Progress, Result>, listener: TaskListener<in Progress, in Result?>? ): Cancellable { return sTaskManager.launchCollectionTaskConcrete(task, listener) } /** * Block the current thread until the currently running CollectionTask instance (if any) has finished. */ fun waitToFinish() { sTaskManager.waitToFinishConcrete() } /** * Block the current thread until the currently running CollectionTask instance (if any) has finished. * @param timeoutSeconds timeout in seconds (or null to wait indefinitely) * @return whether or not the previous task was successful or not, OR if an exception occurred (for example: timeout) */ fun waitToFinish(timeoutSeconds: Int?): Boolean { return sTaskManager.waitToFinishConcrete(timeoutSeconds) } /** Cancel the current task only if it's of type taskType */ fun cancelCurrentlyExecutingTask() { sTaskManager.cancelCurrentlyExecutingTaskConcrete() } /** Cancel all tasks of type taskType */ fun cancelAllTasks(taskType: Class<*>) { sTaskManager.cancelAllTasksConcrete(taskType) } /** * Block the current thread until all CollectionTasks have finished. * @param timeoutSeconds timeout in seconds * @return whether all tasks exited successfully */ fun waitForAllToFinish(timeoutSeconds: Int): Boolean { return sTaskManager.waitForAllToFinishConcrete(timeoutSeconds) } } }
gpl-3.0
cemrich/zapp
app/src/main/java/de/christinecoenen/code/zapp/app/settings/helper/ShortcutPreference.kt
1
2486
package de.christinecoenen.code.zapp.app.settings.helper import android.annotation.TargetApi import android.content.Context import android.text.TextUtils import android.util.AttributeSet import android.widget.Toast import androidx.preference.MultiSelectListPreference import androidx.preference.Preference import de.christinecoenen.code.zapp.R import de.christinecoenen.code.zapp.models.channels.IChannelList import de.christinecoenen.code.zapp.models.channels.json.JsonChannelList import de.christinecoenen.code.zapp.utils.system.ShortcutHelper.areShortcutsSupported import de.christinecoenen.code.zapp.utils.system.ShortcutHelper.getChannelIdsOfShortcuts import de.christinecoenen.code.zapp.utils.system.ShortcutHelper.updateShortcutsToChannels import java.util.* class ShortcutPreference @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : MultiSelectListPreference(context, attrs), Preference.OnPreferenceChangeListener { private lateinit var channelList: IChannelList init { if (areShortcutsSupported()) { loadChannelList() setSummaryToSelectedChannels() isEnabled = true } } override fun onPreferenceChange(preference: Preference, selectedValues: Any): Boolean { @Suppress("UNCHECKED_CAST") val selectedIds = selectedValues as Set<String> val success = saveShortcuts(selectedIds) if (!success) { // shortcuts could not be saved Toast.makeText(context, R.string.pref_shortcuts_too_many, Toast.LENGTH_LONG).show() } loadValuesFromShortcuts() setSummaryToSelectedChannels() return success } private fun loadChannelList() { channelList = JsonChannelList(context) val entries = channelList.map { it.name } val values = channelList.map { it.id } setEntries(entries.toTypedArray()) // human readable entryValues = values.toTypedArray() // ids loadValuesFromShortcuts() } private fun loadValuesFromShortcuts() { val shortcutIds = getChannelIdsOfShortcuts(context) values = HashSet(shortcutIds) } @TargetApi(25) private fun saveShortcuts(channelIds: Set<String>): Boolean { val channels = channelIds.map { channelList[it]!! } return updateShortcutsToChannels(context, channels) } private fun setSummaryToSelectedChannels() { if (values.size == 0) { setSummary(R.string.pref_shortcuts_summary_limit) return } val selectedChannelNames = channelList .filter { values.contains(it.id) } .map { it.name } summary = TextUtils.join(", ", selectedChannelNames) } }
mit
matkoniecz/StreetComplete
app/src/test/java/de/westnordost/streetcomplete/data/elementfilter/filters/HasTagValueLikeTest.kt
2
1337
package de.westnordost.streetcomplete.data.elementfilter.filters import de.westnordost.streetcomplete.data.elementfilter.matches import org.junit.Assert.* import org.junit.Test class HasTagValueLikeTest { @Test fun `matches like dot`() { val f = HasTagValueLike("highway",".esidential") assertTrue(f.matches(mapOf("highway" to "residential"))) assertTrue(f.matches(mapOf("highway" to "wesidential"))) assertFalse(f.matches(mapOf("highway" to "rresidential"))) assertFalse(f.matches(mapOf())) } @Test fun `matches like or`() { val f = HasTagValueLike("highway", "residential|unclassified") assertTrue(f.matches(mapOf("highway" to "residential"))) assertTrue(f.matches(mapOf("highway" to "unclassified"))) assertFalse(f.matches(mapOf("highway" to "blub"))) assertFalse(f.matches(mapOf())) } @Test fun `groups values properly`() { val f = HasTagValueLike("highway", "residential|unclassified") assertEquals( "[highway ~ '^(residential|unclassified)$']", f.toOverpassQLString() ) } @Test fun `key value to string`() { val f = HasTagValueLike("highway",".*") assertEquals( "[highway ~ '^(.*)$']", f.toOverpassQLString() ) } }
gpl-3.0
matkoniecz/StreetComplete
app/src/test/java/de/westnordost/streetcomplete/ktx/ElementTest.kt
1
1700
package de.westnordost.streetcomplete.ktx import de.westnordost.streetcomplete.testutils.rel import de.westnordost.streetcomplete.testutils.way import org.junit.Assert.* import org.junit.Test class ElementTest { @Test fun `relation with no tags is no area`() { assertFalse(rel().isArea()) } @Test fun `way is closed`() { assertTrue(createRing().isClosed) } @Test fun `way is not closed`() { assertFalse(createWay().isClosed) } @Test fun `multipolygon relation is an area`() { assertTrue(rel(tags = mapOf("type" to "multipolygon")).isArea()) } @Test fun `way with no tags is no area`() { assertFalse(createWay().isArea()) assertFalse(createRing().isArea()) } @Test fun `simple way with area=yes tag is no area`() { assertFalse(createWay(mapOf("area" to "yes")).isArea()) } @Test fun `closed way with area=yes tag is an area`() { assertTrue(createRing(mapOf("area" to "yes")).isArea()) } @Test fun `closed way with specific value of a key that is usually no area is an area`() { assertFalse(createRing(mapOf("railway" to "something")).isArea()) assertTrue(createRing(mapOf("railway" to "station")).isArea()) } @Test fun `closed way with a certain tag value is an area`() { assertFalse(createRing(mapOf("waterway" to "duck")).isArea()) assertTrue(createRing(mapOf("waterway" to "dock")).isArea()) } private fun createWay(tags: Map<String, String> = emptyMap()) = way(nodes = listOf(0L, 1L), tags = tags) private fun createRing(tags: Map<String, String> = emptyMap()) = way(nodes = listOf(0L, 1L, 0L), tags = tags) }
gpl-3.0
wordpress-mobile/WordPress-Stores-Android
fluxc/src/main/java/org/wordpress/android/fluxc/model/scan/ScanStateModel.kt
2
1689
package org.wordpress.android.fluxc.model.scan import org.wordpress.android.fluxc.model.scan.threat.ThreatModel import java.util.Date data class ScanStateModel( val state: State, val reason: Reason, val threats: List<ThreatModel>? = null, val credentials: List<Credentials>? = null, val hasCloud: Boolean = false, val mostRecentStatus: ScanProgressStatus? = null, val currentStatus: ScanProgressStatus? = null, val hasValidCredentials: Boolean = false ) { enum class State(val value: String) { IDLE("idle"), SCANNING("scanning"), PROVISIONING("provisioning"), UNAVAILABLE("unavailable"), UNKNOWN("unknown"); companion object { fun fromValue(value: String): State? { return values().firstOrNull { it.value == value } } } } data class Credentials( val type: String, val role: String, val host: String?, val port: Int?, val user: String?, val path: String?, val stillValid: Boolean ) data class ScanProgressStatus( val startDate: Date?, val duration: Int = 0, val progress: Int = 0, val error: Boolean = false, val isInitial: Boolean = false ) enum class Reason(val value: String?) { MULTISITE_NOT_SUPPORTED("multisite_not_supported"), VP_ACTIVE_ON_SITE("vp_active_on_site"), NO_REASON(null), UNKNOWN("unknown"); companion object { fun fromValue(value: String?): Reason { return values().firstOrNull { it.value == value } ?: UNKNOWN } } } }
gpl-2.0
openMF/self-service-app
app/src/main/java/org/mifos/mobile/models/accounts/loan/Currency.kt
1
764
package org.mifos.mobile.models.accounts.loan import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize /** * Created by dilpreet on 27/2/17. */ @Parcelize data class Currency( @SerializedName("code") var code: String, @SerializedName("name") var name: String, @SerializedName("decimalPlaces") var decimalPlaces: Double? = null, @SerializedName("inMultiplesOf") var inMultiplesOf: Double? = null, @SerializedName("displaySymbol") var displaySymbol: String, @SerializedName("nameCode") var nameCode: String, @SerializedName("displayLabel") var displayLabel: String ) : Parcelable
mpl-2.0
yujintao529/android_practice
MyPractice/app/src/main/java/com/demon/yu/kotlin/CoroutinesEventBusKt.kt
1
30
package com.demon.yu.kotlin
apache-2.0
wordpress-mobile/WordPress-Stores-Android
example/src/test/java/org/wordpress/android/fluxc/wc/order/WCOrderListDescriptorTest.kt
1
4891
package org.wordpress.android.fluxc.wc.order import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.junit.runners.Parameterized.Parameters import org.wordpress.android.fluxc.list.ListDescriptorUnitTestCase import org.wordpress.android.fluxc.list.post.LIST_DESCRIPTOR_TEST_FIRST_MOCK_SITE_LOCAL_SITE_ID import org.wordpress.android.fluxc.list.post.LIST_DESCRIPTOR_TEST_QUERY_1 import org.wordpress.android.fluxc.list.post.LIST_DESCRIPTOR_TEST_QUERY_2 import org.wordpress.android.fluxc.list.post.LIST_DESCRIPTOR_TEST_SECOND_MOCK_SITE_LOCAL_SITE_ID import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.WCOrderListDescriptor private typealias WCOrderListDescriptorTestCase = ListDescriptorUnitTestCase<WCOrderListDescriptor> @RunWith(Parameterized::class) internal class WCOrderListDescriptorTest( private val testCase: WCOrderListDescriptorTestCase ) { companion object { @JvmStatic @Parameters fun testCases(): List<WCOrderListDescriptorTestCase> { val mockSite = mock<SiteModel>() val mockSite2 = mock<SiteModel>() whenever(mockSite.id).thenReturn(LIST_DESCRIPTOR_TEST_FIRST_MOCK_SITE_LOCAL_SITE_ID) whenever(mockSite2.id).thenReturn(LIST_DESCRIPTOR_TEST_SECOND_MOCK_SITE_LOCAL_SITE_ID) return listOf( // Same site WCOrderListDescriptorTestCase( typeIdentifierReason = "Same sites should have same type identifier", uniqueIdentifierReason = "Same sites should have same unique identifier", descriptor1 = WCOrderListDescriptor(site = mockSite), descriptor2 = WCOrderListDescriptor(site = mockSite), shouldHaveSameTypeIdentifier = true, shouldHaveSameUniqueIdentifier = true ), // Different site WCOrderListDescriptorTestCase( typeIdentifierReason = "Different sites should have different type identifiers", uniqueIdentifierReason = "Different sites should have different unique identifiers", descriptor1 = WCOrderListDescriptor(site = mockSite), descriptor2 = WCOrderListDescriptor(site = mockSite2), shouldHaveSameTypeIdentifier = false, shouldHaveSameUniqueIdentifier = false ), // Different status filters WCOrderListDescriptorTestCase( typeIdentifierReason = "Different status filters should have same type identifiers", uniqueIdentifierReason = "Different status filters should have different " + "unique identifiers", descriptor1 = WCOrderListDescriptor( site = mockSite, statusFilter = LIST_DESCRIPTOR_TEST_QUERY_1 ), descriptor2 = WCOrderListDescriptor( site = mockSite, statusFilter = LIST_DESCRIPTOR_TEST_QUERY_2 ), shouldHaveSameTypeIdentifier = true, shouldHaveSameUniqueIdentifier = false ), // Different search query WCOrderListDescriptorTestCase( typeIdentifierReason = "Different search queries should have same type identifiers", uniqueIdentifierReason = "Different search queries should have different " + "unique identifiers", descriptor1 = WCOrderListDescriptor( site = mockSite, searchQuery = LIST_DESCRIPTOR_TEST_QUERY_1 ), descriptor2 = WCOrderListDescriptor( site = mockSite, statusFilter = LIST_DESCRIPTOR_TEST_QUERY_2 ), shouldHaveSameTypeIdentifier = true, shouldHaveSameUniqueIdentifier = false ) ) } } @Test fun `test type identifier`() { testCase.testTypeIdentifier() } @Test fun `test unique identifier`() { testCase.testUniqueIdentifier() } }
gpl-2.0
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/text/LanternTextRenderer.kt
1
10250
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.text import net.kyori.adventure.text.BuildableComponent import net.kyori.adventure.text.NBTComponentBuilder import net.kyori.adventure.text.event.HoverEvent import net.kyori.adventure.text.format.Style import net.kyori.adventure.text.renderer.AbstractComponentRenderer import org.lanternpowered.api.text.BlockDataText import org.lanternpowered.api.text.DataText import org.lanternpowered.api.text.EntityDataText import org.lanternpowered.api.text.KeybindText import org.lanternpowered.api.text.LiteralText import org.lanternpowered.api.text.ScoreText import org.lanternpowered.api.text.SelectorText import org.lanternpowered.api.text.StorageDataText import org.lanternpowered.api.text.Text import org.lanternpowered.api.text.TextBuilder import org.lanternpowered.api.text.TranslatableText import org.lanternpowered.api.text.textOf import java.text.MessageFormat abstract class LanternTextRenderer<C> : AbstractComponentRenderer<C>() { companion object { private val Merges = Style.Merge.of( Style.Merge.COLOR, Style.Merge.DECORATIONS, Style.Merge.INSERTION, Style.Merge.FONT) } protected fun <T : BuildableComponent<T, B>, B : TextBuilder<T, B>> B.applyChildren(text: Text, context: C): B = apply { for (child in text.children()) this.append(render(child, context)) } protected fun <T : BuildableComponent<T, B>, B : TextBuilder<T, B>> B.applyStyle(text: Text, context: C): B = apply { this.mergeStyle(text, Merges) this.clickEvent(text.clickEvent()) this.insertion(text.insertion()) this.hoverEvent(renderHoverEventIfNeeded(text.hoverEvent(), context) ?: text.hoverEvent()) } protected fun <T : BuildableComponent<T, B>, B : TextBuilder<T, B>> B.applyStyleAndChildren(text: Text, context: C): B = this.applyChildren(text, context).applyStyle(text, context) private fun <T : DataText<T, B>, B : NBTComponentBuilder<T, B>> B.applyNbt(text: DataText<*, *>): B = apply { this.nbtPath(text.nbtPath()) this.interpret(text.interpret()) } final override fun renderText(text: LiteralText, context: C): Text = this.renderLiteralIfNeeded(text, context) ?: text final override fun renderStorageNbt(text: StorageDataText, context: C): Text = this.renderStorageNbtIfNeeded(text, context) ?: text final override fun renderEntityNbt(text: EntityDataText, context: C): Text = this.renderEntityNbtIfNeeded(text, context) ?: text final override fun renderBlockNbt(text: BlockDataText, context: C): Text = this.renderBlockNbtIfNeeded(text, context) ?: text final override fun renderScore(text: ScoreText, context: C): Text = this.renderScoreIfNeeded(text, context) ?: text final override fun renderKeybind(text: KeybindText, context: C): Text = this.renderKeybindIfNeeded(text, context) ?: text final override fun renderSelector(text: SelectorText, context: C): Text = this.renderSelectorIfNeeded(text, context) ?: text final override fun renderTranslatable(text: TranslatableText, context: C): Text = this.renderTranslatableIfNeeded(text, context) ?: text protected open fun renderLiteralIfNeeded(text: LiteralText, context: C): Text? { return this.renderIfNeeded(text, context) { Text.text().content(text.content()) } } protected open fun renderStorageNbtIfNeeded(text: StorageDataText, context: C): Text? { return this.renderIfNeeded(text, context) { Text.storageNBT() .storage(text.storage()) .applyNbt(text) } } protected open fun renderEntityNbtIfNeeded(text: EntityDataText, context: C): Text? { return this.renderIfNeeded(text, context) { Text.entityNBT() .selector(text.selector()) .applyNbt(text) } } protected open fun renderBlockNbtIfNeeded(text: BlockDataText, context: C): Text? { return this.renderIfNeeded(text, context) { Text.blockNBT() .pos(text.pos()) .applyNbt(text) } } protected open fun renderScoreIfNeeded(text: ScoreText, context: C): Text? { return this.renderIfNeeded(text, context) { Text.score() .objective(text.objective()) .value(text.value()) .name(text.name()) } } protected open fun renderKeybindIfNeeded(text: KeybindText, context: C): Text? { return this.renderIfNeeded(text, context) { Text.keybind().keybind(text.keybind()) } } protected open fun renderSelectorIfNeeded(text: SelectorText, context: C): Text? { return this.renderIfNeeded(text, context) { Text.selector().pattern(text.pattern()) } } protected open fun renderTranslatableIfNeeded(text: TranslatableText, context: C): Text? { val format = this.translate(text.key(), context) val args = text.args() if (format == null) { val renderedArgs = this.renderListIfNeeded(text.args(), context) return this.renderIfNeeded(text, context, force = renderedArgs != null) { Text.translatable().key(text.key()) .args(renderedArgs ?: args) } } val builder = Text.text() if (args.isEmpty()) return builder.content(format.format(null, StringBuffer(), null).toString()) .applyStyleAndChildren(text, context) .build() val nulls = arrayOfNulls<Any>(args.size) val sb = format.format(nulls, StringBuffer(), null) val itr = format.formatToCharacterIterator(nulls) while (itr.index < itr.endIndex) { val end = itr.runLimit val index = itr.getAttribute(MessageFormat.Field.ARGUMENT) as Int? if (index != null) { builder.append(this.render(args[index], context)) } else { builder.append(textOf(sb.substring(itr.index, end))) } itr.index = end } return builder.applyStyleAndChildren(text, context).build() } private fun <T : Text, B : TextBuilder<T, B>> renderIfNeeded( text: Text, context: C, force: Boolean = false, builderSupplier: () -> B ): T? { val children = this.renderListIfNeeded(text.children(), context) val hoverEvent = this.renderHoverEventIfNeeded(text.hoverEvent(), context) if (children == null && hoverEvent == null && !force) return null val builder = builderSupplier() builder.append(children ?: text.children()) builder.mergeStyle(text, Style.Merge.colorAndDecorations()) builder.hoverEvent(hoverEvent ?: text.hoverEvent()) builder.clickEvent(text.clickEvent()) builder.insertion(text.insertion()) return builder.build() } protected fun renderHoverEventIfNeeded(hoverEvent: HoverEvent<*>?, context: C): HoverEvent<*>? { if (hoverEvent == null) return null return when (val value = hoverEvent.value()) { is Text -> { val text = this.renderIfNeeded(value, context) ?: return null HoverEvent.showText(text) } is HoverEvent.ShowEntity -> { val name = value.name() ?: return null val text = this.renderIfNeeded(name, context) ?: return null HoverEvent.showEntity(HoverEvent.ShowEntity.of(value.type(), value.id(), text)) } is HoverEvent.ShowItem -> null // TODO else -> hoverEvent.withRenderedValue(this, context) } } /** * Renders the given [Text] for the [context]. This function will return `null` * in case nothing changed to the contents when rendering. */ fun renderIfNeeded(text: Text, context: C): Text? { return when (text) { is LiteralText -> this.renderLiteralIfNeeded(text, context) is TranslatableText -> this.renderTranslatableIfNeeded(text, context) is KeybindText -> this.renderKeybindIfNeeded(text, context) is ScoreText -> this.renderScoreIfNeeded(text, context) is SelectorText -> this.renderSelectorIfNeeded(text, context) is DataText<*, *> -> when (text) { is BlockDataText -> this.renderBlockNbtIfNeeded(text, context) is EntityDataText -> this.renderEntityNbtIfNeeded(text, context) is StorageDataText -> this.renderStorageNbtIfNeeded(text, context) else -> text } else -> text } } /** * Renders the given list of [Text], if it's needed. */ fun renderListIfNeeded(list: List<Text>, context: C): List<Text>? { if (list.isEmpty()) return null var resultList: MutableList<Text>? = null for (index in list.indices) { val text = list[index] val result = this.renderIfNeeded(text, context) if (result != null) { if (resultList == null) { resultList = ArrayList(list.size) resultList.addAll(list.subList(0, index)) } resultList.add(result) } else { resultList?.add(text) } } return resultList } /** * Gets a message format from a key and context. * * @param context a context * @param key a translation key * @return a message format or `null` to skip translation */ protected abstract fun translate(key: String, context: C): MessageFormat? }
mit
andersonlucasg3/SpriteKit-Android
SpriteKitLib/src/main/java/br/com/insanitech/spritekit/actions/SKActionRemoveFromParent.kt
1
399
package br.com.insanitech.spritekit.actions import br.com.insanitech.spritekit.SKNode /** * Created by anderson on 06/01/17. */ internal class SKActionRemoveFromParent : SKAction() { override fun computeStart(node: SKNode) { } override fun computeAction(node: SKNode, elapsed: Long) { node.removeFromParent() } override fun computeFinish(node: SKNode) { } }
bsd-3-clause
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/codec/play/SetExperienceEncoder.kt
1
1000
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.vanilla.packet.codec.play import org.lanternpowered.server.network.buffer.ByteBuffer import org.lanternpowered.server.network.packet.PacketEncoder import org.lanternpowered.server.network.packet.CodecContext import org.lanternpowered.server.network.vanilla.packet.type.play.SetExperiencePacket object SetExperienceEncoder : PacketEncoder<SetExperiencePacket> { override fun encode(ctx: CodecContext, packet: SetExperiencePacket): ByteBuffer { val buf = ctx.byteBufAlloc().buffer() buf.writeFloat(packet.exp) buf.writeVarInt(packet.level) buf.writeVarInt(packet.total) return buf } }
mit
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/data/DataHolderBase.kt
1
4454
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.data import com.google.common.collect.ImmutableSet import org.lanternpowered.api.util.optional.emptyOptional import org.lanternpowered.api.util.uncheckedCast import org.spongepowered.api.data.DataHolder import org.spongepowered.api.data.Key import org.spongepowered.api.data.value.Value import java.util.Optional import kotlin.reflect.KProperty interface DataHolderBase : DataHolder, ValueContainerBase { /** * Gets a element delegate for the given [Key]. */ @JvmDefault operator fun <V : Value<E>, E : Any, H : DataHolder> Key<V>.provideDelegate(thisRef: H, property: KProperty<*>): DataHolderProperty<H, E> = KeyElementProperty(this) /** * Gets a element delegate for the given [Key]. */ @JvmDefault operator fun <V : Value<E>, E : Any, H : DataHolder> Optional<out Key<V>>.provideDelegate(thisRef: H, property: KProperty<*>): DataHolderProperty<H, E> = get().provideDelegate(thisRef, property) /** * Gets a value delegate for the given [Key]. */ @JvmDefault fun <V : Value<E>, E : Any, H : DataHolder> value(key: Key<V>): DataHolderProperty<H, V> = KeyValueProperty(key) /** * Gets a value delegate for the given [Key]. */ @JvmDefault fun <V : Value<E>, E : Any, H : DataHolder> value(key: Optional<out Key<V>>): DataHolderProperty<H, V> = value(key.get()) /** * Gets a optional element delegate for the given [Key]. */ @JvmDefault fun <V : Value<E>, E : Any, H : DataHolder> optional(key: Key<V>): DataHolderProperty<H, E?> = OptionalKeyElementProperty(key) /** * Gets a optional element delegate for the given [Key]. */ @JvmDefault fun <V : Value<E>, E : Any, H : DataHolder> optional(key: Optional<out Key<V>>): DataHolderProperty<H, E?> = optional(key.get()) /** * Gets a optional value delegate for the given [Key]. */ @JvmDefault fun <V : Value<E>, E : Any, H : DataHolder> optionalValue(key: Key<V>): DataHolderProperty<H, V?> = OptionalKeyValueProperty(key) /** * Gets a optional value delegate for the given [Key]. */ @JvmDefault fun <V : Value<E>, E : Any, H : DataHolder> optionalValue(key: Optional<out Key<V>>): DataHolderProperty<H, V?> = optionalValue(key.get()) @JvmDefault override fun supports(key: Key<*>) = supportsKey(key.uncheckedCast<Key<Value<Any>>>()) /** * Gets whether the [Key] is supported by this [LocalDataHolder]. */ @JvmDefault private fun <V : Value<E>, E : Any> supportsKey(key: Key<V>): Boolean { val globalRegistration = GlobalKeyRegistry[key] if (globalRegistration != null) return globalRegistration.anyDataProvider().isSupported(this) return false } @JvmDefault override fun <E : Any, V : Value<E>> getValue(key: Key<V>): Optional<V> { val globalRegistration = GlobalKeyRegistry[key] if (globalRegistration != null) return globalRegistration.dataProvider<V, E>().getValue(this) return emptyOptional() } @JvmDefault override fun <E : Any> get(key: Key<out Value<E>>): Optional<E> { val globalRegistration = GlobalKeyRegistry[key] if (globalRegistration != null) return globalRegistration.dataProvider<Value<E>, E>().get(this) return emptyOptional() } @JvmDefault override fun getKeys(): Set<Key<*>> { val keys = ImmutableSet.builder<Key<*>>() GlobalKeyRegistry.registrations.stream() .filter { registration -> registration.anyDataProvider().isSupported(this) } .forEach { registration -> keys.add(registration.key) } return keys.build() } @JvmDefault override fun getValues(): Set<Value.Immutable<*>> { val values = ImmutableSet.builder<Value.Immutable<*>>() for (registration in GlobalKeyRegistry.registrations) { registration.anyDataProvider().getValue(this).ifPresent { value -> values.add(value.asImmutable()) } } return values.build() } }
mit
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/codec/play/ClientBlockPlacementDecoder.kt
1
1543
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.vanilla.packet.codec.play import org.lanternpowered.server.network.buffer.ByteBuffer import org.lanternpowered.server.network.packet.PacketDecoder import org.lanternpowered.server.network.packet.CodecContext import org.lanternpowered.server.network.vanilla.packet.codec.play.CodecUtils.decodeDirection import org.lanternpowered.server.network.vanilla.packet.type.play.ClientBlockPlacementPacket import org.spongepowered.api.data.type.HandTypes import org.spongepowered.math.vector.Vector3d object ClientBlockPlacementDecoder : PacketDecoder<ClientBlockPlacementPacket> { override fun decode(ctx: CodecContext, buf: ByteBuffer): ClientBlockPlacementPacket { val hand = if (buf.readVarInt() == 0) HandTypes.MAIN_HAND.get() else HandTypes.OFF_HAND.get() val position = buf.readBlockPosition() val face = decodeDirection(buf.readVarInt()) val ox = buf.readFloat().toDouble() val oy = buf.readFloat().toDouble() val oz = buf.readFloat().toDouble() val offset = Vector3d(ox, oy, oz) val insideBlock = buf.readBoolean() return ClientBlockPlacementPacket(position, offset, face, hand, insideBlock) } }
mit
aCoder2013/general
general-gossip/src/test/java/com/song/general/netty/NettyTest.kt
1
182
package com.song.general.netty import org.junit.Test /** * Created by song on 2017/8/19. */ class NettyTest { @Test @Throws(Exception::class) fun test() { } }
apache-2.0
mediathekview/MediathekView
src/main/kotlin/org/jdesktop/swingx/VerticalLayout.kt
1
2441
package org.jdesktop.swingx import java.awt.Component import java.awt.Container import java.awt.Dimension import java.awt.LayoutManager import java.io.Serializable import kotlin.math.max abstract class AbstractLayoutManager : LayoutManager, Serializable { override fun addLayoutComponent(name: String, comp: Component) { //do nothing } override fun removeLayoutComponent(comp: Component) { // do nothing } override fun minimumLayoutSize(parent: Container): Dimension { return preferredLayoutSize(parent) } companion object { private const val serialVersionUID = 1446292747820044161L } } /** * SwingX VerticalLayout implementation recreated in Kotlin. * Unfortunately SwingX is not maintained anymore :( */ class VerticalLayout @JvmOverloads constructor(var gap: Int = 0) : AbstractLayoutManager() { internal class Separator(private var next: Int, private val separator: Int) { fun get(): Int { val result = next next = separator return result } } override fun preferredLayoutSize(parent: Container): Dimension { val pref = Dimension(0, 0) val sep = Separator(0, gap) var i = 0 val c = parent.componentCount while (i < c) { val m = parent.getComponent(i) if (m.isVisible) { val componentPreferredSize = parent.getComponent(i).preferredSize pref.height += componentPreferredSize.height + sep.get() pref.width = max(pref.width, componentPreferredSize.width) } i++ } val insets = parent.insets pref.width += insets.left + insets.right pref.height += insets.top + insets.bottom return pref } override fun layoutContainer(parent: Container) { val insets = parent.insets val size = parent.size val width = size.width - insets.left - insets.right var height = insets.top var i = 0 val c = parent.componentCount while (i < c) { val m = parent.getComponent(i) if (m.isVisible) { m.setBounds(insets.left, height, width, m.preferredSize.height) height += m.size.height + gap } i++ } } companion object { private const val serialVersionUID = 5342270033773736441L } }
gpl-3.0
SixCan/SixDaily
app/src/main/java/ca/six/daily/view/OneAdapter.kt
1
736
package ca.six.daily.view import android.support.v7.widget.RecyclerView import android.view.ViewGroup abstract class OneAdapter<T>(val layoutResId: Int) : RecyclerView.Adapter<RvViewHolder>() { var data: List<T> = ArrayList() override fun getItemCount(): Int { return data.size } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RvViewHolder { val vh = RvViewHolder.createViewHolder(parent, layoutResId) return vh } override fun onBindViewHolder(holder: RvViewHolder, position: Int) { if (data.size > position) { apply(holder, data[position], position) } } protected abstract fun apply(vh: RvViewHolder, t: T, position: Int) }
mpl-2.0
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/util/labels/Labels.kt
1
4228
package nl.hannahsten.texifyidea.util.labels import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import nl.hannahsten.texifyidea.index.LatexParameterLabeledCommandsIndex import nl.hannahsten.texifyidea.index.LatexParameterLabeledEnvironmentsIndex import nl.hannahsten.texifyidea.lang.commands.LatexGenericRegularCommand import nl.hannahsten.texifyidea.psi.LatexCommands import nl.hannahsten.texifyidea.reference.InputFileReference import nl.hannahsten.texifyidea.util.files.commandsInFile import nl.hannahsten.texifyidea.util.files.commandsInFileSet import nl.hannahsten.texifyidea.util.files.psiFile /** * Finds all the defined labels in the fileset of the file. * * @return A set containing all labels that are defined in the fileset of the given file. */ fun PsiFile.findLatexAndBibtexLabelStringsInFileSet(): Set<String> = (findLatexLabelStringsInFileSetAsSequence() + findBibtexLabelsInFileSetAsSequence()).toSet() /** * Finds all the defined latex labels in the fileset of the file. * May contain duplicates. * * @return A set containing all labels that are defined in the fileset of the given file. */ fun PsiFile.findLatexLabelStringsInFileSetAsSequence(): Sequence<String> { val allCommands = this.commandsInFileSet() return findLatexLabelingElementsInFileSet().map { it.extractLabelName(referencingFileSetCommands = allCommands) } } /** * All labels in this file. */ fun PsiFile.findLatexLabelingElementsInFile(): Sequence<PsiElement> = sequenceOf( findLabelingCommandsInFile(), LatexParameterLabeledEnvironmentsIndex.getItems(this).asSequence(), LatexParameterLabeledCommandsIndex.getItems(this).asSequence() ).flatten() /** * All labels in the fileset. * May contain duplicates. */ fun PsiFile.findLatexLabelingElementsInFileSet(): Sequence<PsiElement> = sequenceOf( findLabelingCommandsInFileSet(), LatexParameterLabeledEnvironmentsIndex.getItemsInFileSet(this).asSequence(), LatexParameterLabeledCommandsIndex.getItemsInFileSet(this).asSequence() ).flatten() /** * Make a sequence of all commands in the file set that specify a label. This does not include commands which define a label via an * optional parameter. */ fun PsiFile.findLabelingCommandsInFileSet(): Sequence<LatexCommands> { // If using the xr package to include label definitions in external files, include those external files when searching for labeling commands in the fileset val externalCommands = this.findXrPackageExternalDocuments().flatMap { it.commandsInFileSet() } return (this.commandsInFileSet() + externalCommands).asSequence().findLatexCommandsLabels(this.project) } /** * Find external files which contain label definitions, as used by the xr package, which are called with \externaldocument anywhere in the fileset. */ fun PsiFile.findXrPackageExternalDocuments(): List<PsiFile> { return this.commandsInFileSet() .filter { it.name == LatexGenericRegularCommand.EXTERNALDOCUMENT.commandWithSlash } .flatMap { it.references.filterIsInstance<InputFileReference>() } .mapNotNull { it.findAnywhereInProject(it.key)?.psiFile(project) } } /** * @see [findLabelingCommandsInFileSet] but then only for commands in this file. */ fun PsiFile.findLabelingCommandsInFile(): Sequence<LatexCommands> { return this.commandsInFile().asSequence().findLatexCommandsLabels(this.project) } /* * Filtering sequence or collection */ /** * Finds all the labeling commands within the collection of PsiElements. * * @return A collection of all label commands. */ fun Collection<PsiElement>.findLatexCommandsLabels(project: Project): Collection<LatexCommands> { val commandNames = project.getLabelDefinitionCommands() return filterIsInstance<LatexCommands>().filter { commandNames.contains(it.name) } } /** * Finds all the labeling commands within the sequence of PsiElements. * * @return A sequence of all label commands. */ fun Sequence<PsiElement>.findLatexCommandsLabels(project: Project): Sequence<LatexCommands> { val commandNames = project.getLabelDefinitionCommands() return filterIsInstance<LatexCommands>().filter { commandNames.contains(it.name) } }
mit
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/run/bibtex/logtab/BibtexMessageHandler.kt
1
340
package nl.hannahsten.texifyidea.run.bibtex.logtab abstract class BibtexMessageHandler { /** * Find a message from the given window, last added line is last in the list. * * @param currentFile: Currently open bib file. */ abstract fun findMessage(window: List<String>, currentFile: String): BibtexLogMessage? }
mit
Ruben-Sten/TeXiFy-IDEA
src/nl/hannahsten/texifyidea/util/Collections.kt
1
4675
package nl.hannahsten.texifyidea.util import java.util.* import java.util.stream.Collectors import java.util.stream.Stream /** * Puts all the elements of an array into a mutable map. * * The format is `key0, value0, key1, value1, ...`. This means that there must always be an even amount of elements. * * @return A map mapping `keyN` to `valueN` (see description above). When there are no elements, an empty map will be * returned * @throws IllegalArgumentException When there is an odd amount of elements in the array. */ @Throws(IllegalArgumentException::class) fun <T> mutableMapOfArray(args: Array<out T>): MutableMap<T, T> { if (args.isEmpty()) { return HashMap() } if (args.size % 2 != 0) { throw IllegalArgumentException("Must have an even number of elements, got ${args.size} instead.") } val map: MutableMap<T, T> = HashMap() for (i in 0 until args.size - 1 step 2) { map[args[i]] = args[i + 1] } return map } /** * Puts some elements into a mutable map. * * The format is `key0, value0, key1, value1, ...`. This means that there must always be an even amount of elements. * * @return A map mapping `keyN` to `valueN` (see description above). When there are no elements, an empty map will be * returned * @throws IllegalArgumentException When there is an odd amount of elements in the array. */ fun <T> mutableMapOfVarargs(vararg args: T): MutableMap<T, T> = mutableMapOfArray(args) /** * Puts some into a mutable map. * * The format is `key0, value0, key1, value1, ...`. This means that there must always be an even amount of elements. * * @return A map mapping `keyN` to `valueN` (see description above). When there are no elements, an empty map will be * returned * @throws IllegalArgumentException When there is an odd amount of elements in the array. */ fun <T> mapOfVarargs(vararg args: T): Map<T, T> = mutableMapOfArray(args) /** * Gets a random element from the list using the given random object. */ fun <T> List<T>.randomElement(random: Random): T = this[random.nextInt(this.size)] /** * Looks up keys in the map that has the given `value`. * * @return All keys with the given value. */ fun <K, V> Map<K, V>.findKeys(value: V): Set<K> { return entries.asSequence() .filter { (_, v) -> v == value } .map { it.key } .toSet() } /** * Finds at least `amount` elements matching the given predicate. * * @param amount * How many items the collection must contain at least in order to return true. Must be nonnegative. * @return `true` when `amount` or more elements in the collection match the given predicate. */ inline fun <T> Collection<T>.findAtLeast(amount: Int, predicate: (T) -> Boolean): Boolean { require(amount >= 0) { "Amount must be positive." } // Edge cases. when (amount) { 0 -> none(predicate) 1 -> any(predicate) } // More than 1 item, iterate. var matches = 0 for (element in this) { if (predicate(element)) { matches += 1 if (matches >= amount) { return true } } } return false } /** * Checks if all given predicates can be matched at least once. * * @return `true` if all predicates match for at least 1 element in the collection, `false` otherwise. */ inline fun <T> Collection<T>.anyMatchAll(predicate: (T) -> Boolean, vararg predicates: (T) -> Boolean): Boolean { val matches = BooleanArray(predicates.size + 1) var matchCount = 0 for (element in this) { for (i in predicates.indices) { if (!matches[i] && predicates[i](element)) { matches[i] = true matchCount += 1 } } if (!matches.last() && predicate(element)) { matches[matches.size - 1] = true matchCount += 1 } } return matchCount == matches.size } /** * Checks if the map contains the given value as either a key or value. */ fun <T> Map<T, T>.containsKeyOrValue(value: T) = containsKey(value) || containsValue(value) /** * Collects stream to [List]. */ fun <T> Stream<T>.list(): List<T> = this.mutableList() /** * Collects stream to [MutableList]. */ fun <T> Stream<T>.mutableList(): MutableList<T> = this.collect(Collectors.toList()) /** * Collects stream to [Set]. */ fun <T> Stream<T>.set(): Set<T> = this.mutableSet() /** * Collects stream to [MutableSet] */ fun <T> Stream<T>.mutableSet(): MutableSet<T> = this.collect(Collectors.toSet()) /** * Converts the collection to a vector. */ fun <T> Collection<T>.toVector() = Vector(this)
mit
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/config.kt
1
81
package com.pr0gramm.app const val ServiceBaseURL = "https://app.pr0gramm.com"
mit
B515/Schedule
app/src/main/kotlin/xyz/b515/schedule/ui/view/TodayCoursesFragment.kt
1
1742
package xyz.b515.schedule.ui.view import android.app.Fragment import android.content.SharedPreferences import android.os.Bundle import android.preference.PreferenceManager import android.support.v7.widget.DefaultItemAnimator import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.fragment_today.view.* import xyz.b515.schedule.Constant import xyz.b515.schedule.R import xyz.b515.schedule.db.CourseManager import xyz.b515.schedule.ui.adapter.CourseAdapter import java.util.* /** * Created by Yun on 2017.4.24. */ class TodayCoursesFragment : Fragment() { lateinit var adapter: CourseAdapter private val manager: CourseManager by lazy { CourseManager(context) } private val preferences: SharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(context) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_today, container, false) adapter = CourseAdapter(arrayListOf()) view.recycler.adapter = adapter view.recycler.itemAnimator = DefaultItemAnimator() val today = Calendar.getInstance().get(Calendar.DAY_OF_WEEK) val currentWeek = preferences.getInt(Constant.CURRENT_WEEK, -1) + 1 adapter.items.clear() manager.getAllCourse() .flatMap { it.spacetimes!! } .filter { it.weekday == today } .filter { currentWeek in it.startWeek..it.endWeek } .sortedBy { it.startTime } .forEach { adapter.items.add(it.course) } adapter.notifyDataSetChanged() return view } }
apache-2.0
FHannes/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/WebServerPathToFileManager.kt
11
7261
package org.jetbrains.builtInWebServer import com.google.common.base.Function import com.google.common.cache.CacheBuilder import com.google.common.cache.CacheLoader import com.intellij.ProjectTopics import com.intellij.openapi.application.Application import com.intellij.openapi.application.runReadAction import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.rootManager import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.openapi.vfs.newvfs.BulkFileListener import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.util.SmartList import com.intellij.util.containers.computeIfAny import com.intellij.util.io.exists import java.nio.file.Paths import java.util.concurrent.TimeUnit private val cacheSize: Long = 4096 * 4 /** * Implement [WebServerRootsProvider] to add your provider */ class WebServerPathToFileManager(application: Application, private val project: Project) { val pathToInfoCache = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(10, TimeUnit.MINUTES).build<String, PathInfo>()!! // time to expire should be greater than pathToFileCache private val virtualFileToPathInfo = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(11, TimeUnit.MINUTES).build<VirtualFile, PathInfo>() internal val pathToExistShortTermCache = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(5, TimeUnit.SECONDS).build<String, Boolean>()!! /** * https://youtrack.jetbrains.com/issue/WEB-25900 * * Compute suitable roots for oldest parent (web/foo/my/file.dart -> oldest is web and we compute all suitable roots for it in advance) to avoid linear search * (i.e. to avoid two queries for root if files web/foo and web/bar requested if root doesn't have web dir) */ internal val parentToSuitableRoot = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(10, TimeUnit.MINUTES).build<String, List<SuitableRoot>>( CacheLoader.from(Function { path -> val suitableRoots = SmartList<SuitableRoot>() var moduleQualifier: String? = null val modules = runReadAction { ModuleManager.getInstance(project).modules } for (rootProvider in RootProvider.values()) { for (module in modules) { if (module.isDisposed) { continue } for (root in rootProvider.getRoots(module.rootManager)) { if (root.findChild(path!!) != null) { if (moduleQualifier == null) { moduleQualifier = getModuleNameQualifier(project, module) } suitableRoots.add(SuitableRoot(root, moduleQualifier)) } } } } suitableRoots }))!! init { application.messageBus.connect(project).subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener { override fun after(events: List<VFileEvent>) { for (event in events) { if (event is VFileContentChangeEvent) { val file = event.file for (rootsProvider in WebServerRootsProvider.EP_NAME.extensions) { if (rootsProvider.isClearCacheOnFileContentChanged(file)) { clearCache() break } } } else { clearCache() break } } } }) project.messageBus.connect().subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent) { clearCache() } }) } companion object { @JvmStatic fun getInstance(project: Project) = ServiceManager.getService(project, WebServerPathToFileManager::class.java)!! } private fun clearCache() { pathToInfoCache.invalidateAll() virtualFileToPathInfo.invalidateAll() pathToExistShortTermCache.invalidateAll() parentToSuitableRoot.invalidateAll() } @JvmOverloads fun findVirtualFile(path: String, cacheResult: Boolean = true, pathQuery: PathQuery = defaultPathQuery): VirtualFile? { return getPathInfo(path, cacheResult, pathQuery)?.getOrResolveVirtualFile() } @JvmOverloads fun getPathInfo(path: String, cacheResult: Boolean = true, pathQuery: PathQuery = defaultPathQuery): PathInfo? { var pathInfo = pathToInfoCache.getIfPresent(path) if (pathInfo == null || !pathInfo.isValid) { if (pathToExistShortTermCache.getIfPresent(path) == false) { return null } pathInfo = doFindByRelativePath(path, pathQuery) if (cacheResult) { if (pathInfo != null && pathInfo.isValid) { pathToInfoCache.put(path, pathInfo) } else { pathToExistShortTermCache.put(path, false) } } } return pathInfo } fun getPath(file: VirtualFile) = getPathInfo(file)?.path fun getPathInfo(child: VirtualFile): PathInfo? { var result = virtualFileToPathInfo.getIfPresent(child) if (result == null) { result = WebServerRootsProvider.EP_NAME.extensions.computeIfAny { it.getPathInfo(child, project) } if (result != null) { virtualFileToPathInfo.put(child, result) } } return result } internal fun doFindByRelativePath(path: String, pathQuery: PathQuery): PathInfo? { val result = WebServerRootsProvider.EP_NAME.extensions.computeIfAny { it.resolve(path, project, pathQuery) } ?: return null result.file?.let { virtualFileToPathInfo.put(it, result) } return result } fun getResolver(path: String) = if (path.isEmpty()) EMPTY_PATH_RESOLVER else RELATIVE_PATH_RESOLVER } interface FileResolver { fun resolve(path: String, root: VirtualFile, moduleName: String? = null, isLibrary: Boolean = false, pathQuery: PathQuery): PathInfo? } private val RELATIVE_PATH_RESOLVER = object : FileResolver { override fun resolve(path: String, root: VirtualFile, moduleName: String?, isLibrary: Boolean, pathQuery: PathQuery): PathInfo? { // WEB-17691 built-in server doesn't serve files it doesn't have in the project tree // temp:// reports isInLocalFileSystem == true, but it is not true if (pathQuery.useVfs || root.fileSystem != LocalFileSystem.getInstance() || path == ".htaccess" || path == "config.json") { return root.findFileByRelativePath(path)?.let { PathInfo(null, it, root, moduleName, isLibrary) } } val file = Paths.get(root.path, path) return if (file.exists()) { PathInfo(file, null, root, moduleName, isLibrary) } else { null } } } private val EMPTY_PATH_RESOLVER = object : FileResolver { override fun resolve(path: String, root: VirtualFile, moduleName: String?, isLibrary: Boolean, pathQuery: PathQuery): PathInfo? { val file = findIndexFile(root) ?: return null return PathInfo(null, file, root, moduleName, isLibrary) } } internal val defaultPathQuery = PathQuery()
apache-2.0
NextFaze/dev-fun
dokka/src/main/java/wiki/Components.kt
1
17838
package wiki import com.nextfaze.devfun.DeveloperAnnotation import com.nextfaze.devfun.category.DeveloperCategory import com.nextfaze.devfun.compiler.DevFunProcessor import com.nextfaze.devfun.core.DevFun import com.nextfaze.devfun.core.call import com.nextfaze.devfun.core.devFun import com.nextfaze.devfun.function.DeveloperFunction import com.nextfaze.devfun.function.DeveloperProperty import com.nextfaze.devfun.function.FunctionItem import com.nextfaze.devfun.httpd.DevHttpD import com.nextfaze.devfun.httpd.devDefaultPort import com.nextfaze.devfun.httpd.frontend.HttpFrontEnd import com.nextfaze.devfun.inject.CompositeInstanceProvider import com.nextfaze.devfun.inject.InstanceProvider import com.nextfaze.devfun.inject.dagger2.InjectFromDagger2 import com.nextfaze.devfun.inject.dagger2.tryGetInstanceFromComponent import com.nextfaze.devfun.inject.dagger2.useAutomaticDagger2Injector import com.nextfaze.devfun.invoke.view.ColorPicker import com.nextfaze.devfun.menu.DevMenu import com.nextfaze.devfun.menu.MenuController import com.nextfaze.devfun.menu.controllers.CogOverlay import com.nextfaze.devfun.menu.controllers.KeySequence import com.nextfaze.devfun.reference.Dagger2Component import com.nextfaze.devfun.reference.Dagger2Scope import com.nextfaze.devfun.reference.DeveloperLogger import com.nextfaze.devfun.reference.DeveloperReference import com.nextfaze.devfun.stetho.DevStetho import com.nextfaze.devfun.utils.glide.GlideUtils import com.nextfaze.devfun.utils.leakcanary.LeakCanaryUtils import java.util.ServiceLoader /** DevFun is designed to be modular, in terms of both its dependencies (limiting impact to main source tree) and its plugin-like architecture. ![Component Dependencies](https://github.com/NextFaze/dev-fun/raw/gh-pages/assets/uml/components.png) * <!-- START doctoc generated TOC please keep comment here to allow auto update --> * <!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE --> * * * - [Main Modules](#main-modules) * - [Annotations](#annotations) * - [Compiler](#compiler) * - [Gradle Plugin](#gradle-plugin) * - [Core Modules](#core-modules) * - [DevFun](#devfun) * - [Menu](#menu) * - [Inject Modules](#inject-modules) * - [Dagger 2](#dagger-2) * - [Supported Versions](#supported-versions) * - [Limitations](#limitations) * - [Instance and Component Resolution](#instance-and-component-resolution) * - [Reflection Based](#reflection-based) * - [Annotation Based](#annotation-based) * - [Custom Instance Provider](#custom-instance-provider) * - [Util Modules](#util-modules) * - [Glide](#glide) * - [Leak Canary](#leak-canary) * - [Invoke Modules](#invoke-modules) * - [Color Picker View](#color-picker-view) * - [Experimental Modules](#experimental-modules) * - [HttpD](#httpd) * - [Custom Port](#custom-port) * - [Http Front-end](#http-front-end) * - [Stetho](#stetho) * * <!-- END doctoc generated TOC please keep comment here to allow auto update --> ## Main Modules Minimum required libraries - annotations and annotation processor. `IMG_START<img src="https://github.com/NextFaze/dev-fun/raw/gh-pages/assets/gif/enable-sign-in.gif" alt="DevFun demonstration" width="35%" align="right"/>IMG_END` ### Annotations Provides DevFun annotations and various interface definitions: - [DeveloperFunction] - [DeveloperCategory] - [DeveloperReference] - [DeveloperAnnotation] - [DeveloperLogger] - [DeveloperProperty] - [Dagger2Component] This library contains primarily interface definitions and inline functions, and will have a negligible impact on your method count and dex sizes. Apply to your main `compile` configuration: * ```kotlin * implementation("com.nextfaze.devfun:devfun-annotations:2.1.0") * ``` ### Compiler Annotation processor [DevFunProcessor] that handles [DeveloperFunction], [DeveloperCategory], [DeveloperReference], and [DeveloperAnnotation] annotations. This should be applied to your non-main kapt configuration 'kaptDebug' to avoid running/using it on release builds. * ```kotlin * kaptDebug("com.nextfaze.devfun:devfun-compiler:2.1.0") * ``` Configuration options can be applied using Android DSL: * ```kotlin * android { * defaultConfig { * javaCompileOptions { * annotationProcessorOptions { * argument("devfun.argument", "value") * } * } * } * } * ``` Full list available at [com.nextfaze.devfun.compiler]. ### Gradle Plugin Used to configure/provide the compiler with the project/build configurations. In your `build.gradle` add the DevFun Gradle plugin to your build script. If you can use the Gradle `plugins` block (which you should be able to do - this locates and downloads it for you): * ```kotlin * plugins { * id("com.nextfaze.devfun") version "2.1.0" * } * ``` __Or__ the legacy method using `apply`; Add the plugin to your classpath (found in the `jcenter()` repository): * ```kotlin * buildscript { * dependencies { * classpath("com.nextfaze.devfun:devfun-gradle-plugin:2.1.0") * } * } * ``` And in your `build.gradle`: * ```kotlin * apply { * plugin("com.nextfaze.devfun") * } * ``` ## Core Modules Modules that extend the accessibility of DevFun (e.g. add menu/http server). _Also see [Experimental Modules](#experimental-modules) below._ ### DevFun Core of [DevFun]. Loads modules and definitions. Apply to your non-main configuration: * ```kotlin * debugImplementation("com.nextfaze.devfun:devfun:2.1.0") * ``` Modules are loaded by [DevFun] using Java's [ServiceLoader]. [DevFun] loads, transforms, and sorts the generated function definitions, again via the [ServiceLoader] mechanism. To inject function invocations, [InstanceProvider]s are used, which will attempt to locate (or create) object instances. A composite instance provider [CompositeInstanceProvider] at [DevFun.instanceProviders] is used via convenience function (extension) [FunctionItem.call] that uses the currently loaded [devFun] instance. If using Dagger 2.x, you can use the `devfun-inject-dagger2` module for a simple reflection based provider or related helper functions. A heavily reflective version will be used automatically, but if it fails (e.g. it expects a `Component` in your application class), a manual implementation can be provided. See the demo app [DemoInstanceProvider](https://github.com/NextFaze/dev-fun/tree/master/demo/src/debug/java/com/nextfaze/devfun/demo/devfun/DevFun.kt#L52) for a sample implementation. `IMG_START<img src="https://github.com/NextFaze/dev-fun/raw/gh-pages/assets/gif/registration-flow.gif" alt="Menu demonstration" width="35%" align="right"/>IMG_END` ### Menu Adds a developer menu [DevMenu], accessible by a floating cog [CogOverlay] (long-press to drag) or device button sequence [KeySequence]. * ```kotlin * debugImplementation("com.nextfaze.devfun:menu:2.1.0") * ``` Button sequences: *(this are not configurable at the moment but are intended to be eventually)* * ```kotlin * internal val GRAVE_KEY_SEQUENCE = KeySequence.Definition( * keyCodes = intArrayOf(KeyEvent.KEYCODE_GRAVE), * description = R.string.df_menu_grave_sequence, * consumeEvent = true * ) * internal val VOLUME_KEY_SEQUENCE = KeySequence.Definition( * keyCodes = intArrayOf( * KeyEvent.KEYCODE_VOLUME_DOWN, * KeyEvent.KEYCODE_VOLUME_DOWN, * KeyEvent.KEYCODE_VOLUME_UP, * KeyEvent.KEYCODE_VOLUME_DOWN * ), * description = R.string.df_menu_volume_sequence, * consumeEvent = false * ) * ``` Menu controllers implement [MenuController] and can be added via `devFun.module<DevMenu>() += MyMenuController()`. ## Inject Modules Modules to facilitate dependency injection for function invocation. ### Dagger 2 Adds module [InjectFromDagger2] which adds an [InstanceProvider] that can reflectively locate components or (if used) resolve [Dagger2Component] uses. Tested from Dagger 2.4 to 2.17. * ```kotlin * debugImplementation("com.nextfaze.devfun:devfun-inject-dagger2:2.1.0") * ``` Simply graphs should be well supported. More complex graphs _should_ work (it has been working well in-house). Please report any issues you encounter. The module also provides a variety of utility functions for manually providing your own instance provider using your components. See below for more details. _I'm always looking into better ways to support this, comments/suggestions are welcome._ - Currently kapt doesn't support multi-staged processing of generated Kotlin code. - Possibly consider generating Java `Component` interfaces for some types? - Likely will investigate the new SPI functionality in Dagger 2.17+ once it becomes more stable. #### Supported Versions Dagger has been tested on the demo app from versions 2.4 to 2.17, and various in-house apps on more recent versions, and should function correctly for most simple scopes/graphs. For reference the demo app uses three scopes; Singleton, Retained (fragments), and an Activity scope. It uses both type-annotated scoping and provides scoping. It keeps component instances in the activity and obtains the singleton scope via an extension function. In general this should cover most use cases - if you encounter any problems please create an issue. #### Limitations DevFun uses a number of methods iteratively to introspect the generated components/modules, however depending on scoping, visibility, and instantiation of a type it can be difficult to determine the source/scope in initial (but faster) introspection methods. When all else fails DevFun will use a form of heavy reflection to introspect the generated code - types with a custom scope and no constructor arguments are not necessarily obtainable from Dagger (depends on the version) by any other means. To help with this ensure your scope is `@Retention(RUNTIME)` so that DevFun wont unintentionally create a new instance when it can't find it right away. Due to the way Dagger generates/injects it is not possible to obtain the instance of non-scoped types from the generated component/module as its instance is created/injected once (effectively inlined) at the inject site. It is intended to allow finding instances based on the context of the dev. function in the future (i.e. if the dev. function is in a fragment then check for the injected instance in the fragment etc.) - if this is desirable sooner make a comment in the issue [#26](https://github.com/NextFaze/dev-fun/issues/26). #### Instance and Component Resolution Unless you specify [Dagger2Component] annotations, DevFun will use a heavy-reflection based provider. Where possible DevFun will cache the locations of where it found various types - this is somewhat loose in that the provider cache still attempts to be aware of scoping. ##### Reflection Based By default simply including the module will use the reflection-based component locator. It will attempt to locate your component objects in your application class and/or your activity classes and use aforementioned utility functions. If you place one or more [Dagger2Component] annotations (see below), then the reflective locator wont be used. ##### Annotation Based For more control, or if the above method doesn't (such as if you use top-level extension functions to retrieve your components, or you put them in weird places, or for whatever reason), then you can annotate the functions/getters with [Dagger2Component]. The scope/broadness/priority can be set on the annotation either via [Dagger2Component.scope] or [Dagger2Component.priority]. If unset then the scope will be assumed based on the context of its location (i.e. in Application class > probably the top level component, if static then first argument assumed to be the receiver, etc). Note: For properties you can annotated to property itself (`@Dagger2Component`) or the getter explicitly (`@get:Dagger2Component`) if for some reason on the property doesn't work (which could happen if it can't find your getter - which is done via method name string manipulation due to KAPT limitations. Example usage: - Where a top-level/singleton/application component is retrieved via an extension function _(from the demo)_: * ```kotlin * @Dagger2Component * val Context.applicationComponent: ApplicationComponent? * get() = (applicationContext as DaggerApplication).applicationComponent *``` - Where a component is kept in the activity _(from the demo)_: * ```kotlin * @get:Dagger2Component // if we want to specify getter explicitly * lateinit var activityComponent: ActivityComponent * private set * ``` - Where a differently scoped component is also kept in the activity, we can set the scope manually ([Dagger2Scope]) _(from the demo)_: * ```kotlin * @get:Dagger2Component(Dagger2Scope.RETAINED_FRAGMENT) * lateinit var retainedComponent: RetainedComponent * private set * ``` ##### Custom Instance Provider Since the reflection locator and annotation based still make assumptions and are bit inefficient because of it, sometimes you may need to implement your own instance provider. - Disable the automatic locator: set [useAutomaticDagger2Injector] to `false` (can be done at any time). - Add your own provider using `devFun += MyProvider` (see [InstanceProvider] for more details). - Utility function [tryGetInstanceFromComponent] to help (though again it relies heavily on reflection and don't consider scoping very well). See demo for example implementation: [DemoInstanceProvider](https://github.com/NextFaze/dev-fun/tree/master/demo/src/debug/java/com/nextfaze/devfun/demo/devfun/DevFun.kt#L52) ## Util Modules Modules with frequently used or just handy functions (e.g. show Glide memory use). Developers love reusable utility functions, we all have them, and we usually copy-paste them into new projects. Adding them to modules and leveraging dependency injection allows for non-static, easily invokable code reuse. _Still playing with this concept and naming conventions etc._ ### Glide Module [GlideUtils] provides some utility functions when using Glide. * ```kotlin * debugImplementation("com.nextfaze.devfun:devfun-util-glide:2.1.0") * ``` Features: - Clear memory cache - Clear disk cache - Log current memory/disk cache usage ### Leak Canary Module [LeakCanaryUtils] provides some utility functions when using Leak Canary. * ```kotlin * debugImplementation("com.nextfaze.devfun:devfun-util-leakcanary:2.1.0") * ``` Features: - Launch `DisplayLeakActivity` `IMG_START<img src="https://github.com/NextFaze/dev-fun/raw/gh-pages/assets/images/color-picker.png" alt="Invocation UI with custom color picker view" width="35%" align="right"/>IMG_END` ## Invoke Modules Modules to facilitate function invocation. ### Color Picker View Adds a parameter annotation [ColorPicker] that lets the invocation UI render a color picker view for the associated argument. _Note: Only needed if you don't include `devfun-menu` (as it uses/includes the color picker transitively)._ * ```kotlin * debugImplementation("com.nextfaze.devfun-invoke-view-colorpicker:2.1.0") * ``` ## Experimental Modules These modules are mostly for use experimenting with various use-cases. They generally work, but are likely to be buggy and have various limitations and nuances. Having said that, it would be nice to expand upon them and make them nicer/more feature reach in the future. Some future possibilities: - HttpD: Use ktor instead of Nano - HttpD Simple Index: Provide a themed react page or something pretty/nice - Add a Kotlin REPL module ### HttpD Module [DevHttpD] adds a local HTTP server (uses [NanoHttpD](https://github.com/NanoHttpd/nanohttpd)). Provides a single `POST` method `invoke` with one parameter `hashCode` (expecting [FunctionItem.hashCode]) * ```kotlin * debugImplementation("com.nextfaze.devfun:httpd:2.1.0") * ``` Use with HttpD Front-end. _Current port and access instructions are logged on start._ Default port is `23075`. If this is in use another is deterministically generated from your package (this might become the default). If using AVD, forward port: ```bash adb forward tcp:23075 tcp:23075 ``` Then access via IP: [http://127.0.0.1:23075/](http://127.0.0.1:23075/) #### Custom Port Can be set via resources: ```xml <integer name="df_httpd_default_port">12345</integer> ``` Or before initialization [devDefaultPort] (i.e. if not using auto-init content provider): ```kotlin devDefaultPort = 12345 // top level value located in com.nextfaze.devfun.httpd ``` ### Http Front-end Module [HttpFrontEnd] generates an admin interface using SB Admin 2 (similar to [DevMenu]), allowing function invocation from a browser. __Depends on [DevHttpD].__ * ```kotlin * debugImplementation("com.nextfaze.devfun:httpd-frontend:2.1.0") * ``` Page is rather simple at the moment, but in the future it's somewhat intended (as a learning exercise) to create a React front end using Kotlin or something. ![HTTP Server](https://github.com/NextFaze/dev-fun/raw/gh-pages/assets/images/httpd-auth-context.png) ### Stetho Module [DevStetho] allows generated methods to be invoked from Chrome's Dev Tools JavaScript console. * ```kotlin * debugImplementation("com.nextfaze.devfun:devfun-stetho:2.1.0") * ``` Opening console will show available functions. e.g. `Context_Enable_Account_Creation()` _Extremely experimental and limited functionality._ ![Stetho Integration](https://github.com/NextFaze/dev-fun/raw/gh-pages/assets/images/stetho-auth.png) */ object Components /** Here to ensure the `.call` extension function stays in the import list (Kotlin IDE bug). */ @Suppress("unused") private val dummy = (Any() as FunctionItem).call()
apache-2.0
ken-kentan/student-portal-plus
app/src/main/java/jp/kentan/studentportalplus/ui/main/FragmentType.kt
1
707
package jp.kentan.studentportalplus.ui.main import androidx.annotation.StringRes import jp.kentan.studentportalplus.R enum class FragmentType( @StringRes val titleResId: Int, val menuItemId: Int ) { DASHBOARD( R.string.title_fragment_dashboard, R.id.nav_dashboard), TIMETABLE( R.string.title_fragment_timetable, R.id.nav_timetable), LECTURE_INFO( R.string.title_fragment_lecture_info, R.id.nav_lecture_info), LECTURE_CANCEL( R.string.title_fragment_lecture_cancel, R.id.nav_lecture_cancel), NOTICE( R.string.title_fragment_notice, R.id.nav_notice) }
gpl-3.0
ken-kentan/student-portal-plus
app/src/main/java/jp/kentan/studentportalplus/data/dao/LectureInformationDao.kt
1
3720
package jp.kentan.studentportalplus.data.dao import jp.kentan.studentportalplus.data.component.LectureAttend import jp.kentan.studentportalplus.data.component.PortalContent import jp.kentan.studentportalplus.data.model.LectureInformation import jp.kentan.studentportalplus.data.parser.LectureAttendParser import jp.kentan.studentportalplus.data.parser.LectureInformationParser import jp.kentan.studentportalplus.util.JaroWinklerDistance import org.jetbrains.anko.db.SqlOrderDirection import org.jetbrains.anko.db.delete import org.jetbrains.anko.db.select import org.jetbrains.anko.db.update class LectureInformationDao( private val database: DatabaseOpenHelper, var similarThreshold: Float ) : BaseDao() { companion object { const val TABLE_NAME = "lecture_info" private val PARSER = LectureInformationParser() private val LECTURE_ATTEND_PARSER = LectureAttendParser() private val STRING_DISTANCE = JaroWinklerDistance() } fun getAll(): List<LectureInformation> = database.use { val myClassList = select(MyClassDao.TABLE_NAME, "subject, user").parseList(LECTURE_ATTEND_PARSER) select(TABLE_NAME) .orderBy("updated_date", SqlOrderDirection.DESC) .orderBy("subject") .parseList(PARSER) .map { it.copy(attend = myClassList.calcLectureAttend(it.subject)) } } fun update(data: LectureInformation): Int = database.use { update(TABLE_NAME, "read" to data.isRead.toLong()) .whereArgs("_id = ${data.id}") .exec() } fun updateAll(list: List<LectureInformation>) = database.use { beginTransaction() val updatedContentList = mutableListOf<PortalContent>() var st = compileStatement("INSERT OR IGNORE INTO $TABLE_NAME VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?);") // Insert new data list.forEach { st.bindNull(1) st.bindLong(2, it.hash) st.bindString(3, it.grade) st.bindString(4, it.semester) st.bindString(5, it.subject) st.bindString(6, it.instructor) st.bindString(7, it.week) st.bindString(8, it.period) st.bindString(9, it.category) st.bindString(10, it.detailText) st.bindString(11, it.detailHtml) st.bindLong(12, it.createdDate.time) st.bindLong(13, it.updatedDate.time) st.bindLong(14, it.isRead.toLong()) val id = st.executeInsert() if (id > 0) { updatedContentList.add(PortalContent(id, it.subject, it.detailText)) } st.clearBindings() } // Delete old data if (list.isNotEmpty()) { val args = StringBuilder("?") for (i in 2..list.size) { args.append(",?") } st = compileStatement("DELETE FROM $TABLE_NAME WHERE hash NOT IN ($args)") list.forEachIndexed { i, d -> st.bindLong(i + 1, d.hash) } st.executeUpdateDelete() } else { delete(TABLE_NAME) } setTransactionSuccessful() endTransaction() return@use updatedContentList } private fun List<Pair<String, LectureAttend>>.calcLectureAttend(subject: String): LectureAttend { // If match subject firstOrNull { it.first == subject }?.run { return second } // If similar if (any { STRING_DISTANCE.getDistance(it.first, subject) >= similarThreshold }) { return LectureAttend.SIMILAR } return LectureAttend.NOT } }
gpl-3.0
tasks/tasks
app/src/main/java/com/todoroo/astrid/ui/StartDateViewModel.kt
1
3333
package com.todoroo.astrid.ui import androidx.lifecycle.ViewModel import com.todoroo.astrid.data.Task import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import org.tasks.R import org.tasks.date.DateTimeUtils.toDateTime import org.tasks.dialogs.StartDatePicker import org.tasks.dialogs.StartDatePicker.Companion.DAY_BEFORE_DUE import org.tasks.dialogs.StartDatePicker.Companion.DUE_DATE import org.tasks.dialogs.StartDatePicker.Companion.DUE_TIME import org.tasks.dialogs.StartDatePicker.Companion.WEEK_BEFORE_DUE import org.tasks.preferences.Preferences import org.tasks.time.DateTimeUtils.millisOfDay import org.tasks.time.DateTimeUtils.startOfDay import javax.inject.Inject @HiltViewModel class StartDateViewModel @Inject constructor( private val preferences: Preferences ) : ViewModel() { private val _selectedDay = MutableStateFlow(StartDatePicker.NO_DAY) val selectedDay: StateFlow<Long> get() = _selectedDay.asStateFlow() private val _selectedTime = MutableStateFlow(StartDatePicker.NO_TIME) val selectedTime: StateFlow<Int> get() = _selectedTime.asStateFlow() fun init(dueDate: Long, startDate: Long, isNew: Boolean) { val dueDay = dueDate.startOfDay() val dueTime = dueDate.millisOfDay() val hideUntil = startDate.takeIf { it > 0 }?.toDateTime() if (hideUntil == null) { if (isNew) { _selectedDay.value = when (preferences.getIntegerFromString(R.string.p_default_hideUntil_key, Task.HIDE_UNTIL_NONE)) { Task.HIDE_UNTIL_DUE -> DUE_DATE Task.HIDE_UNTIL_DUE_TIME -> DUE_TIME Task.HIDE_UNTIL_DAY_BEFORE -> DAY_BEFORE_DUE Task.HIDE_UNTIL_WEEK_BEFORE -> WEEK_BEFORE_DUE else -> 0L } } } else { _selectedDay.value = hideUntil.startOfDay().millis _selectedTime.value = hideUntil.millisOfDay _selectedDay.value = when (_selectedDay.value) { dueDay -> if (_selectedTime.value == dueTime) { _selectedTime.value = StartDatePicker.NO_TIME DUE_TIME } else { DUE_DATE } dueDay.toDateTime().minusDays(1).millis -> DAY_BEFORE_DUE dueDay.toDateTime().minusDays(7).millis -> WEEK_BEFORE_DUE else -> _selectedDay.value } } } fun setSelected(selectedDay: Long, selectedTime: Int) { _selectedDay.value = selectedDay _selectedTime.value = selectedTime } fun getSelectedValue(dueDate: Long): Long { val due = dueDate.takeIf { it > 0 }?.toDateTime() return when (selectedDay.value) { DUE_DATE -> due?.withMillisOfDay(selectedTime.value)?.millis ?: 0 DUE_TIME -> due?.millis ?: 0 DAY_BEFORE_DUE -> due?.minusDays(1)?.withMillisOfDay(selectedTime.value)?.millis ?: 0 WEEK_BEFORE_DUE -> due?.minusDays(7)?.withMillisOfDay(selectedTime.value)?.millis ?: 0 else -> selectedDay.value + selectedTime.value } } }
gpl-3.0
AoEiuV020/PaNovel
app/src/main/java/cc/aoeiuv020/panovel/server/ServerManager.kt
1
5876
package cc.aoeiuv020.panovel.server import android.content.Context import androidx.annotation.WorkerThread import cc.aoeiuv020.base.jar.notZero import cc.aoeiuv020.gson.toBean import cc.aoeiuv020.jsonpath.get import cc.aoeiuv020.jsonpath.jsonPath import cc.aoeiuv020.panovel.App import cc.aoeiuv020.panovel.R import cc.aoeiuv020.panovel.data.DataManager import cc.aoeiuv020.panovel.report.Reporter import cc.aoeiuv020.panovel.server.common.bookId import cc.aoeiuv020.panovel.server.dal.model.Config import cc.aoeiuv020.panovel.server.dal.model.Message import cc.aoeiuv020.panovel.server.dal.model.QueryResponse import cc.aoeiuv020.panovel.server.dal.model.autogen.Novel import cc.aoeiuv020.panovel.server.service.NovelService import cc.aoeiuv020.panovel.server.service.impl.NovelServiceImpl import cc.aoeiuv020.panovel.settings.ServerSettings import cc.aoeiuv020.panovel.util.* import org.jetbrains.anko.* /** * * Created by AoEiuV020 on 2018.04.06-02:37:52. */ object ServerManager : AnkoLogger { private var novelService: NovelService? = null private var outOfVersion: Boolean = false private var disabled: Boolean = false var config: Config? = null fun downloadUpdate(ctx: Context, extra: String) { debug { "downloadUpdate $extra" } ctx.doAsync({ e -> val message = "更新通知解析失败," Reporter.post(message, e) error(message, e) }) { val remoteNovel: Novel = extra.jsonPath.get<String>("novel").toBean() requireNotNull(remoteNovel.site) requireNotNull(remoteNovel.author) requireNotNull(remoteNovel.name) requireNotNull(remoteNovel.detail) requireNotNull(remoteNovel.chaptersCount) val (localNovel, hasUpdate) = DataManager.receiveUpdate(remoteNovel) if (!hasUpdate || !ServerSettings.notifyNovelUpdate) { // 没有更新或者不通知更新就不继续, return@doAsync } debug { "notifyPinnedOnly: ${ServerSettings.notifyPinnedOnly}" } debug { "pinnedTime: ${localNovel.pinnedTime}" } debug { "pinnedTime.notZero: ${localNovel.pinnedTime.notZero()}" } if (ServerSettings.notifyPinnedOnly && localNovel.pinnedTime.notZero() == null) { return@doAsync } debug { "notify update: $localNovel" } if (ServerSettings.singleNotification) { val bitText = DataManager.hasUpdateNovelList() .joinToString("\n") { it.run { "$name: $lastChapterName" } } uiThread { it.notify(id = 2, text = localNovel.lastChapterName, title = it.getString(R.string.notify_has_update_title_placeholder, localNovel.name), bigText = bitText, time = localNovel.receiveUpdateTime.notZero()?.time, channelId = NotificationChannelId.update) } } else { uiThread { it.notify(id = localNovel.nId.toInt(), text = localNovel.lastChapterName, title = it.getString(R.string.notify_has_update_title_placeholder, localNovel.name), time = localNovel.receiveUpdateTime.notZero()?.time, channelId = NotificationChannelId.update) } } } } fun queryList(novelMap: Map<Long, Novel>): Map<Long, QueryResponse> { debug { "queryList :${novelMap.map { "${it.key}=${it.value.bookId}" }}" } val service = getService() ?: return emptyMap() return service.queryList(novelMap).also { debug { "查询小说更新返回: $it" } } } fun touch(novel: Novel) { // 意义不大,禁用了, } fun message(): Message? { debug { "message :" } return try { DnsUtils.txtToBean(ServerAddress.MESSAGE_HOST) } catch (e: Exception) { warn("get message failed: " + ServerAddress.MESSAGE_HOST, e) null } } @Synchronized @WorkerThread private fun getService(): NovelService? { debug { "getService <$novelService, $outOfVersion>" } // 已经创建就直接返回, novelService?.let { return it } // 如果版本过低,直接返回空,不继续, if (outOfVersion) return null // 暂时禁用了, if (disabled) return null val config: Config try { config = DnsUtils.txtToBean(ServerAddress.CONFIG_HOST) } catch (e: Exception) { warn("get config failed: " + ServerAddress.CONFIG_HOST, e) disabled = true return null } this.config = config val apiUrl: String = config.apiUrl.takeIf { !it.isNullOrEmpty() } ?: run { disabled = true return null } val minVersion = VersionName(config.minVersion) val currentVersion = VersionName(VersionUtil.getAppVersionName(App.ctx)) info { "getService minVersion $minVersion/$currentVersion" } if (currentVersion < minVersion) { // 如果版本过低,直接返回空,不继续, outOfVersion = true return null } val serverAddress = ServerAddress.new(ServerSettings.serverAddress.takeIf { !it.isNullOrEmpty() } ?: apiUrl) info { "server: " + serverAddress.baseUrl } return NovelServiceImpl(serverAddress) } }
gpl-3.0
nickthecoder/paratask
paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/gui/DragHelper.kt
1
785
/* ParaTask Copyright (C) 2017 Nick Robinson> 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 uk.co.nickthecoder.paratask.gui import javafx.scene.Node interface DragHelper { fun applyTo(node: Node) }
gpl-3.0
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/tools/places/CopyFilesTask.kt
1
1590
/* ParaTask Copyright (C) 2017 Nick Robinson 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 uk.co.nickthecoder.paratask.tools.places import uk.co.nickthecoder.paratask.AbstractTask import uk.co.nickthecoder.paratask.TaskDescription import uk.co.nickthecoder.paratask.parameters.FileParameter import uk.co.nickthecoder.paratask.parameters.MultipleParameter import uk.co.nickthecoder.paratask.util.process.Exec import uk.co.nickthecoder.paratask.util.process.OSCommand class CopyFilesTask : AbstractTask() { override val taskD = TaskDescription("copyFiles") val filesP = MultipleParameter("files", minItems = 1) { FileParameter("file", expectFile = null, mustExist = true) } val toDirectoryP = FileParameter("toDirectory", mustExist = true, expectFile = false) init { taskD.addParameters(filesP, toDirectoryP) } override fun run() { val command = OSCommand("cp", "--archive", "--", filesP.value, toDirectoryP.value!!) Exec(command).start().waitFor() } }
gpl-3.0
jonalmeida/focus-android
app/src/main/java/org/mozilla/focus/autocomplete/AutocompleteSettingsFragment.kt
1
1864
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.autocomplete import android.content.SharedPreferences import android.os.Bundle import org.mozilla.focus.R import org.mozilla.focus.settings.BaseSettingsFragment import org.mozilla.focus.telemetry.TelemetryWrapper /** * Settings UI for configuring autocomplete. */ class AutocompleteSettingsFragment : BaseSettingsFragment(), SharedPreferences.OnSharedPreferenceChangeListener { override fun onCreatePreferences(p0: Bundle?, p1: String?) { addPreferencesFromResource(R.xml.autocomplete) } override fun onResume() { super.onResume() val updater = activity as BaseSettingsFragment.ActionBarUpdater updater.updateTitle(R.string.preference_subitem_autocomplete) updater.updateIcon(R.drawable.ic_back) preferenceManager.sharedPreferences.registerOnSharedPreferenceChangeListener(this) } override fun onPause() { super.onPause() preferenceManager.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) } override fun onPreferenceTreeClick(preference: androidx.preference.Preference?): Boolean { preference?.let { if (it.key == getString(R.string.pref_key_screen_custom_domains)) { navigateToFragment(AutocompleteListFragment()) } } return super.onPreferenceTreeClick(preference) } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) { if (key == null || sharedPreferences == null) { return } TelemetryWrapper.settingsEvent(key, sharedPreferences.all[key].toString()) } }
mpl-2.0
antoniolg/KataContactsKotlin
src/main/java/com/antonioleiva/kataagenda/ui/SysOutContactsListView.kt
1
1717
/* * Copyright (C) 2015 Antonio Leiva * * 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.antonioleiva.kataagenda.ui import com.antonioleiva.kataagenda.domain.Contact class SysOutContactsListView : ContactsListPresenter.View { override fun showWelcomeMessage() { println("Welcome to your awesome agenda!") println("I'm going to ask you about some of your contacts information :)") } override fun showGoodbyeMessage() { println("\n\nSee you soon!") } override fun showContacts(contactList: List<Contact>) { println() contactList.forEach { println("${it.firstName} - ${it.lastName} - ${it.phone}") } println() } override fun getNewContactFirstName(): String = readLine("First Name: ") override fun getNewContactLastName(): String = readLine("Last Name: ") override fun getNewContactPhoneNumber(): String = readLine("Phone Number: ") override fun showDefaultError() = println("Ups, something went wrong :( Try again!") override fun showEmptyCase() = println("Your agenda is empty!") private fun readLine(message: String): String { print(message) return readLine() ?: "" } }
apache-2.0
pgutkowski/KGraphQL
src/main/kotlin/com/github/pgutkowski/kgraphql/request/TypeReference.kt
1
684
package com.github.pgutkowski.kgraphql.request /** * Raw reference to type, e.g. in query variables section '($var: [String!]!)', '[String!]!' is type reference */ data class TypeReference ( val name: String, val isNullable: Boolean = false, val isList : Boolean = false, val isElementNullable: Boolean = isList ) { override fun toString(): String { return buildString { if (isList){ append("[").append(name) if(!isElementNullable) append("!") append("]") } else { append(name) } if(!isNullable) append("!") } } }
mit
nemerosa/ontrack
ontrack-service/src/main/java/net/nemerosa/ontrack/service/settings/SecuritySettingsManager.kt
1
1478
package net.nemerosa.ontrack.service.settings import net.nemerosa.ontrack.model.form.Form import net.nemerosa.ontrack.model.security.SecurityService import net.nemerosa.ontrack.model.settings.AbstractSettingsManager import net.nemerosa.ontrack.model.settings.CachedSettingsService import net.nemerosa.ontrack.model.settings.SecuritySettings import net.nemerosa.ontrack.model.support.SettingsRepository import org.springframework.stereotype.Component @Component class SecuritySettingsManager( cachedSettingsService: CachedSettingsService, private val settingsRepository: SettingsRepository, securityService: SecurityService ) : AbstractSettingsManager<SecuritySettings>(SecuritySettings::class.java, cachedSettingsService, securityService) { override fun getSettingsForm(settings: SecuritySettings): Form = settings.form() override fun doSaveSettings(settings: SecuritySettings) { settingsRepository.setBoolean(SecuritySettings::class.java, "grantProjectViewToAll", settings.isGrantProjectViewToAll) settingsRepository.setBoolean(SecuritySettings::class.java, "grantProjectParticipationToAll", settings.isGrantProjectParticipationToAll) settingsRepository.setBoolean(SecuritySettings::class.java, SecuritySettings::builtInAuthenticationEnabled.name, settings.builtInAuthenticationEnabled) } override fun getId(): String = "general-security" override fun getTitle(): String = "General security settings" }
mit
wiltonlazary/kotlin-native
tools/kotlin-native-gradle-plugin/src/main/kotlin/org/jetbrains/kotlin/gradle/plugin/konan/tasks/KonanBuildingTask.kt
1
2099
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.gradle.plugin.tasks import org.gradle.api.tasks.Console import org.gradle.api.tasks.Input import org.gradle.api.tasks.Internal import org.gradle.api.tasks.TaskAction import org.jetbrains.kotlin.gradle.plugin.konan.* import org.jetbrains.kotlin.gradle.plugin.model.KonanModelArtifact import org.jetbrains.kotlin.konan.target.KonanTarget import java.io.File /** Base class for both interop and compiler tasks. */ abstract class KonanBuildingTask: KonanArtifactWithLibrariesTask(), KonanBuildingSpec { @get:Internal internal abstract val toolRunner: KonanToolRunner internal abstract fun toModelArtifact(): KonanModelArtifact override fun init(config: KonanBuildingConfig<*>, destinationDir: File, artifactName: String, target: KonanTarget) { dependsOn(project.konanCompilerDownloadTask) super.init(config, destinationDir, artifactName, target) } @Console var dumpParameters: Boolean = false @Input val extraOpts = mutableListOf<String>() val konanHome @Input get() = project.konanHome val konanVersion @Input get() = project.konanVersion.toString(true, true) @TaskAction abstract fun run() // DSL. override fun dumpParameters(flag: Boolean) { dumpParameters = flag } override fun extraOpts(vararg values: Any) = extraOpts(values.toList()) override fun extraOpts(values: List<Any>) { extraOpts.addAll(values.map { it.toString() }) } }
apache-2.0
nemerosa/ontrack
ontrack-extension-github/src/main/java/net/nemerosa/ontrack/extension/github/ingestion/processing/NoGitHubConfigException.kt
1
282
package net.nemerosa.ontrack.extension.github.ingestion.processing import net.nemerosa.ontrack.common.BaseException class NoGitHubConfigException : BaseException( "No GitHub Workflow ingestion can be performed because no GitHub configuration has been registered in Ontrack." )
mit
wiltonlazary/kotlin-native
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/objcexport/ObjCExportHeaderGeneratorImpl.kt
1
1851
/* * Copyright 2010-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.kotlin.backend.konan.objcexport import org.jetbrains.kotlin.backend.konan.Context import org.jetbrains.kotlin.backend.konan.KonanConfigKeys import org.jetbrains.kotlin.backend.konan.reportCompilationWarning import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.MessageUtil import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithSource import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.resolve.source.getPsi internal class ObjCExportHeaderGeneratorImpl( val context: Context, moduleDescriptors: List<ModuleDescriptor>, mapper: ObjCExportMapper, namer: ObjCExportNamer, objcGenerics: Boolean ) : ObjCExportHeaderGenerator(moduleDescriptors, mapper, namer, objcGenerics) { override fun reportWarning(text: String) { context.reportCompilationWarning(text) } override fun reportWarning(method: FunctionDescriptor, text: String) { val psi = (method as? DeclarationDescriptorWithSource)?.source?.getPsi() ?: return reportWarning( "$text\n (at ${DescriptorRenderer.COMPACT_WITH_SHORT_TYPES.render(method)})" ) val location = MessageUtil.psiElementToMessageLocation(psi) context.messageCollector.report(CompilerMessageSeverity.WARNING, text, location) } override fun getAdditionalImports(): List<String> = context.config.configuration.getNotNull(KonanConfigKeys.FRAMEWORK_IMPORT_HEADERS) }
apache-2.0
ibaton/3House
mobile/src/main/java/treehou/se/habit/dagger/fragment/LightModule.kt
1
769
package treehou.se.habit.dagger.fragment import android.os.Bundle import dagger.Module import dagger.Provides import treehou.se.habit.dagger.ViewModule import treehou.se.habit.ui.colorpicker.LightContract import treehou.se.habit.ui.colorpicker.LightFragment import treehou.se.habit.ui.colorpicker.LightPresenter import javax.inject.Named @Module class LightModule(fragment: LightFragment, protected val args: Bundle) : ViewModule<LightFragment>(fragment) { @Provides fun provideView(): LightContract.View? { return view } @Provides fun providePresenter(presenter: LightPresenter): LightContract.Presenter { return presenter } @Provides @Named("arguments") fun provideArgs(): Bundle { return args } }
epl-1.0
DemonWav/IntelliJBukkitSupport
src/main/kotlin/nbt/tags/TagFloat.kt
1
672
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.tags import java.io.DataOutputStream class TagFloat(override val value: Float) : NbtValueTag<Float>(Float::class.java) { override val payloadSize = 4 override val typeId = NbtTypeId.FLOAT override fun write(stream: DataOutputStream) { stream.writeFloat(value) } override fun toString() = toString(StringBuilder(), 0, WriterState.COMPOUND).toString() override fun toString(sb: StringBuilder, indentLevel: Int, writerState: WriterState) = sb.append(value).append('F')!! }
mit
drakeet/MultiType
sample/src/main/kotlin/com/drakeet/multitype/sample/weibo/WeiboJsonParser.kt
1
1064
/* * Copyright (c) 2016-present. Drakeet Xu * * 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.drakeet.multitype.sample.weibo import com.google.gson.GsonBuilder import com.google.gson.reflect.TypeToken import java.util.* /** * @author Drakeet Xu */ internal object WeiboJsonParser { val GSON = GsonBuilder() .registerTypeAdapter(WeiboContent::class.java, WeiboContentDeserializer()) .create()!! fun fromJson(json: String): List<Weibo> { return GSON.fromJson(json, object : TypeToken<ArrayList<Weibo>>() {}.type) } }
apache-2.0
Ztiany/Repository
Kotlin/Kotlin-github/layout/src/main/java/com/bennyhuo/dsl/layout/v1/DslViewParent.kt
2
2216
package com.bennyhuo.dsl.layout.v1 import android.annotation.TargetApi import android.os.Build.VERSION_CODES import android.view.View import android.view.ViewGroup import kotlin.annotation.AnnotationTarget.* @DslMarker @Target(CLASS, TYPE, TYPEALIAS) annotation class DslViewMarker @DslViewMarker interface DslViewParent<out P : ViewGroup.MarginLayoutParams> { val <T : View> T.lparams: P get() = layoutParams as P var <T : View> T.leftMargin: Int set(value) { lparams.leftMargin = value } get() { return lparams.leftMargin } var <T : View> T.topMargin: Int set(value) { lparams.topMargin = value } get() { return lparams.topMargin } var <T : View> T.rightMargin: Int set(value) { lparams.rightMargin = value } get() { return lparams.rightMargin } var <T : View> T.bottomMargin: Int set(value) { lparams.bottomMargin = value } get() { return lparams.bottomMargin } @get:TargetApi(VERSION_CODES.JELLY_BEAN_MR1) @set:TargetApi(VERSION_CODES.JELLY_BEAN_MR1) var <T : View> T.startMargin: Int set(value) { lparams.marginStart = value } get() { return lparams.marginStart } @get:TargetApi(VERSION_CODES.JELLY_BEAN_MR1) @set:TargetApi(VERSION_CODES.JELLY_BEAN_MR1) var <T : View> T.endMargin: Int set(value) { lparams.marginEnd = value } get() { return lparams.marginEnd } fun <T : View> T.margin(margin: Int) { leftMargin = margin topMargin = margin rightMargin = margin bottomMargin = margin startMargin = margin endMargin = margin } var <T : View> T.layoutWidth: Int set(value) { lparams.width = value } get() { return lparams.width } var <T : View> T.layoutHeight: Int set(value) { lparams.height = value } get() { return lparams.height } }
apache-2.0
openstreetview/android
app/src/main/java/com/telenav/osv/map/MapFragment.kt
1
21040
package com.telenav.osv.map import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.Intent import android.location.Location import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.constraintlayout.widget.ConstraintLayout import androidx.constraintlayout.widget.ConstraintSet import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.google.android.material.snackbar.Snackbar import com.mapbox.mapboxsdk.geometry.LatLng import com.mapbox.mapboxsdk.maps.MapboxMap import com.mapbox.mapboxsdk.maps.MapboxMap.OnCameraMoveStartedListener.REASON_API_GESTURE import com.mapbox.mapboxsdk.maps.MapboxMap.OnCameraMoveStartedListener.REASON_DEVELOPER_ANIMATION import com.mapbox.mapboxsdk.maps.Style import com.telenav.osv.R import com.telenav.osv.activity.KVActivityTempBase import com.telenav.osv.activity.LocationPermissionsListener import com.telenav.osv.activity.MainActivity import com.telenav.osv.activity.OSVActivity import com.telenav.osv.application.ApplicationPreferences import com.telenav.osv.application.KVApplication import com.telenav.osv.application.PreferenceTypes import com.telenav.osv.common.Injection import com.telenav.osv.common.dialog.KVDialog import com.telenav.osv.databinding.FragmentMapBinding import com.telenav.osv.jarvis.login.utils.LoginUtils import com.telenav.osv.location.LocationService import com.telenav.osv.manager.playback.PlaybackManager import com.telenav.osv.map.model.* import com.telenav.osv.map.model.MapModes import com.telenav.osv.map.render.MapRender import com.telenav.osv.map.render.template.MapRenderTemplateIdentifier import com.telenav.osv.map.viewmodel.MapViewModel import com.telenav.osv.recorder.gpsTrail.ListenerRecordingGpsTrail import com.telenav.osv.tasks.activity.KEY_TASK_ID import com.telenav.osv.tasks.activity.TaskActivity import com.telenav.osv.ui.ScreenComposer import com.telenav.osv.ui.fragment.DisplayFragment import com.telenav.osv.ui.fragment.camera.controls.viewmodel.RecordingViewModel import com.telenav.osv.utils.Log import com.telenav.osv.utils.LogUtils import com.telenav.osv.utils.PermissionUtils import com.telenav.osv.utils.Utils import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.fragment_map.* /** * Fragment which represent the map feature. Holds logic in order to render a usable map by using the internal [MapboxMap] and helper [MapRender]. */ class MapFragment(private var mapMode: MapModes = MapModes.IDLE, private var playbackManager: PlaybackManager? = null) : DisplayFragment(), LocationPermissionsListener, ListenerRecordingGpsTrail { init { TAG = MapFragment::class.java.simpleName } private var mapRender: MapRender? = null private lateinit var appPrefs: ApplicationPreferences private var mapboxMap: MapboxMap? = null private lateinit var fragmentMapBinding: FragmentMapBinding private lateinit var locationService: LocationService private lateinit var recordingViewModel: RecordingViewModel private val disposables: CompositeDisposable = CompositeDisposable() private var sessionExpireDialog: KVDialog? = null private val mapClickListener: MapboxMap.OnMapClickListener = MapboxMap.OnMapClickListener { if (LoginUtils.isLoginTypePartner(appPrefs)) { val selectedGridId = mapRender?.mapGridClick(it) if (selectedGridId != null) { val taskDetailsIntent = Intent(context, TaskActivity::class.java) taskDetailsIntent.putExtra(KEY_TASK_ID, selectedGridId) context?.startActivity(taskDetailsIntent) return@OnMapClickListener true } else return@OnMapClickListener mapViewModel.onNearbySequencesClick(it) } else { return@OnMapClickListener mapViewModel.onNearbySequencesClick(it) } } private val onCameraMoveStartedListener: MapboxMap.OnCameraMoveStartedListener = MapboxMap.OnCameraMoveStartedListener { if (it == REASON_API_GESTURE || it == REASON_DEVELOPER_ANIMATION) { onMapMove() } } private val mapViewModel: MapViewModel by lazy { ViewModelProviders.of(this, Injection.provideMapViewFactory(Injection.provideLocationLocalDataSource(context!!), Injection.provideUserRepository(context!!), Injection.provideGridsLoader( Injection.provideFetchAssignedTasksUseCase( Injection.provideTasksApi(true, Injection.provideApplicationPreferences(context!!))), Injection.provideGenericJarvisApiErrorHandler(context!!, Injection.provideApplicationPreferences(context!!))), Injection.provideGeometryRetriever(context!!, Injection.provideNetworkFactoryUrl(Injection.provideApplicationPreferences(context!!))), Injection.provideApplicationPreferences(context!!), recordingViewModel)).get(MapViewModel::class.java) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d(TAG, "onCreate") this.recordingViewModel = ViewModelProviders.of(activity!!).get(RecordingViewModel::class.java) activity?.let { appPrefs = (it.application as KVApplication).appPrefs locationService = Injection.provideLocationService(it.applicationContext) initLocation() } if (savedInstanceState != null) { Log.d(TAG, "onCreate. Status: restore saved instance state.") val savedMapMode = MapModes.getByType(savedInstanceState.getInt(KEY_MAP_MODE)) if (savedMapMode != null) { this.mapMode = savedMapMode } } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { fragmentMapBinding = FragmentMapBinding.inflate(inflater, container, false).apply { clickListenerCamera = View.OnClickListener { activity?.let { if (it is MainActivity) { it.goToRecordingScreen() } } } clickListenerCenter = View.OnClickListener { getLastKnowLocationAsync { location -> mapRender?.centerOnCurrentLocation(location) } } lifecycleOwner = this@MapFragment viewModel = mapViewModel } return fragmentMapBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) fragmentMapBinding.tvTasks.setOnClickListener { context?.startActivity(Intent(context, TaskActivity::class.java)) } observerOnLoginDialog() observeOnNearbySequences() observeOnEnableProgress() observeOnMapRender() observeOnMapUpdate() observeOnRecordingStateChanged() setMarginForRecordingIfRequired() mapView?.onCreate(savedInstanceState) } override fun onStart() { mapViewModel.enableEventBus(true) super.onStart() mapView?.onStart() } override fun onResume() { super.onResume() mapView?.onResume() if (recordingViewModel.isRecording) { recordingViewModel.setListenerRecordingGpsTrail(this) } switchMapMode(mapMode, playbackManager) } override fun onPause() { super.onPause() mapView?.onPause() recordingViewModel.removeListenerRecordingGpsTrail(this) } override fun setSource(extra: Any?) { } override fun onStop() { mapViewModel.enableEventBus(false) super.onStop() mapView?.onStop() } override fun onLowMemory() { super.onLowMemory() mapView?.onLowMemory() } override fun onDestroy() { disposables.clear() super.onDestroy() } override fun onDestroyView() { this.mapboxMap?.removeOnCameraMoveStartedListener(onCameraMoveStartedListener) mapRender?.clearMap() mapView?.onDestroy() Log.d(TAG, "onDestroyView. Map loaded: ${mapView != null}") super.onDestroyView() } override fun onSaveInstanceState(outState: Bundle) { outState.apply { this.putInt(KEY_MAP_MODE, mapMode.mode) } super.onSaveInstanceState(outState) mapView?.onSaveInstanceState(outState) } override fun onLocationPermissionGranted() { LogUtils.logDebug(TAG, "onLocationPermissionGranted. Initialising map.") getLastKnowLocationAsync { location -> mapRender?.centerOnCurrentLocation(location) } initLocation() } override fun onLocationPermissionDenied() { context?.let { Toast.makeText(context, R.string.enable_location_label, Toast.LENGTH_SHORT).show() } } override fun onGpsTrailChanged(gpsTrail: List<Location>) { onMapMove() mapRender?.updateRecording(gpsTrail) } /** * Switches the map mode for the map. This method only exposes the viewModel logic. * //ToDo: to be removed, recommended inject the view model directly for direct control of the fragment. */ fun switchMapMode(mapMode: MapModes, playbackManager: PlaybackManager? = null) { activity?.let { this.mapMode = mapMode //preserve reference to the playback manager for the case when the fragment is not added yet this.playbackManager = playbackManager mapViewModel.setupMapResource(Injection.provideMapBoxOkHttpClient(appPrefs)) if (isAdded) { Log.d(TAG, "Switching map mode: ${mapMode.mode}.") mapViewModel.switchMode(mapMode, playbackManager) } } } private fun setMarginForRecordingIfRequired() { if (mapMode.mode == MapModes.RECORDING.mode) { context?.let { val set = ConstraintSet() set.clone(fragmentMapBinding.root as ConstraintLayout) set.setMargin(R.id.mapView, ConstraintSet.TOP, 0) set.applyTo(fragmentMapBinding.root as ConstraintLayout) } } } private fun observeOnRecordingStateChanged() { recordingViewModel.let { Log.d(TAG, "observeOnRecordingStateChanged. Recording status: ${it.isRecording}") it.recordingObservable?.observe(this, Observer { recordingStatus -> Log.d(TAG, "recordingObservable. Recording status: $recordingStatus") if (recordingStatus) { recordingViewModel.setListenerRecordingGpsTrail(this) } else { mapRender?.clearGpsTrail() recordingViewModel.removeListenerRecordingGpsTrail(this) mapViewModel.switchMode(mapMode, null) } }) } } private fun observeOnNearbySequences() { mapViewModel.nearbySequences.observe(this, Observer { val activity = activity as OSVActivity if (it != null) { activity.openScreen(ScreenComposer.SCREEN_NEARBY, it) } else { activity.showSnackBar(getString(R.string.nearby_no_result_label), Snackbar.LENGTH_SHORT) } }) } /** * This method displays alert dialog for expired session */ private fun showSessionExpiredDialog(context: Context) { if (sessionExpireDialog == null) { sessionExpireDialog = LoginUtils.getSessionExpiredDialog(context) } sessionExpireDialog?.show() } private fun observeOnEnableProgress() { mapViewModel.enableProgress.observe(this, Observer { (activity as OSVActivity).enableProgressBar(it) }) } private fun observerOnLoginDialog() { mapViewModel.shouldReLogin.observe(this, Observer { shouldReLogin -> if (shouldReLogin) { context?.let { showSessionExpiredDialog(it) } } }) } private fun observeOnMapRender() { mapViewModel.mapRender.observe(this, Observer { Log.d(TAG, "observeOnMapRender. Map status change: $it") if (it.value == MapRenderMode.DISABLED.value) { mapRender?.clearMap() val mapView = fragmentMapBinding.root.findViewById(R.id.mapView) as View mapView.visibility = View.GONE } else { loadMap { when (it.value) { MapRenderMode.DEFAULT.value -> { this.mapboxMap?.uiSettings?.setAllGesturesEnabled(true) this.mapboxMap?.addOnCameraMoveStartedListener(onCameraMoveStartedListener) this.mapboxMap?.addOnMapClickListener(mapClickListener) mapRender?.render(MapRenderTemplateIdentifier.DEFAULT) getLastKnowLocationAsync { location -> mapRender?.centerOnCurrentLocation(location) } } MapRenderMode.DEFAULT_WITH_GRID.value -> { this.mapboxMap?.uiSettings?.setAllGesturesEnabled(true) this.mapboxMap?.addOnCameraMoveStartedListener(onCameraMoveStartedListener) mapRender?.render(MapRenderTemplateIdentifier.GRID) this.mapboxMap?.addOnMapClickListener(mapClickListener) getLastKnowLocationAsync { location -> run { mapRender?.centerOnCurrentLocation(location) onMapMove(true) } } } MapRenderMode.PREVIEW.value -> { this.mapboxMap?.uiSettings?.setAllGesturesEnabled(false) this.mapboxMap?.removeOnMapClickListener(mapClickListener) this.mapboxMap?.removeOnCameraMoveStartedListener(onCameraMoveStartedListener) mapRender?.render(MapRenderTemplateIdentifier.PREVIEW) } MapRenderMode.RECORDING.value -> { Log.d(TAG, "loadMap function. Status: map render recording function. Message: Preparing for recording.") this.mapboxMap?.addOnCameraMoveStartedListener(onCameraMoveStartedListener) this.mapboxMap?.uiSettings?.setAllGesturesEnabled(false) this.mapboxMap?.uiSettings?.isZoomGesturesEnabled = true this.mapboxMap?.removeOnMapClickListener(mapClickListener) mapRender?.render(MapRenderTemplateIdentifier.RECORDING) } else -> { //nothing since it is not required to add disabled } } } } }) } private fun observeOnMapUpdate() { mapViewModel.mapRenderUpdate.observe(this, Observer { Log.d(TAG, "observeOnMapUpdate. Map update change: $it") when (it) { is MapUpdateDefault -> { getLastKnowLocationAsync { location -> mapRender?.updateDefault(it.sequences, location) } } is MapUpdateGrid -> { if (it.tasks.isNotEmpty()) { mapRender?.refreshCoverage(it.tasks[0].createdAt) } mapRender?.updateGrid(it.tasks, it.jarvisUserId, it.includeLabels, it.sequences) } is MapUpdatePreview -> { mapRender?.updatePreview(it.localSequence, it.symbolLocation) } is MapUpdateRecording -> { getLastKnowLocationAsync { location -> Log.d(TAG, "loadMap function. Status: centerOnCurrentPosition callback. Message: Preparing for render map in recording mode. Location: $location. Sequence size: ${it.sequences.size}") run { mapRender?.updateRecording(location, it.sequences) onMapMove() } } } } }) } private fun loadMap(function: () -> Unit) { mapView?.visibility = View.VISIBLE mapView?.getMapAsync { mapBoxMap -> if (this.mapboxMap == null) { Log.d(TAG, "loadMap. Status: initialising map.") this.mapboxMap = mapBoxMap this.mapboxMap?.setStyle(Style.LIGHT) } context?.let { context -> Log.d(TAG, "loadMap. Status: initialising map render.") if (mapRender == null) { mapRender = MapRender(context, mapboxMap!!, Injection.provideNetworkFactoryUrl(appPrefs), Injection.provideCurrencyUtil()) } function() } } } @SuppressLint("CheckResult") @Suppress("IMPLICIT_CAST_TO_ANY") private fun getLastKnowLocationAsync(callback: (LatLng) -> Unit) { activity?.let { val kvActivityTempBase = it as KVActivityTempBase val locationPermission = android.Manifest.permission.ACCESS_FINE_LOCATION if (PermissionUtils.isPermissionGranted(it.applicationContext, locationPermission)) { locationService .lastKnownLocation .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ location -> callback(LatLng(location.latitude, location.longitude)) LogUtils.logDebug(TAG, "getLastKnowLocationAsync. Status: success.") }, { error: Throwable? -> LogUtils.logDebug(TAG, "getLastKnowLocationAsync. Error: ${error?.message}") if (!Utils.isGPSEnabled(it.applicationContext)) { kvActivityTempBase.resolveLocationProblem() } }) } else { PermissionUtils.checkPermissionsForGPS(it as Activity) } } } private fun initLocation() { activity?.let { if (PermissionUtils.isPermissionGranted(it.applicationContext, android.Manifest.permission.ACCESS_FINE_LOCATION)) { if (Utils.isGPSEnabled(it.applicationContext)) { locationService .lastKnownLocation .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ location -> appPrefs.saveBooleanPreference(PreferenceTypes.K_DISTANCE_UNIT_METRIC, !mapViewModel.initMetricBasedOnCcp(location)) }, { error: Throwable? -> LogUtils.logDebug(TAG, "centerOnCurrentPosition. Error: ${error?.message}") }) } } } } private fun onMapMove(forceLoad: Boolean = false) { val loadGrid = mapMode.mode == MapModes.GRID.mode || mapMode.mode == MapModes.IDLE.mode || mapMode.mode == MapModes.RECORDING.mode Log.d(TAG, "onMapMove. Status: performing grid load if required. Required: $loadGrid. Map mode: ${mapMode.mode}. Force loads: $forceLoad") if (loadGrid) { mapboxMap?.let { mapboxMap -> getLastKnowLocationAsync { mapViewModel.onGridsLoadIfAvailable(mapboxMap.cameraPosition.zoom, mapboxMap.projection.visibleRegion.latLngBounds, it, forceLoad) } } } } companion object { lateinit var TAG: String private const val KEY_MAP_MODE = "key_map_mode" /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * @return A new instance of fragment MapFragment. */ @JvmStatic fun newInstance(mapMode: MapModes = MapModes.IDLE, playbackManager: PlaybackManager? = null) = MapFragment(mapMode, playbackManager) } }
lgpl-3.0
chilangolabs/MDBancomer
app/src/main/java/com/chilangolabs/mdb/customviews/MDBFontManager.kt
1
1913
package com.chilangolabs.mdb.customviews import android.content.Context import android.graphics.Typeface import android.util.AttributeSet import android.view.View import android.widget.Button import android.widget.EditText import android.widget.TextView import com.chilangolabs.mdb.R /** * @author Gorro. */ class MDBFontManager(private val context: Context?) { /** * Init custom font to view * @param view you want asing font * @param attrs attributeset with value of font can be null */ fun initStyle(view: View, attrs: AttributeSet? = null) { if (attrs != null) { val typedArray = context?.theme?.obtainStyledAttributes(attrs, R.styleable.fontraleway, 0, 0) val tp = when (typedArray?.getInteger(R.styleable.fontraleway_type, 0)) { 0 -> Typeface.createFromAsset(context?.assets, "fonts/Raleway-Light.ttf") 1 -> Typeface.createFromAsset(context?.assets, "fonts/Raleway-Medium.ttf") 2 -> Typeface.createFromAsset(context?.assets, "fonts/Raleway-Regular.ttf") 3 -> Typeface.createFromAsset(context?.assets, "fonts/Raleway-SemiBold.ttf") else -> { Typeface.createFromAsset(context?.assets, "fonts/Raleway-Regular.ttf") } } typedArray?.recycle() setTypeFace(view, tp) } else { setTypeFace(view) } } /** * This function asing typeface to view * @param view view you want asing the typeface font * @param tp this is the typeface can be null */ fun setTypeFace(view: View, tp: Typeface = Typeface.createFromAsset(context?.assets, "fonts/Raleway-Regular.ttf")) { when (view) { is TextView -> view.typeface = tp is EditText -> view.typeface = tp is Button -> view.typeface = tp } } }
mit
DarrenAtherton49/android-kotlin-base
app/src/main/kotlin/com/atherton/sample/util/parcel/Parcelers.kt
1
372
package com.atherton.sample.util.parcel import android.os.Parcel import kotlinx.android.parcel.Parceler import java.io.IOException object IOExceptionParceler : Parceler<IOException> { override fun create(parcel: Parcel) = IOException(parcel.readString()) override fun IOException.write(parcel: Parcel, flags: Int) { parcel.writeString(message) } }
mit
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/exception/MalformedResponseException.kt
1
1063
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.exception import de.vanita5.microblog.library.MicroBlogException class MalformedResponseException : MicroBlogException("Malformed response object")
gpl-3.0
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/analytics/eventplatform/ArticleInteractionEvent.kt
1
2589
package org.wikipedia.analytics.eventplatform import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable class ArticleInteractionEvent(private val wikiDb: String, private val pageId: Int) : TimedEvent() { fun logLoaded() { submitEvent("load") } fun logSaveClick() { submitEvent("save") } fun logLanguageClick() { submitEvent("language") } fun logFindInArticleClick() { submitEvent("find_in_article") } fun logThemeClick() { submitEvent("theme") } fun logContentsClick() { submitEvent("contents") } fun logMoreClick() { submitEvent("more") } fun logShareClick() { submitEvent("share") } fun logTalkPageClick() { submitEvent("talk_page") } fun logEditHistoryClick() { submitEvent("edit_history") } fun logNewTabClick() { submitEvent("new_tab") } fun logExploreClick() { submitEvent("explore") } fun logForwardClick() { submitEvent("forward") } fun logNotificationClick() { submitEvent("notification") } fun logTabsClick() { submitEvent("tabs") } fun logSearchWikipediaClick() { submitEvent("search_wikipedia") } fun logBackClick() { submitEvent("back") } fun logEditHistoryArticleClick() { submitEvent("edit_history_from_article") } fun logTalkPageArticleClick() { submitEvent("talk_page_from_article") } fun logTocSwipe() { submitEvent("toc_swipe") } fun logCategoriesClick() { submitEvent("categories") } fun logWatchClick() { submitEvent("watch_article") } fun logUnWatchClick() { submitEvent("unwatch_article") } fun logEditArticleClick() { submitEvent("edit_article") } private fun submitEvent(action: String) { EventPlatformClient.submit(ArticleInteractionEventImpl(duration, wikiDb, pageId, action)) } @Suppress("unused") @Serializable @SerialName("/analytics/mobile_apps/android_article_toolbar_interaction/1.0.0") class ArticleInteractionEventImpl(@SerialName("time_spent_ms") private val timeSpentMs: Int, @SerialName("wiki_db") private val wikiDb: String, @SerialName("page_id") private val pageId: Int, private val action: String) : MobileAppsEvent("android.article_toolbar_interaction") }
apache-2.0
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/view/controller/twitter/card/CardBrowserViewController.kt
1
2150
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.view.controller.twitter.card import android.annotation.SuppressLint import android.view.View import android.view.ViewGroup import android.webkit.WebView import android.widget.FrameLayout import de.vanita5.twittnuker.view.ContainerView class CardBrowserViewController : ContainerView.ViewController() { lateinit var url: String override fun onCreateView(parent: ContainerView): View { val webView = WebView(context) webView.layoutParams = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) return webView } override fun onDestroyView(view: View) { (view as WebView).destroy() super.onDestroyView(view) } @SuppressLint("SetJavaScriptEnabled") override fun onCreate() { super.onCreate() val webView = view as WebView webView.settings.apply { javaScriptEnabled = true builtInZoomControls = false } webView.loadUrl(url) } companion object { fun show(url: String): CardBrowserViewController { val vc = CardBrowserViewController() vc.url = url return vc } } }
gpl-3.0
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/adapter/TrendsAdapter.kt
1
1752
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.adapter import android.content.Context import android.database.Cursor import android.support.v4.widget.SimpleCursorAdapter import de.vanita5.twittnuker.provider.TwidereDataStore class TrendsAdapter(context: Context) : SimpleCursorAdapter(context, android.R.layout.simple_list_item_1, null, arrayOf(TwidereDataStore.CachedTrends.NAME), intArrayOf(android.R.id.text1), 0) { private var nameIdx: Int = 0 override fun getItem(position: Int): String? { val c = cursor if (c != null && !c.isClosed && c.moveToPosition(position)) return c.getString(nameIdx) return null } override fun swapCursor(c: Cursor?): Cursor? { if (c != null) { nameIdx = c.getColumnIndex(TwidereDataStore.CachedTrends.NAME) } return super.swapCursor(c) } }
gpl-3.0
numa08/Gochisou
app/src/test/java/net/numa08/gochisou/data/service/AuthorizeURLGeneratorTest.kt
1
1161
package net.numa08.gochisou.data.service import android.net.Uri import android.os.Build import net.numa08.gochisou.BuildConfig import net.numa08.gochisou.testtools.MyTestRunner import org.hamcrest.CoreMatchers.`is` import org.junit.Assert.assertThat import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.Config @RunWith(MyTestRunner::class) @Config(constants = BuildConfig::class, sdk = intArrayOf(Build.VERSION_CODES.LOLLIPOP)) class AuthorizeURLGeneratorTest { val generator = AuthorizeURLGenerator() @Test fun generateURL() { val url = Uri.parse(generator.generateAuthorizeURL("clientID", "https://redirect.url")) assertThat(url.scheme, `is`("https")) assertThat(url.authority, `is`(AuthorizeURLGenerator.ENDPOINT)) assertThat(url.getQueryParameter("client_id"), `is`("clientID")) assertThat(url.getQueryParameter("redirect_uri"), `is`("https://redirect.url")) assertThat(url.getQueryParameter("scope"), `is`("write read")) assertThat(url.getQueryParameter("response_type"), `is`("code")) assert(url.getQueryParameter("state") == null) } }
mit
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/diff/ArticleEditDetailsViewModel.kt
1
11424
package org.wikipedia.diff import android.net.Uri import android.os.Bundle import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import kotlinx.coroutines.* import org.wikipedia.analytics.WatchlistFunnel import org.wikipedia.dataclient.Service import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import org.wikipedia.dataclient.mwapi.MwQueryPage import org.wikipedia.dataclient.restbase.DiffResponse import org.wikipedia.dataclient.restbase.Revision import org.wikipedia.dataclient.rollback.RollbackPostResponse import org.wikipedia.dataclient.watch.WatchPostResponse import org.wikipedia.dataclient.wikidata.EntityPostResponse import org.wikipedia.edit.Edit import org.wikipedia.page.PageTitle import org.wikipedia.util.Resource import org.wikipedia.util.SingleLiveData import org.wikipedia.watchlist.WatchlistExpiry class ArticleEditDetailsViewModel(bundle: Bundle) : ViewModel() { val watchedStatus = MutableLiveData<Resource<MwQueryPage>>() val rollbackRights = MutableLiveData<Resource<Boolean>>() val revisionDetails = MutableLiveData<Resource<Unit>>() val diffText = MutableLiveData<Resource<DiffResponse>>() val singleRevisionText = MutableLiveData<Resource<Revision>>() val thankStatus = SingleLiveData<Resource<EntityPostResponse>>() val watchResponse = SingleLiveData<Resource<WatchPostResponse>>() val undoEditResponse = SingleLiveData<Resource<Edit>>() val rollbackResponse = SingleLiveData<Resource<RollbackPostResponse>>() var watchlistExpiryChanged = false var lastWatchExpiry = WatchlistExpiry.NEVER var pageId = -1 private set val pageTitle = bundle.getParcelable<PageTitle>(ArticleEditDetailsActivity.EXTRA_ARTICLE_TITLE)!! var revisionToId = bundle.getLong(ArticleEditDetailsActivity.EXTRA_EDIT_REVISION_TO, -1) var revisionTo: MwQueryPage.Revision? = null var revisionFromId = bundle.getLong(ArticleEditDetailsActivity.EXTRA_EDIT_REVISION_FROM, -1) var revisionFrom: MwQueryPage.Revision? = null var canGoForward = false var hasRollbackRights = false private var diffRevisionId = 0L val diffSize get() = if (revisionFrom != null) revisionTo!!.size - revisionFrom!!.size else revisionTo!!.size private val watchlistFunnel = WatchlistFunnel() init { getWatchedStatusAndPageId() checkRollbackRights() getRevisionDetails(revisionToId, revisionFromId) } private fun getWatchedStatusAndPageId() { viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> watchedStatus.postValue(Resource.Error(throwable)) }) { withContext(Dispatchers.IO) { val page = ServiceFactory.get(pageTitle.wikiSite).getWatchedStatus(pageTitle.prefixedText).query?.firstPage()!! pageId = page.pageId watchedStatus.postValue(Resource.Success(page)) } } } private fun checkRollbackRights() { viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> rollbackRights.postValue(Resource.Error(throwable)) }) { withContext(Dispatchers.IO) { val userRights = ServiceFactory.get(pageTitle.wikiSite).userRights().query?.userInfo?.rights hasRollbackRights = userRights?.contains("rollback") == true rollbackRights.postValue(Resource.Success(hasRollbackRights)) } } } fun getRevisionDetails(revisionIdTo: Long, revisionIdFrom: Long = -1) { viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> revisionDetails.postValue(Resource.Error(throwable)) }) { withContext(Dispatchers.IO) { if (revisionIdFrom >= 0) { val responseFrom = async { ServiceFactory.get(pageTitle.wikiSite).getRevisionDetailsWithInfo(pageTitle.prefixedText, 2, revisionIdFrom) } val responseTo = async { ServiceFactory.get(pageTitle.wikiSite).getRevisionDetailsWithInfo(pageTitle.prefixedText, 2, revisionIdTo) } val pageTo = responseTo.await().query?.firstPage()!! revisionFrom = responseFrom.await().query?.firstPage()!!.revisions[0] revisionTo = pageTo.revisions[0] canGoForward = revisionTo!!.revId < pageTo.lastrevid } else { val response = ServiceFactory.get(pageTitle.wikiSite).getRevisionDetailsWithInfo(pageTitle.prefixedText, 2, revisionIdTo) val page = response.query?.firstPage()!! val revisions = page.revisions revisionTo = revisions[0] canGoForward = revisions[0].revId < page.lastrevid revisionFrom = revisions.getOrNull(1) } revisionToId = revisionTo!!.revId revisionFromId = if (revisionFrom != null) revisionFrom!!.revId else revisionTo!!.parentRevId revisionDetails.postValue(Resource.Success(Unit)) getDiffText(revisionFromId, revisionToId) } } } fun goBackward() { revisionToId = revisionFromId getRevisionDetails(revisionToId) } fun goForward() { val revisionIdFrom = revisionToId viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> revisionDetails.postValue(Resource.Error(throwable)) }) { withContext(Dispatchers.IO) { val response = ServiceFactory.get(pageTitle.wikiSite).getRevisionDetailsAscending(pageTitle.prefixedText, 2, revisionIdFrom) val page = response.query?.firstPage()!! val revisions = page.revisions revisionFrom = revisions[0] revisionTo = revisions.getOrElse(1) { revisions.first() } canGoForward = revisions.size > 1 && revisions[1].revId < page.lastrevid revisionToId = revisionTo!!.revId revisionFromId = if (revisionFrom != null) revisionFrom!!.revId else revisionTo!!.parentRevId revisionDetails.postValue(Resource.Success(Unit)) getDiffText(revisionFromId, revisionToId) } } } private fun getDiffText(oldRevisionId: Long, newRevisionId: Long) { if (diffRevisionId == newRevisionId) { return } viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> diffText.postValue(Resource.Error(throwable)) }) { withContext(Dispatchers.IO) { if (pageTitle.wikiSite.uri.authority == Uri.parse(Service.WIKIDATA_URL).authority) { // For the special case of Wikidata we return a blank Revision object, since the // Rest API in Wikidata cannot render diffs properly yet. // TODO: wait until Wikidata API returns diffs correctly singleRevisionText.postValue(Resource.Success(Revision())) } else if (oldRevisionId > 0) { diffText.postValue(Resource.Success(ServiceFactory.getCoreRest(pageTitle.wikiSite).getDiff(oldRevisionId, newRevisionId))) } else { singleRevisionText.postValue(Resource.Success(ServiceFactory.getCoreRest(pageTitle.wikiSite).getRevision(newRevisionId))) } diffRevisionId = newRevisionId } } } fun sendThanks(wikiSite: WikiSite, revisionId: Long) { viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> thankStatus.postValue(Resource.Error(throwable)) }) { withContext(Dispatchers.IO) { val token = ServiceFactory.get(wikiSite).getToken().query?.csrfToken() thankStatus.postValue(Resource.Success(ServiceFactory.get(wikiSite).postThanksToRevision(revisionId, token!!))) } } } fun watchOrUnwatch(isWatched: Boolean, expiry: WatchlistExpiry, unwatch: Boolean) { viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> watchResponse.postValue(Resource.Error(throwable)) }) { withContext(Dispatchers.IO) { if (expiry != WatchlistExpiry.NEVER) { watchlistFunnel.logAddExpiry() } else { if (isWatched) { watchlistFunnel.logRemoveArticle() } else { watchlistFunnel.logAddArticle() } } val token = ServiceFactory.get(pageTitle.wikiSite).getWatchToken().query?.watchToken() val response = ServiceFactory.get(pageTitle.wikiSite) .watch(if (unwatch) 1 else null, null, pageTitle.prefixedText, expiry.expiry, token!!) lastWatchExpiry = expiry if (watchlistExpiryChanged && unwatch) { watchlistExpiryChanged = false } if (unwatch) { watchlistFunnel.logRemoveSuccess() } else { watchlistFunnel.logAddSuccess() } watchResponse.postValue(Resource.Success(response)) } } } fun undoEdit(title: PageTitle, user: String, comment: String, revisionId: Long, revisionIdAfter: Long) { viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> undoEditResponse.postValue(Resource.Error(throwable)) }) { withContext(Dispatchers.IO) { val msgResponse = ServiceFactory.get(title.wikiSite).getMessages("undo-summary", "$revisionId|$user") val undoMessage = msgResponse.query?.allmessages?.find { it.name == "undo-summary" }?.content val summary = if (undoMessage != null) "$undoMessage $comment" else comment val token = ServiceFactory.get(title.wikiSite).getToken().query!!.csrfToken()!! val undoResponse = ServiceFactory.get(title.wikiSite).postUndoEdit(title.prefixedText, summary, null, token, revisionId, if (revisionIdAfter > 0) revisionIdAfter else null) undoEditResponse.postValue(Resource.Success(undoResponse)) } } } fun postRollback(title: PageTitle, user: String) { viewModelScope.launch(CoroutineExceptionHandler { _, throwable -> rollbackResponse.postValue(Resource.Error(throwable)) }) { withContext(Dispatchers.IO) { val rollbackToken = ServiceFactory.get(title.wikiSite).getToken("rollback").query!!.rollbackToken()!! val rollbackPostResponse = ServiceFactory.get(title.wikiSite).postRollback(title.prefixedText, null, user, rollbackToken) rollbackResponse.postValue(Resource.Success(rollbackPostResponse)) } } } class Factory(private val bundle: Bundle) : ViewModelProvider.Factory { @Suppress("unchecked_cast") override fun <T : ViewModel> create(modelClass: Class<T>): T { return ArticleEditDetailsViewModel(bundle) as T } } }
apache-2.0
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/views/SearchActionProvider.kt
1
2518
package org.wikipedia.views import android.content.Context import android.graphics.Color import android.view.LayoutInflater import android.view.View import android.view.inputmethod.EditorInfo import androidx.appcompat.widget.SearchView import androidx.core.view.ActionProvider import org.wikipedia.R import org.wikipedia.databinding.GroupSearchBinding import org.wikipedia.util.DeviceUtil.showSoftKeyboard import org.wikipedia.util.ResourceUtil.getThemedColor class SearchActionProvider(context: Context, private val searchHintString: String, private val callback: Callback) : ActionProvider(context) { interface Callback { fun onQueryTextChange(s: String) fun onQueryTextFocusChange() } private val binding = GroupSearchBinding.inflate(LayoutInflater.from(context)) override fun onCreateActionView(): View { binding.searchInput.isFocusable = true binding.searchInput.isIconified = false binding.searchInput.maxWidth = Int.MAX_VALUE binding.searchInput.inputType = EditorInfo.TYPE_CLASS_TEXT binding.searchInput.isSubmitButtonEnabled = false binding.searchInput.queryHint = searchHintString binding.searchInput.setSearchHintTextColor(getThemedColor(context, R.attr.color_group_63)) binding.searchInput.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextSubmit(s: String): Boolean { return false } override fun onQueryTextChange(s: String): Boolean { binding.searchInput.setCloseButtonVisibility(s) callback.onQueryTextChange(s) return true } }) binding.searchInput.setOnQueryTextFocusChangeListener { _: View?, isFocus: Boolean -> if (!isFocus) { callback.onQueryTextFocusChange() } } // remove focus line from search plate val searchEditPlate = binding.searchInput.findViewById<View>(androidx.appcompat.R.id.search_plate) searchEditPlate.setBackgroundColor(Color.TRANSPARENT) showSoftKeyboard(binding.searchInput) return binding.root } override fun overridesItemVisibility(): Boolean { return true } fun selectAllQueryTexts() { binding.searchInput.selectAllQueryTexts() } fun setQueryText(text: String?) { binding.searchInput.setQuery(text, false) } }
apache-2.0
stripe/stripe-android
payments-core/src/test/java/com/stripe/android/cards/RemoteCardAccountRangeSourceTest.kt
1
6445
package com.stripe.android.cards import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth.assertThat import com.stripe.android.ApiKeyFixtures import com.stripe.android.CardNumberFixtures import com.stripe.android.core.networking.AnalyticsRequest import com.stripe.android.core.networking.ApiRequest import com.stripe.android.model.AccountRange import com.stripe.android.model.BinFixtures import com.stripe.android.model.BinRange import com.stripe.android.model.CardMetadata import com.stripe.android.networking.AbsFakeStripeRepository import com.stripe.android.networking.PaymentAnalyticsRequestFactory import com.stripe.android.networking.StripeRepository import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import org.junit.runner.RunWith import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify import org.robolectric.RobolectricTestRunner import kotlin.test.Test @RunWith(RobolectricTestRunner::class) @ExperimentalCoroutinesApi internal class RemoteCardAccountRangeSourceTest { private val cardAccountRangeStore = mock<CardAccountRangeStore>() @Test fun `getAccountRange() should return expected AccountRange`() = runTest { val remoteCardAccountRangeSource = RemoteCardAccountRangeSource( FakeStripeRepository(VISA_METADATA), REQUEST_OPTIONS, cardAccountRangeStore, { }, PaymentAnalyticsRequestFactory( ApplicationProvider.getApplicationContext(), ApiKeyFixtures.FAKE_PUBLISHABLE_KEY ) ) assertThat( remoteCardAccountRangeSource.getAccountRange( CardNumberFixtures.VISA ) ).isEqualTo( AccountRange( binRange = BinRange( low = "4242424240000000", high = "4242424249999999" ), panLength = 16, brandInfo = AccountRange.BrandInfo.Visa, country = "GB" ) ) verify(cardAccountRangeStore).save( BinFixtures.VISA, AccountRangeFixtures.DEFAULT ) } @Test fun `getAccountRange() when CardMetadata is empty should return null`() = runTest { val remoteCardAccountRangeSource = RemoteCardAccountRangeSource( FakeStripeRepository(EMPTY_METADATA), REQUEST_OPTIONS, cardAccountRangeStore, { }, PaymentAnalyticsRequestFactory( ApplicationProvider.getApplicationContext(), ApiKeyFixtures.FAKE_PUBLISHABLE_KEY ) ) assertThat( remoteCardAccountRangeSource.getAccountRange( CardNumberFixtures.VISA ) ).isNull() verify(cardAccountRangeStore).save( BinFixtures.VISA, emptyList() ) } @Test fun `getAccountRange() when card number is less than required BIN length should return null`() = runTest { val repository = mock<StripeRepository>() val remoteCardAccountRangeSource = RemoteCardAccountRangeSource( repository, REQUEST_OPTIONS, cardAccountRangeStore, { }, PaymentAnalyticsRequestFactory( ApplicationProvider.getApplicationContext(), ApiKeyFixtures.FAKE_PUBLISHABLE_KEY ) ) assertThat( remoteCardAccountRangeSource.getAccountRange( CardNumber.Unvalidated("42") ) ).isNull() verify(repository, never()).getCardMetadata(any(), any()) verify(cardAccountRangeStore, never()).save(any(), any()) } @Test fun `getAccountRange() should fire missing range analytics request when response is not empty but card number does not match`() = runTest { val analyticsRequests = mutableListOf<AnalyticsRequest>() val remoteCardAccountRangeSource = RemoteCardAccountRangeSource( FakeStripeRepository( CardMetadata( bin = BinFixtures.VISA, accountRanges = listOf( AccountRange( binRange = BinRange( low = "4242420000000000", high = "4242424200000000" ), panLength = 16, brandInfo = AccountRange.BrandInfo.Visa, country = "GB" ) ) ) ), REQUEST_OPTIONS, cardAccountRangeStore, { analyticsRequests.add(it) }, PaymentAnalyticsRequestFactory( ApplicationProvider.getApplicationContext(), ApiKeyFixtures.FAKE_PUBLISHABLE_KEY ) ) remoteCardAccountRangeSource.getAccountRange( CardNumber.Unvalidated("4242424242424242") ) assertThat(analyticsRequests) .hasSize(1) assertThat(analyticsRequests.first().params["event"]) .isEqualTo("stripe_android.card_metadata_missing_range") } private class FakeStripeRepository( private val cardMetadata: CardMetadata ) : AbsFakeStripeRepository() { override suspend fun getCardMetadata( bin: Bin, options: ApiRequest.Options ) = cardMetadata } private companion object { private val REQUEST_OPTIONS = ApiRequest.Options( apiKey = ApiKeyFixtures.FAKE_PUBLISHABLE_KEY ) private val EMPTY_METADATA = CardMetadata( bin = BinFixtures.FAKE, accountRanges = emptyList() ) private val VISA_METADATA = CardMetadata( bin = BinFixtures.VISA, accountRanges = AccountRangeFixtures.DEFAULT ) } }
mit
slartus/4pdaClient-plus
core-lib/src/main/java/org/softeg/slartus/forpdaplus/core_lib/utils/AppPreferenceDelegate.kt
1
3514
package org.softeg.slartus.forpdaplus.core_lib.utils import android.content.SharedPreferences import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty @Suppress("UNCHECKED_CAST") inline fun <reified T> appPreference( preferences: SharedPreferences, key: String, defaultValue: T ): AppPreference<T> { return when (T::class) { String::class -> AppPreferenceString(preferences, key, defaultValue as String?) Boolean::class -> AppPreferenceBoolean(preferences, key, defaultValue as Boolean) Int::class -> AppPreferenceInt(preferences, key, defaultValue as Int) Float::class -> AppPreferenceFloat(preferences, key, defaultValue as Float) else -> throw Exception("appPreference given unknown class ${T::class}") } as AppPreference<T> } interface AppPreference<T> : ReadWriteProperty<Any?, T> { val value: T } data class AppPreferenceString( private val preferences: SharedPreferences, private val key: String, private val defaultValue: String? ) : AppPreference<String?> { override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String?) { preferences.edit().putString(key, value).apply() } override operator fun getValue(thisRef: Any?, property: KProperty<*>): String? { return value } override val value get() = preferences.getString(key, defaultValue) ?: defaultValue } data class AppPreferenceBoolean( private val preferences: SharedPreferences, private val key: String, private val defaultValue: Boolean ) : AppPreference<Boolean> { override operator fun getValue(thisRef: Any?, property: KProperty<*>): Boolean { return value } override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Boolean) { preferences.edit().putBoolean(key, value).apply() } override val value get() = preferences.getBoolean(key, defaultValue) } data class AppPreferenceInt( private val preferences: SharedPreferences, private val key: String, private val defaultValue: Int ) : AppPreference<Int> { override operator fun getValue(thisRef: Any?, property: KProperty<*>): Int { return value } override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) { preferences.edit().putInt(key, value).apply() } override val value get() = try { preferences.getInt(key, defaultValue) } catch (ex: java.lang.Exception) { val strValue = preferences.getString(key, defaultValue.toString()) ?: defaultValue.toString() strValue.toIntOrNull() ?: defaultValue } } data class AppPreferenceFloat( private val preferences: SharedPreferences, private val key: String, private val defaultValue: Float ) : AppPreference<Float> { override operator fun getValue(thisRef: Any?, property: KProperty<*>): Float { return value } override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Float) { preferences.edit().putFloat(key, value).apply() } override val value get() = try { preferences.getFloat(key, defaultValue) } catch (ex: java.lang.Exception) { val strValue = preferences.getString(key, defaultValue.toString()) ?: defaultValue.toString() strValue.toFloatOrNull() ?: defaultValue } }
apache-2.0
slartus/4pdaClient-plus
forum/forum-data/src/main/java/org/softeg/slartus/forpdaplus/forum/data/ForumServiceImpl.kt
1
2414
package org.softeg.slartus.forpdaplus.forum.data import com.google.gson.Gson import com.google.gson.reflect.TypeToken import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.softeg.slartus.forpdacommon.NameValuePair import org.softeg.slartus.forpdacommon.URIUtils import org.softeg.slartus.forpdaplus.core.services.AppHttpClient import ru.softeg.slartus.forum.api.ForumService import org.softeg.slartus.forpdaplus.forum.data.models.ForumItemResponse import org.softeg.slartus.forpdaplus.forum.data.models.mapToForumItemOrNull import org.softeg.slartus.hosthelper.HostHelper import ru.softeg.slartus.forum.api.ForumItem import javax.inject.Inject class ForumServiceImpl @Inject constructor(private val httpClient: AppHttpClient) : ForumService { override suspend fun getGithubForum(): List<ForumItem> = withContext(Dispatchers.IO) { val response = httpClient .performGet("https://raw.githubusercontent.com/slartus/4pdaClient-plus/master/forum_struct.json") val itemsListType = object : TypeToken<List<ForumItemResponse>>() {}.type val responseItems: List<ForumItemResponse> = Gson().fromJson(response, itemsListType) responseItems.mapNotNull { it.mapToForumItemOrNull() } } override suspend fun getSlartusForum(): List<ForumItem> = withContext(Dispatchers.IO) { val response = httpClient .performGet("http://slartus.ru/4pda/forum_struct.json") val itemsListType = object : TypeToken<List<ForumItemResponse>>() {}.type val responseItems: List<ForumItemResponse> = Gson().fromJson(response, itemsListType) responseItems.mapNotNull { it.mapToForumItemOrNull() } } override suspend fun markAsRead(forumId: String) = withContext(Dispatchers.IO) { val queryParams = mapOf("act" to "login", "CODE" to "04", "f" to forumId, "fromforum" to forumId) .map { NameValuePair(it.key, it.value) } val uri = URIUtils.createURI("http", HostHelper.host, "/forum/index.php", queryParams, "UTF-8") httpClient.performGet(uri) Unit } override fun getForumUrl(forumId: String?): String { val baseUrl = "https://${HostHelper.host}/forum/index.php" return if (forumId == null) baseUrl else "$baseUrl?showforum=$forumId" } }
apache-2.0
ivanTrogrlic/LeagueStats
app/src/main/java/com/ivantrogrlic/leaguestats/LeagueStatsApplication.kt
1
1121
package com.ivantrogrlic.leaguestats import android.app.Application import com.ivantrogrlic.leaguestats.dagger.AppComponent import com.ivantrogrlic.leaguestats.dagger.DaggerAppComponent import com.ivantrogrlic.leaguestats.web.NetComponent import com.ivantrogrlic.leaguestats.web.NetModule /** Created by ivanTrogrlic on 12/07/2017. */ class LeagueStatsApplication : Application() { companion object { lateinit var appComponent: AppComponent var netComponent: NetComponent? = null } override fun onCreate() { super.onCreate() appComponent = DaggerAppComponent .builder() .application(this) .build() appComponent.inject(this) } fun component() = appComponent fun netComponent() = netComponent fun createNetComponent(baseUrl: String): NetComponent { netComponent = component() .netComponentBuilder() .netModule(NetModule(baseUrl)) .build() return netComponent!! } fun destroyNetComponent() { netComponent = null } }
apache-2.0
exponent/exponent
android/expoview/src/main/java/versioned/host/exp/exponent/ExponentPackage.kt
2
12161
// Copyright 2015-present 650 Industries. All rights reserved. package versioned.host.exp.exponent import android.content.Context import android.os.Looper import com.facebook.react.ReactPackage import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.uimanager.ViewManager import expo.modules.adapters.react.ReactModuleRegistryProvider import expo.modules.core.interfaces.Package import expo.modules.core.interfaces.SingletonModule import expo.modules.kotlin.ModulesProvider import expo.modules.random.RandomModule import expo.modules.manifests.core.Manifest import host.exp.exponent.Constants import host.exp.exponent.analytics.EXL import host.exp.exponent.kernel.ExperienceKey // WHEN_VERSIONING_REMOVE_FROM_HERE import host.exp.exponent.kernel.ExponentKernelModuleProvider // WHEN_VERSIONING_REMOVE_TO_HERE import host.exp.exponent.kernel.KernelConstants import host.exp.exponent.utils.ScopedContext import org.json.JSONException import versioned.host.exp.exponent.modules.api.* import versioned.host.exp.exponent.modules.api.appearance.ExpoAppearanceModule import versioned.host.exp.exponent.modules.api.appearance.ExpoAppearancePackage import versioned.host.exp.exponent.modules.api.appearance.rncappearance.RNCAppearanceModule import versioned.host.exp.exponent.modules.api.cognito.RNAWSCognitoModule import versioned.host.exp.exponent.modules.api.components.datetimepicker.RNDateTimePickerPackage import versioned.host.exp.exponent.modules.api.components.gesturehandler.react.RNGestureHandlerModule import versioned.host.exp.exponent.modules.api.components.gesturehandler.react.RNGestureHandlerPackage import versioned.host.exp.exponent.modules.api.components.lottie.LottiePackage import versioned.host.exp.exponent.modules.api.components.maps.MapsPackage import versioned.host.exp.exponent.modules.api.components.maskedview.RNCMaskedViewPackage import versioned.host.exp.exponent.modules.api.components.picker.RNCPickerPackage import versioned.host.exp.exponent.modules.api.components.reactnativestripesdk.StripeSdkPackage import versioned.host.exp.exponent.modules.api.components.sharedelement.RNSharedElementModule import versioned.host.exp.exponent.modules.api.components.sharedelement.RNSharedElementPackage import versioned.host.exp.exponent.modules.api.components.slider.ReactSliderPackage import versioned.host.exp.exponent.modules.api.components.svg.SvgPackage import versioned.host.exp.exponent.modules.api.components.pagerview.PagerViewPackage import versioned.host.exp.exponent.modules.api.components.webview.RNCWebViewModule import versioned.host.exp.exponent.modules.api.components.webview.RNCWebViewPackage import versioned.host.exp.exponent.modules.api.netinfo.NetInfoModule import versioned.host.exp.exponent.modules.api.notifications.NotificationsModule import versioned.host.exp.exponent.modules.api.safeareacontext.SafeAreaContextPackage import versioned.host.exp.exponent.modules.api.screens.RNScreensPackage import versioned.host.exp.exponent.modules.api.viewshot.RNViewShotModule import versioned.host.exp.exponent.modules.internal.DevMenuModule import versioned.host.exp.exponent.modules.test.ExponentTestNativeModule import versioned.host.exp.exponent.modules.universal.ExpoModuleRegistryAdapter import versioned.host.exp.exponent.modules.universal.ScopedModuleRegistryAdapter import java.io.UnsupportedEncodingException // This is an Expo module but not a unimodule class ExponentPackage : ReactPackage { private val isKernel: Boolean private val experienceProperties: Map<String, Any?> private val manifest: Manifest private val moduleRegistryAdapter: ScopedModuleRegistryAdapter private constructor( isKernel: Boolean, experienceProperties: Map<String, Any?>, manifest: Manifest, expoPackages: List<Package>, singletonModules: List<SingletonModule>? ) { this.isKernel = isKernel this.experienceProperties = experienceProperties this.manifest = manifest moduleRegistryAdapter = createDefaultModuleRegistryAdapterForPackages(expoPackages, singletonModules) } constructor( experienceProperties: Map<String, Any?>, manifest: Manifest, expoPackages: List<Package>?, delegate: ExponentPackageDelegate?, singletonModules: List<SingletonModule> ) { isKernel = false this.experienceProperties = experienceProperties this.manifest = manifest val packages = expoPackages ?: ExperiencePackagePicker.packages(manifest) // Delegate may not be null only when the app is detached moduleRegistryAdapter = createModuleRegistryAdapter(delegate, singletonModules, packages) } private fun createModuleRegistryAdapter( delegate: ExponentPackageDelegate?, singletonModules: List<SingletonModule>, packages: List<Package> ): ScopedModuleRegistryAdapter { var registryAdapter: ScopedModuleRegistryAdapter? = null if (delegate != null) { registryAdapter = delegate.getScopedModuleRegistryAdapterForPackages(packages, singletonModules) } if (registryAdapter == null) { registryAdapter = createDefaultModuleRegistryAdapterForPackages(packages, singletonModules, ExperiencePackagePicker) } return registryAdapter } override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> { val isVerified = manifest.isVerified() ?: false val nativeModules: MutableList<NativeModule> = mutableListOf( URLHandlerModule(reactContext), ShakeModule(reactContext), KeyboardModule(reactContext) ) if (isKernel) { // WHEN_VERSIONING_REMOVE_FROM_HERE nativeModules.add((ExponentKernelModuleProvider.newInstance(reactContext) as NativeModule?)!!) // WHEN_VERSIONING_REMOVE_TO_HERE } if (!isKernel && !Constants.isStandaloneApp()) { // We need DevMenuModule only in non-home and non-standalone apps. nativeModules.add(DevMenuModule(reactContext, experienceProperties, manifest)) } if (isVerified) { try { val experienceKey = ExperienceKey.fromManifest(manifest) val scopedContext = ScopedContext(reactContext, experienceKey) nativeModules.add(NotificationsModule(reactContext, experienceKey, manifest.getStableLegacyID(), manifest.getEASProjectID())) nativeModules.add(RNViewShotModule(reactContext, scopedContext)) nativeModules.add(RandomModule(reactContext)) nativeModules.add(ExponentTestNativeModule(reactContext)) nativeModules.add(PedometerModule(reactContext)) nativeModules.add(ScreenOrientationModule(reactContext)) nativeModules.add(RNGestureHandlerModule(reactContext)) nativeModules.add(RNAWSCognitoModule(reactContext)) nativeModules.add(RNCWebViewModule(reactContext)) nativeModules.add(NetInfoModule(reactContext)) nativeModules.add(RNSharedElementModule(reactContext)) // @tsapeta: Using ExpoAppearanceModule in home app causes some issues with the dev menu, // when home's setting is set to automatic and the system theme is different // than this supported by the experience in which we opened the dev menu. if (isKernel) { nativeModules.add(RNCAppearanceModule(reactContext)) } else { nativeModules.add(ExpoAppearanceModule(reactContext)) } nativeModules.addAll(SvgPackage().createNativeModules(reactContext)) nativeModules.addAll(MapsPackage().createNativeModules(reactContext)) nativeModules.addAll(RNDateTimePickerPackage().createNativeModules(reactContext)) nativeModules.addAll(stripePackage.createNativeModules(reactContext)) // Call to create native modules has to be at the bottom -- // -- ExpoModuleRegistryAdapter uses the list of native modules // to create Bindings for internal modules. nativeModules.addAll( moduleRegistryAdapter.createNativeModules( scopedContext, experienceKey, experienceProperties, manifest, nativeModules ) ) } catch (e: JSONException) { EXL.e(TAG, e.toString()) } catch (e: UnsupportedEncodingException) { EXL.e(TAG, e.toString()) } } return nativeModules } override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> { val viewManagers = mutableListOf<ViewManager<*, *>>() // Add view manager from 3rd party library packages. addViewManagersFromPackages( reactContext, viewManagers, listOf( SvgPackage(), MapsPackage(), LottiePackage(), RNGestureHandlerPackage(), RNScreensPackage(), RNCWebViewPackage(), SafeAreaContextPackage(), RNSharedElementPackage(), RNDateTimePickerPackage(), RNCMaskedViewPackage(), RNCPickerPackage(), ReactSliderPackage(), PagerViewPackage(), ExpoAppearancePackage(), stripePackage ) ) viewManagers.addAll(moduleRegistryAdapter.createViewManagers(reactContext)) return viewManagers } private fun addViewManagersFromPackages( reactContext: ReactApplicationContext, viewManagers: MutableList<ViewManager<*, *>>, packages: List<ReactPackage> ) { for (pack in packages) { viewManagers.addAll(pack.createViewManagers(reactContext)) } } private fun createDefaultModuleRegistryAdapterForPackages( packages: List<Package>, singletonModules: List<SingletonModule>?, modulesProvider: ModulesProvider? = null ): ExpoModuleRegistryAdapter { return ExpoModuleRegistryAdapter(ReactModuleRegistryProvider(packages, singletonModules), modulesProvider) } companion object { private val TAG = ExponentPackage::class.java.simpleName private val singletonModules = mutableListOf<SingletonModule>() private val singletonModulesClasses = mutableSetOf<Class<*>>() // Need to avoid initializing 2 StripeSdkPackages private val stripePackage = StripeSdkPackage() fun kernelExponentPackage( context: Context, manifest: Manifest, expoPackages: List<Package>, initialURL: String? ): ExponentPackage { val kernelExperienceProperties = mutableMapOf( KernelConstants.LINKING_URI_KEY to "exp://", KernelConstants.IS_HEADLESS_KEY to false ).apply { if (initialURL != null) { this[KernelConstants.INTENT_URI_KEY] = initialURL } } val singletonModules = getOrCreateSingletonModules(context, manifest, expoPackages) return ExponentPackage( true, kernelExperienceProperties, manifest, expoPackages, singletonModules ) } fun getOrCreateSingletonModules( context: Context?, manifest: Manifest?, providedExpoPackages: List<Package>? ): List<SingletonModule> { if (Looper.getMainLooper() != Looper.myLooper()) { throw RuntimeException("Singleton modules must be created on the main thread.") } val expoPackages = providedExpoPackages ?: ExperiencePackagePicker.packages(manifest) for (expoPackage in expoPackages) { // For now we just accumulate more and more singleton modules, // but in fact we should only return singleton modules from the requested // unimodules. This solution also unnecessarily creates singleton modules // which are going to be deallocated in a tick, but there's no better solution // without a bigger-than-minimal refactor. In SDK32 the only singleton module // is TaskService which is safe to initialize more than once. val packageSingletonModules = expoPackage.createSingletonModules(context) for (singletonModule in packageSingletonModules) { if (!singletonModulesClasses.contains(singletonModule.javaClass)) { singletonModules.add(singletonModule) singletonModulesClasses.add(singletonModule.javaClass) } } } return singletonModules } } }
bsd-3-clause
vimeo/vimeo-networking-java
model-generator/integrations/models-input/src/main/java/com/vimeo/networking2/data/PropertyDataClass.kt
1
134
package com.vimeo.networking2.data data class PropertyDataClass(val foo: String, val bar: Long) { val baz: String = "$foo $bar" }
mit
kunalsheth/units-of-measure
demo/src/jsTest/kotlin/MainTest.kt
1
1732
package info.kunalsheth.units.sample import info.kunalsheth.units.generated.* import info.kunalsheth.units.math.* import kotlin.test.assertTrue import kotlin.test.Test class MainTest { @Test fun main() { val mass1 = 3.kilo(Gram) val mass2 = 14.Ounce val sum = mass1 + mass2 // mass1 + 3.Days // will not compile assert(sum in 7.5.Pound plusOrMinus 1.Ounce) assert(sum in 3.3.kilo(Gram)..7.5.Pound) // this works too // assert(sum in 7.4.Kilowatts..7.5.Pounds) // will not compile val ratio = 2.Foot / 1.Metre assert(ratio in 60.Percent plusOrMinus 5.Percent) assert(ratio.Percent.toInt() in 55..65) assert(1.kilo(Gram) == 1000.Gram) assert(10.milli(Metre) == 1.centi(Metre)) assert(60000.milli(Second) == 1.Minute) assert(420.Degree % 1.Turn in 60.Degree plusOrMinus 1.Degree) val speed = 65.Mile / Hour val time = 27.Minute val distance = speed * time val aBitFaster = distance / (time - 30.Second) assert(distance == time * speed) assert(distance in 29.Mile..30.Mile) assert(distance in 30.Mile..29.Mile) // this works too assert(aBitFaster in speed..(speed + 4.kilo(Metre) / Hour)) val kunalsCar = Car(200.Mile / Hour, 62.Mile / Hour / 3.1.Second) assert(kunalsCar.zeroToSixty() < 3.2.Second) val threshold = 0.001.Foot / Second / Second sequenceOf(0, 1, 4, 9, 16, 25).map { it.Foot } .derivative(::p) .derivative(::p) .zipWithNext { a, b -> a in b plusOrMinus threshold } .forEach { assert(it) } } fun assert(b: Boolean) = assertTrue(b) }
mit
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/completion/RsKeywordCompletionProvider.kt
2
2169
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.completion import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionProvider import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.editor.EditorModificationUtil import com.intellij.util.ProcessingContext import org.rust.lang.core.psi.RsFunction import org.rust.lang.core.psi.RsUnitType import org.rust.lang.core.psi.ext.ancestorStrict class RsKeywordCompletionProvider( private vararg val keywords: String ) : CompletionProvider<CompletionParameters>() { override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) { for (keyword in keywords) { var builder = LookupElementBuilder.create(keyword).bold() builder = addInsertionHandler(keyword, builder, parameters) result.addElement(builder.toKeywordElement()) } } } fun InsertionContext.addSuffix(suffix: String) { document.insertString(selectionEndOffset, suffix) EditorModificationUtil.moveCaretRelatively(editor, suffix.length) } private val ALWAYS_NEEDS_SPACE = setOf("crate", "const", "enum", "extern", "fn", "impl", "let", "mod", "mut", "static", "struct", "trait", "type", "union", "unsafe", "use", "where") private fun addInsertionHandler(keyword: String, builder: LookupElementBuilder, parameters: CompletionParameters): LookupElementBuilder { val suffix = when (keyword) { in ALWAYS_NEEDS_SPACE -> " " "return" -> { val fn = parameters.position.ancestorStrict<RsFunction>() ?: return builder val fnRetType = fn.retType val returnsUnit = fnRetType == null || fnRetType.typeReference is RsUnitType if (returnsUnit) ";" else " " } else -> return builder } return builder.withInsertHandler { ctx, _ -> ctx.addSuffix(suffix) } }
mit
glung/DroidconFr
CounterCycle/app/src/main/java/com/glung/github/counter/cycle/MainActivity.kt
1
387
package com.glung.github.counter.cycle import android.os.Bundle import android.support.v7.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) runCycle( { element -> main(this, element) }, makeActivityDriver(this) ) } }
mit
google/dokka
core/src/main/kotlin/Markdown/MarkdownProcessor.kt
2
1879
package org.jetbrains.dokka import org.intellij.markdown.IElementType import org.intellij.markdown.MarkdownElementTypes import org.intellij.markdown.ast.ASTNode import org.intellij.markdown.ast.LeafASTNode import org.intellij.markdown.ast.getTextInNode import org.intellij.markdown.flavours.commonmark.CommonMarkFlavourDescriptor import org.intellij.markdown.parser.MarkdownParser class MarkdownNode(val node: ASTNode, val parent: MarkdownNode?, val markdown: String) { val children: List<MarkdownNode> = node.children.map { MarkdownNode(it, this, markdown) } val type: IElementType get() = node.type val text: String get() = node.getTextInNode(markdown).toString() fun child(type: IElementType): MarkdownNode? = children.firstOrNull { it.type == type } val previous get() = parent?.children?.getOrNull(parent.children.indexOf(this) - 1) override fun toString(): String = StringBuilder().apply { presentTo(this) }.toString() } fun MarkdownNode.visit(action: (MarkdownNode, () -> Unit) -> Unit) { action(this) { for (child in children) { child.visit(action) } } } fun MarkdownNode.toTestString(): String { val sb = StringBuilder() var level = 0 visit { node, visitChildren -> sb.append(" ".repeat(level * 2)) node.presentTo(sb) sb.appendln() level++ visitChildren() level-- } return sb.toString() } private fun MarkdownNode.presentTo(sb: StringBuilder) { sb.append(type.toString()) sb.append(":" + text.replace("\n", "\u23CE")) } fun parseMarkdown(markdown: String): MarkdownNode { if (markdown.isEmpty()) return MarkdownNode(LeafASTNode(MarkdownElementTypes.MARKDOWN_FILE, 0, 0), null, markdown) return MarkdownNode(MarkdownParser(CommonMarkFlavourDescriptor()).buildMarkdownTreeFromString(markdown), null, markdown) }
apache-2.0
androidx/androidx
buildSrc/private/src/main/kotlin/androidx/build/transform/ConfigureAarAsJar.kt
3
2291
/* * 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.build.transform import com.android.build.api.attributes.BuildTypeAttr import org.gradle.api.Project import org.gradle.api.attributes.Attribute import org.gradle.api.attributes.Usage /** * Creates `testAarAsJar` configuration that can be used for JVM tests that need to Android library * classes on the classpath. */ fun configureAarAsJarForConfiguration(project: Project, configurationName: String) { val testAarsAsJars = project.configurations.create("${configurationName}AarAsJar") { it.isTransitive = false it.isCanBeConsumed = false it.isCanBeResolved = true it.attributes.attribute( BuildTypeAttr.ATTRIBUTE, project.objects.named(BuildTypeAttr::class.java, "release") ) it.attributes.attribute( Usage.USAGE_ATTRIBUTE, project.objects.named(Usage::class.java, Usage.JAVA_API) ) } val artifactType = Attribute.of("artifactType", String::class.java) project.dependencies.registerTransform(IdentityTransform::class.java) { spec -> spec.from.attribute(artifactType, "jar") spec.to.attribute(artifactType, "aarAsJar") } project.dependencies.registerTransform(ExtractClassesJarTransform::class.java) { spec -> spec.from.attribute(artifactType, "aar") spec.to.attribute(artifactType, "aarAsJar") } val aarAsJar = testAarsAsJars.incoming.artifactView { viewConfiguration -> viewConfiguration.attributes.attribute(artifactType, "aarAsJar") }.files project.configurations.getByName(configurationName).dependencies.add( project.dependencies.create(aarAsJar) ) }
apache-2.0
androidx/androidx
room/room-compiler/src/main/kotlin/androidx/room/writer/DatabaseWriter.kt
3
20751
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.writer import androidx.room.compiler.codegen.CodeLanguage import androidx.room.compiler.codegen.VisibilityModifier import androidx.room.compiler.codegen.XCodeBlock import androidx.room.compiler.codegen.XCodeBlock.Builder.Companion.addLocalVal import androidx.room.compiler.codegen.XFunSpec import androidx.room.compiler.codegen.XPropertySpec import androidx.room.compiler.codegen.XPropertySpec.Companion.apply import androidx.room.compiler.codegen.XTypeName import androidx.room.compiler.codegen.XTypeSpec import androidx.room.compiler.codegen.XTypeSpec.Builder.Companion.addOriginatingElement import androidx.room.ext.AndroidTypeNames import androidx.room.ext.CommonTypeNames import androidx.room.ext.KotlinTypeNames import androidx.room.ext.RoomTypeNames import androidx.room.ext.SupportDbTypeNames import androidx.room.ext.decapitalize import androidx.room.ext.stripNonJava import androidx.room.solver.CodeGenScope import androidx.room.vo.DaoMethod import androidx.room.vo.Database import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import java.util.Locale import javax.lang.model.element.Modifier /** * Writes implementation of classes that were annotated with @Database. */ class DatabaseWriter( val database: Database, codeLanguage: CodeLanguage ) : TypeWriter(codeLanguage) { override fun createTypeSpecBuilder(): XTypeSpec.Builder { return XTypeSpec.classBuilder(codeLanguage, database.implTypeName).apply { addOriginatingElement(database.element) superclass(database.typeName) setVisibility(VisibilityModifier.PUBLIC) addFunction(createCreateOpenHelper()) addFunction(createCreateInvalidationTracker()) addFunction(createClearAllTables()) addFunction(createCreateTypeConvertersMap()) addFunction(createCreateAutoMigrationSpecsSet()) addFunction(getAutoMigrations()) addDaoImpls(this) } } private fun createCreateTypeConvertersMap(): XFunSpec { val scope = CodeGenScope(this) val classOfAnyTypeName = CommonTypeNames.JAVA_CLASS.parametrizedBy( XTypeName.getProducerExtendsName(KotlinTypeNames.ANY) ) val typeConvertersTypeName = CommonTypeNames.HASH_MAP.parametrizedBy( classOfAnyTypeName, CommonTypeNames.LIST.parametrizedBy(classOfAnyTypeName) ) val body = XCodeBlock.builder(codeLanguage).apply { val typeConvertersVar = scope.getTmpVar("_typeConvertersMap") addLocalVariable( name = typeConvertersVar, typeName = typeConvertersTypeName, assignExpr = XCodeBlock.ofNewInstance(codeLanguage, typeConvertersTypeName) ) database.daoMethods.forEach { addStatement( "%L.put(%L, %T.%L())", typeConvertersVar, XCodeBlock.ofJavaClassLiteral(codeLanguage, it.dao.typeName), it.dao.implTypeName, DaoWriter.GET_LIST_OF_TYPE_CONVERTERS_METHOD ) } addStatement("return %L", typeConvertersVar) }.build() return XFunSpec.builder( language = codeLanguage, name = "getRequiredTypeConverters", visibility = VisibilityModifier.PROTECTED, isOverride = true ).apply { returns( CommonTypeNames.MAP.parametrizedBy( classOfAnyTypeName, CommonTypeNames.LIST.parametrizedBy(classOfAnyTypeName) ) ) addCode(body) }.build() } private fun createCreateAutoMigrationSpecsSet(): XFunSpec { val scope = CodeGenScope(this) val classOfAutoMigrationSpecTypeName = CommonTypeNames.JAVA_CLASS.parametrizedBy( XTypeName.getProducerExtendsName(RoomTypeNames.AUTO_MIGRATION_SPEC) ) val autoMigrationSpecsTypeName = CommonTypeNames.HASH_SET.parametrizedBy(classOfAutoMigrationSpecTypeName) val body = XCodeBlock.builder(codeLanguage).apply { val autoMigrationSpecsVar = scope.getTmpVar("_autoMigrationSpecsSet") addLocalVariable( name = autoMigrationSpecsVar, typeName = autoMigrationSpecsTypeName, assignExpr = XCodeBlock.ofNewInstance(codeLanguage, autoMigrationSpecsTypeName) ) database.autoMigrations.filter { it.isSpecProvided }.map { autoMigration -> val specClassName = checkNotNull(autoMigration.specClassName) addStatement( "%L.add(%L)", autoMigrationSpecsVar, XCodeBlock.ofJavaClassLiteral(codeLanguage, specClassName) ) } addStatement("return %L", autoMigrationSpecsVar) }.build() return XFunSpec.builder( language = codeLanguage, name = "getRequiredAutoMigrationSpecs", visibility = VisibilityModifier.PUBLIC, isOverride = true, ).apply { returns(CommonTypeNames.SET.parametrizedBy(classOfAutoMigrationSpecTypeName)) addCode(body) }.build() } private fun createClearAllTables(): XFunSpec { val scope = CodeGenScope(this) val body = XCodeBlock.builder(codeLanguage).apply { addStatement("super.assertNotMainThread()") val dbVar = scope.getTmpVar("_db") addLocalVal( dbVar, SupportDbTypeNames.DB, when (language) { CodeLanguage.JAVA -> "super.getOpenHelper().getWritableDatabase()" CodeLanguage.KOTLIN -> "super.openHelper.writableDatabase" } ) val deferVar = scope.getTmpVar("_supportsDeferForeignKeys") if (database.enableForeignKeys) { addLocalVal( deferVar, XTypeName.PRIMITIVE_BOOLEAN, "%L.VERSION.SDK_INT >= %L.VERSION_CODES.LOLLIPOP", AndroidTypeNames.BUILD, AndroidTypeNames.BUILD ) } beginControlFlow("try").apply { if (database.enableForeignKeys) { beginControlFlow("if (!%L)", deferVar).apply { addStatement("%L.execSQL(%S)", dbVar, "PRAGMA foreign_keys = FALSE") } endControlFlow() } addStatement("super.beginTransaction()") if (database.enableForeignKeys) { beginControlFlow("if (%L)", deferVar).apply { addStatement("%L.execSQL(%S)", dbVar, "PRAGMA defer_foreign_keys = TRUE") } endControlFlow() } database.entities.sortedWith(EntityDeleteComparator()).forEach { addStatement("%L.execSQL(%S)", dbVar, "DELETE FROM `${it.tableName}`") } addStatement("super.setTransactionSuccessful()") } nextControlFlow("finally").apply { addStatement("super.endTransaction()") if (database.enableForeignKeys) { beginControlFlow("if (!%L)", deferVar).apply { addStatement("%L.execSQL(%S)", dbVar, "PRAGMA foreign_keys = TRUE") } endControlFlow() } addStatement("%L.query(%S).close()", dbVar, "PRAGMA wal_checkpoint(FULL)") beginControlFlow("if (!%L.inTransaction())", dbVar).apply { addStatement("%L.execSQL(%S)", dbVar, "VACUUM") } endControlFlow() } endControlFlow() }.build() return XFunSpec.builder( language = codeLanguage, name = "clearAllTables", visibility = VisibilityModifier.PUBLIC, isOverride = true ).apply { addCode(body) }.build() } private fun createCreateInvalidationTracker(): XFunSpec { val scope = CodeGenScope(this) val body = XCodeBlock.builder(codeLanguage).apply { val shadowTablesVar = "_shadowTablesMap" val shadowTablesTypeName = CommonTypeNames.HASH_MAP.parametrizedBy( CommonTypeNames.STRING, CommonTypeNames.STRING ) val tableNames = database.entities.joinToString(",") { "\"${it.tableName}\"" } val shadowTableNames = database.entities.filter { it.shadowTableName != null }.map { it.tableName to it.shadowTableName } addLocalVariable( name = shadowTablesVar, typeName = shadowTablesTypeName, assignExpr = XCodeBlock.ofNewInstance( codeLanguage, shadowTablesTypeName, "%L", shadowTableNames.size ) ) shadowTableNames.forEach { (tableName, shadowTableName) -> addStatement("%L.put(%S, %S)", shadowTablesVar, tableName, shadowTableName) } val viewTablesVar = scope.getTmpVar("_viewTables") val tablesType = CommonTypeNames.HASH_SET.parametrizedBy(CommonTypeNames.STRING) val viewTablesType = CommonTypeNames.HASH_MAP.parametrizedBy( CommonTypeNames.STRING, CommonTypeNames.SET.parametrizedBy(CommonTypeNames.STRING) ) addLocalVariable( name = viewTablesVar, typeName = viewTablesType, assignExpr = XCodeBlock.ofNewInstance( codeLanguage, viewTablesType, "%L", database.views.size ) ) for (view in database.views) { val tablesVar = scope.getTmpVar("_tables") addLocalVariable( name = tablesVar, typeName = tablesType, assignExpr = XCodeBlock.ofNewInstance( codeLanguage, tablesType, "%L", view.tables.size ) ) for (table in view.tables) { addStatement("%L.add(%S)", tablesVar, table) } addStatement( "%L.put(%S, %L)", viewTablesVar, view.viewName.lowercase(Locale.US), tablesVar ) } addStatement( "return %L", XCodeBlock.ofNewInstance( codeLanguage, RoomTypeNames.INVALIDATION_TRACKER, "this, %L, %L, %L", shadowTablesVar, viewTablesVar, tableNames ) ) }.build() return XFunSpec.builder( language = codeLanguage, name = "createInvalidationTracker", visibility = VisibilityModifier.PROTECTED, isOverride = true ).apply { returns(RoomTypeNames.INVALIDATION_TRACKER) addCode(body) }.build() } private fun addDaoImpls(builder: XTypeSpec.Builder) { val scope = CodeGenScope(this) database.daoMethods.forEach { method -> val name = method.dao.typeName.simpleNames.first() .decapitalize(Locale.US) .stripNonJava() val privateDaoProperty = XPropertySpec.builder( language = codeLanguage, name = scope.getTmpVar("_$name"), typeName = if (codeLanguage == CodeLanguage.KOTLIN) { KotlinTypeNames.LAZY.parametrizedBy(method.dao.typeName) } else { method.dao.typeName }, visibility = VisibilityModifier.PRIVATE, isMutable = codeLanguage == CodeLanguage.JAVA ).apply { // For Kotlin we rely on kotlin.Lazy while for Java we'll memoize the dao impl in // the getter. if (language == CodeLanguage.KOTLIN) { initializer( XCodeBlock.of( language, "lazy { %L }", XCodeBlock.ofNewInstance(language, method.dao.implTypeName, "this") ) ) } }.apply( javaFieldBuilder = { // The volatile modifier is needed since in Java the memoization is generated. addModifiers(Modifier.VOLATILE) }, kotlinPropertyBuilder = { } ).build() builder.addProperty(privateDaoProperty) val overrideProperty = codeLanguage == CodeLanguage.KOTLIN && method.element.isKotlinPropertyMethod() if (overrideProperty) { builder.addProperty(createDaoProperty(method, privateDaoProperty)) } else { builder.addFunction(createDaoGetter(method, privateDaoProperty)) } } } private fun createDaoGetter(method: DaoMethod, daoProperty: XPropertySpec): XFunSpec { val body = XCodeBlock.builder(codeLanguage).apply { // For Java we implement the memoization logic in the Dao getter, meanwhile for Kotlin // we rely on kotlin.Lazy to the getter just delegates to it. when (codeLanguage) { CodeLanguage.JAVA -> { beginControlFlow("if (%N != null)", daoProperty).apply { addStatement("return %N", daoProperty) } nextControlFlow("else").apply { beginControlFlow("synchronized(this)").apply { beginControlFlow("if(%N == null)", daoProperty).apply { addStatement( "%N = %L", daoProperty, XCodeBlock.ofNewInstance( language, method.dao.implTypeName, "this" ) ) } endControlFlow() addStatement("return %N", daoProperty) } endControlFlow() } endControlFlow() } CodeLanguage.KOTLIN -> { addStatement("return %N.value", daoProperty) } } } return XFunSpec.overridingBuilder( language = codeLanguage, element = method.element, owner = database.element.type ).apply { addCode(body.build()) }.build() } private fun createDaoProperty(method: DaoMethod, daoProperty: XPropertySpec): XPropertySpec { // TODO(b/257967987): This has a few flaws that need to be fixed. return XPropertySpec.builder( language = codeLanguage, name = method.element.name.drop(3).replaceFirstChar { it.lowercase(Locale.US) }, typeName = method.dao.typeName, visibility = when { method.element.isPublic() -> VisibilityModifier.PUBLIC method.element.isProtected() -> VisibilityModifier.PROTECTED else -> VisibilityModifier.PUBLIC // Might be internal... ? } ).apply( javaFieldBuilder = { error("Overriding a property in Java is impossible!") }, kotlinPropertyBuilder = { addModifiers(KModifier.OVERRIDE) getter( FunSpec.getterBuilder() .addStatement("return %L.value", daoProperty.name) .build() ) } ).build() } private fun createCreateOpenHelper(): XFunSpec { val scope = CodeGenScope(this) val configParamName = "config" val body = XCodeBlock.builder(codeLanguage).apply { val openHelperVar = scope.getTmpVar("_helper") val openHelperCode = scope.fork() SQLiteOpenHelperWriter(database) .write(openHelperVar, configParamName, openHelperCode) add(openHelperCode.generate()) addStatement("return %L", openHelperVar) }.build() return XFunSpec.builder( language = codeLanguage, name = "createOpenHelper", visibility = VisibilityModifier.PROTECTED, isOverride = true, ).apply { returns(SupportDbTypeNames.SQLITE_OPEN_HELPER) addParameter(RoomTypeNames.ROOM_DB_CONFIG, configParamName) addCode(body) }.build() } private fun getAutoMigrations(): XFunSpec { val scope = CodeGenScope(this) val classOfAutoMigrationSpecTypeName = CommonTypeNames.JAVA_CLASS.parametrizedBy( XTypeName.getProducerExtendsName(RoomTypeNames.AUTO_MIGRATION_SPEC) ) val autoMigrationsListTypeName = CommonTypeNames.ARRAY_LIST.parametrizedBy(RoomTypeNames.MIGRATION) val specsMapParamName = "autoMigrationSpecs" val body = XCodeBlock.builder(codeLanguage).apply { val listVar = scope.getTmpVar("_autoMigrations") addLocalVariable( name = listVar, typeName = CommonTypeNames.LIST.parametrizedBy(RoomTypeNames.MIGRATION), assignExpr = XCodeBlock.ofNewInstance(codeLanguage, autoMigrationsListTypeName) ) database.autoMigrations.forEach { autoMigrationResult -> val implTypeName = autoMigrationResult.getImplTypeName(database.typeName) val newInstanceCode = if (autoMigrationResult.isSpecProvided) { val specClassName = checkNotNull(autoMigrationResult.specClassName) // For Kotlin use getValue() as the Map's values are never null. val getFunction = when (language) { CodeLanguage.JAVA -> "get" CodeLanguage.KOTLIN -> "getValue" } XCodeBlock.ofNewInstance( language, implTypeName, "%L.%L(%L)", specsMapParamName, getFunction, XCodeBlock.ofJavaClassLiteral(language, specClassName) ) } else { XCodeBlock.ofNewInstance(language, implTypeName) } addStatement("%L.add(%L)", listVar, newInstanceCode) } addStatement("return %L", listVar) }.build() return XFunSpec.builder( language = codeLanguage, name = "getAutoMigrations", visibility = VisibilityModifier.PUBLIC, isOverride = true, ).apply { returns(CommonTypeNames.LIST.parametrizedBy(RoomTypeNames.MIGRATION)) addParameter( CommonTypeNames.MAP.parametrizedBy( classOfAutoMigrationSpecTypeName, RoomTypeNames.AUTO_MIGRATION_SPEC, ), specsMapParamName ) addCode(body) }.build() } }
apache-2.0
noemus/kotlin-eclipse
kotlin-eclipse-ui-test/testData/wordSelection/selectPrevious/Classes/3.kt
1
155
class A { fun none() { } } <selection>class B { fun meaningless() { println("You're not supposed to be here") } } class C { <caret> }</selection>
apache-2.0
noemus/kotlin-eclipse
kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/selection/handlers/KotlinBlockSelectionHandler.kt
1
2445
package org.jetbrains.kotlin.ui.editors.selection.handlers import org.jetbrains.kotlin.psi.KtWhenExpression import org.jetbrains.kotlin.psi.KtBlockExpression import com.intellij.psi.PsiElement import org.jetbrains.kotlin.lexer.KtTokens import com.intellij.psi.PsiWhiteSpace import com.intellij.openapi.util.TextRange public class KotlinBlockSelectionHandler: KotlinDefaultSelectionHandler() { override fun canSelect(enclosingElement: PsiElement) = enclosingElement is KtBlockExpression || enclosingElement is KtWhenExpression override fun selectEnclosing(enclosingElement: PsiElement, selectedRange: TextRange): TextRange { val elementStart = findBlockContentStart(enclosingElement); val elementEnd = findBlockContentEnd(enclosingElement) if (elementStart >= elementEnd) { return enclosingElement.getTextRange() } val resultRange = TextRange(elementStart, elementEnd) if (resultRange == selectedRange || selectedRange !in resultRange) { return enclosingElement.getTextRange() } return resultRange; } override fun selectPrevious(enclosingElement: PsiElement, selectionCandidate: PsiElement, selectedRange: TextRange): TextRange { if (selectionCandidate.getNode().getElementType() == KtTokens.LBRACE) { return selectEnclosing(enclosingElement, selectedRange) } return selectionWithElementAppendedToBeginning(selectedRange, selectionCandidate) } override fun selectNext(enclosingElement: PsiElement, selectionCandidate: PsiElement, selectedRange: TextRange): TextRange { if (selectionCandidate.getNode().getElementType() == KtTokens.RBRACE) { return selectEnclosing(enclosingElement, selectedRange) } return selectionWithElementAppendedToEnd(selectedRange, selectionCandidate) } private fun findBlockContentStart(block: PsiElement): Int { val element = block.allChildren .dropWhile { it.getNode().getElementType() != KtTokens.LBRACE } .drop(1) .dropWhile { it is PsiWhiteSpace } .firstOrNull() ?: block return element.getTextRange().getStartOffset() } private fun findBlockContentEnd(block: PsiElement): Int { val element = block.allChildren .toList() .reversed() .asSequence() .dropWhile { it.getNode().getElementType() != KtTokens.RBRACE } .drop(1) .dropWhile { it is PsiWhiteSpace } .firstOrNull() ?: block return element.getTextRange().getEndOffset() } }
apache-2.0
codebutler/odyssey
retrograde-app-shared/src/main/java/com/codebutler/retrograde/lib/storage/StorageProvider.kt
1
1569
/* * GameLibraryProvider.kt * * Copyright (C) 2017 Retrograde Project * * 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.codebutler.retrograde.lib.storage import androidx.leanback.preference.LeanbackPreferenceFragment import com.codebutler.retrograde.lib.library.db.entity.Game import com.codebutler.retrograde.lib.library.metadata.GameMetadataProvider import com.gojuno.koptional.Optional import io.reactivex.Completable import io.reactivex.Single import java.io.File interface StorageProvider { val id: String val name: String val uriSchemes: List<String> val prefsFragmentClass: Class<out LeanbackPreferenceFragment>? val metadataProvider: GameMetadataProvider val enabledByDefault: Boolean fun listFiles(): Single<Iterable<StorageFile>> fun getGameRom(game: Game): Single<File> fun getGameSave(game: Game): Single<Optional<ByteArray>> fun setGameSave(game: Game, data: ByteArray): Completable }
gpl-3.0
pthomain/SharedPreferenceStore
mumbo/src/test/java/uk/co/glass_software/android/shared_preferences/test/TestUtils.kt
2
5230
/* * Copyright (C) 2017 Glass Software Ltd * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package uk.co.glass_software.android.shared_preferences.test import com.nhaarman.mockitokotlin2.atLeastOnce import com.nhaarman.mockitokotlin2.never import com.nhaarman.mockitokotlin2.verify import junit.framework.TestCase.* import org.junit.Assert.assertArrayEquals import org.mockito.internal.verification.VerificationModeFactory fun <E> expectException(exceptionType: Class<E>, message: String, action: () -> Unit, checkCause: Boolean = false) { try { action() } catch (e: Exception) { val toCheck = if (checkCause) e.cause else e if (toCheck != null && exceptionType == toCheck.javaClass) { assertEquals("The exception did not have the right message", message, toCheck.message ) return } else { fail("Expected exception was not caught: $exceptionType, another one was caught instead $toCheck") } } fail("Expected exception was not caught: $exceptionType") } fun assertTrueWithContext(assumption: Boolean, description: String, context: String? = null) = assertTrue(withContext(description, context), assumption) fun assertFalseWithContext(assumption: Boolean, description: String, context: String? = null) = assertFalse(withContext(description, context), assumption) fun <T> assertEqualsWithContext(t1: T, t2: T, description: String, context: String? = null) { val withContext = withContext(description, context) when { t1 is Array<*> && t2 is Array<*> -> assertArrayEquals(withContext, t1, t2) t1 is ByteArray && t2 is ByteArray -> assertByteArrayEqualsWithContext(t1, t2, context) else -> assertEquals(withContext, t1, t2) } } fun <T> assertNullWithContext(value: T?, description: String, context: String? = null) = assertNull(withContext(description, context), value) fun <T> assertNotNullWithContext(value: T?, description: String, context: String? = null) = assertNotNull(withContext(description, context), value) fun failWithContext(description: String, context: String? = null) { fail(withContext(description, context)) } fun withContext(description: String, context: String? = null) = if (context == null) description else "\n$context\n=> $description" internal fun <T> verifyWithContext(target: T, context: String? = null) = verify( target, VerificationModeFactory.description( atLeastOnce(), "\n$context" ) ) internal fun <T> verifyNeverWithContext(target: T, context: String? = null) = verify( target, VerificationModeFactory.description( never(), "\n$context" ) ) fun assertByteArrayEqualsWithContext(expected: ByteArray?, other: ByteArray?, context: String? = null) { when { expected == null -> assertNullWithContext( other, "Byte array should be null", context ) other != null && other.size == expected.size -> { other.forEachIndexed { index, byte -> if (expected[index] != byte) { assertEqualsWithContext( expected[index], byte, "Byte didn't match at index $index", context ) } } } else -> failWithContext( "Byte array had the wrong size", context ) } } inline fun trueFalseSequence(action: (Boolean) -> Unit) { sequenceOf(true, false).forEach(action) }
apache-2.0
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/opengles/templates/NV_gpu_shader5.kt
1
9560
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengles.templates import org.lwjgl.generator.* import org.lwjgl.opengles.* val NV_gpu_shader5 = "NVGPUShader5".nativeClassGLES("NV_gpu_shader5", postfix = NV) { documentation = """ Native bindings to the $registryLink extension. This extension provides a set of new features to the OpenGL ES Shading Language and related APIs to support capabilities of new GPUs. Shaders using the new functionality provided by this extension should enable this functionality via the construct ${codeBlock(""" \\#extension GL_NV_gpu_shader5 : require (or enable)""")} This extension was developed concurrently with the OES_gpu_shader5 extension, and provides a superset of the features provided there. The features common to both extensions are documented in the OES_gpu_shader5 specification; this document describes only the addition language features not available via OES_gpu_shader5. A shader that enables this extension via an \\#extension directive also implicitly enables the common capabilities provided by OES_gpu_shader5. In addition to the capabilities of OES_gpu_shader5, this extension provides a variety of new features for all shader types, including: ${ul( """ support for a full set of 8-, 16-, 32-, and 64-bit scalar and vector data types, including uniform API, uniform buffer object, and shader input and output support; """, """ the ability to aggregate samplers into arrays, index these arrays with arbitrary expressions, and not require that non-constant indices be uniform across all shader invocations; """, "new built-in functions to pack and unpack 64-bit integer types into a two-component 32-bit integer vector;", "new built-in functions to pack and unpack 32-bit unsigned integer types into a two-component 16-bit floating-point vector;", "new built-in functions to convert double-precision floating-point values to or from their 64-bit integer bit encodings;", "new built-in functions to compute the composite of a set of boolean conditions a group of shader threads;", "vector relational functions supporting comparisons of vectors of 8-, 16-, and 64-bit integer types or 16-bit floating-point types; and", """ extending texel offset support to allow loading texel offsets from regular integer operands computed at run-time, except for lookups with gradients (textureGrad*). """ )} This extension also provides additional support for processing patch primitives (introduced by OES_tessellation_shader). OES_tessellation_shader requires the use of a tessellation evaluation shader when processing patches, which means that patches will never survive past the tessellation pipeline stage. This extension lifts that restriction, and allows patches to proceed further in the pipeline and be used ${ul( "as input to a geometry shader, using a new \"patches\" layout qualifier;", "as input to transform feedback;", "by fixed-function rasterization stages, in which case the patches are drawn as independent points." )} Additionally, it allows geometry shaders to read per-patch attributes written by a tessellation control shader using input variables declared with "patch in". Requires ${GLES31.core} and GLSL ES 3.10. """ IntConstant( "Returned by the {@code type} parameter of GetActiveAttrib, GetActiveUniform, and GetTransformFeedbackVarying.", "INT64_NV"..0x140E, "UNSIGNED_INT64_NV"..0x140F, "INT8_NV"..0x8FE0, "INT8_VEC2_NV"..0x8FE1, "INT8_VEC3_NV"..0x8FE2, "INT8_VEC4_NV"..0x8FE3, "INT16_NV"..0x8FE4, "INT16_VEC2_NV"..0x8FE5, "INT16_VEC3_NV"..0x8FE6, "INT16_VEC4_NV"..0x8FE7, "INT64_VEC2_NV"..0x8FE9, "INT64_VEC3_NV"..0x8FEA, "INT64_VEC4_NV"..0x8FEB, "UNSIGNED_INT8_NV"..0x8FEC, "UNSIGNED_INT8_VEC2_NV"..0x8FED, "UNSIGNED_INT8_VEC3_NV"..0x8FEE, "UNSIGNED_INT8_VEC4_NV"..0x8FEF, "UNSIGNED_INT16_NV"..0x8FF0, "UNSIGNED_INT16_VEC2_NV"..0x8FF1, "UNSIGNED_INT16_VEC3_NV"..0x8FF2, "UNSIGNED_INT16_VEC4_NV"..0x8FF3, "UNSIGNED_INT64_VEC2_NV"..0x8FF5, "UNSIGNED_INT64_VEC3_NV"..0x8FF6, "UNSIGNED_INT64_VEC4_NV"..0x8FF7, "FLOAT16_NV"..0x8FF8, "FLOAT16_VEC2_NV"..0x8FF9, "FLOAT16_VEC3_NV"..0x8FFA, "FLOAT16_VEC4_NV"..0x8FFB ) void( "Uniform1i64NV", "", GLint.IN("location", ""), GLint64.IN("x", "") ) void( "Uniform2i64NV", "", GLint.IN("location", ""), GLint64.IN("x", ""), GLint64.IN("y", "") ) void( "Uniform3i64NV", "", GLint.IN("location", ""), GLint64.IN("x", ""), GLint64.IN("y", ""), GLint64.IN("z", "") ) void( "Uniform4i64NV", "", GLint.IN("location", ""), GLint64.IN("x", ""), GLint64.IN("y", ""), GLint64.IN("z", ""), GLint64.IN("w", "") ) void( "Uniform1i64vNV", "", GLint.IN("location", ""), AutoSize("value")..GLsizei.IN("count", ""), const..GLint64_p.IN("value", "") ) void( "Uniform2i64vNV", "", GLint.IN("location", ""), AutoSize(2, "value")..GLsizei.IN("count", ""), const..GLint64_p.IN("value", "") ) void( "Uniform3i64vNV", "", GLint.IN("location", ""), AutoSize(3, "value")..GLsizei.IN("count", ""), const..GLint64_p.IN("value", "") ) void( "Uniform4i64vNV", "", GLint.IN("location", ""), AutoSize(4, "value")..GLsizei.IN("count", ""), const..GLint64_p.IN("value", "") ) void( "Uniform1ui64NV", "", GLint.IN("location", ""), GLuint64.IN("x", "") ) void( "Uniform2ui64NV", "", GLint.IN("location", ""), GLuint64.IN("x", ""), GLuint64.IN("y", "") ) void( "Uniform3ui64NV", "", GLint.IN("location", ""), GLuint64.IN("x", ""), GLuint64.IN("y", ""), GLuint64.IN("z", "") ) void( "Uniform4ui64NV", "", GLint.IN("location", ""), GLuint64.IN("x", ""), GLuint64.IN("y", ""), GLuint64.IN("z", ""), GLuint64.IN("w", "") ) void( "Uniform1ui64vNV", "", GLint.IN("location", ""), AutoSize("value")..GLsizei.IN("count", ""), const..GLuint64_p.IN("value", "") ) void( "Uniform2ui64vNV", "", GLint.IN("location", ""), AutoSize(2, "value")..GLsizei.IN("count", ""), GLuint64_p.IN("value", "") ) void( "Uniform3ui64vNV", "", GLint.IN("location", ""), AutoSize(3, "value")..GLsizei.IN("count", ""), const..GLuint64_p.IN("value", "") ) void( "Uniform4ui64vNV", "", GLint.IN("location", ""), AutoSize(4, "value")..GLsizei.IN("count", ""), const..GLuint64_p.IN("value", "") ) void( "GetUniformi64vNV", "", GLuint.IN("program", ""), GLint.IN("location", ""), Check(1)..ReturnParam..GLint64_p.OUT("params", "") ) void( "GetUniformui64vNV", "", GLuint.IN("program", ""), GLint.IN("location", ""), Check(1)..ReturnParam..GLint64_p.OUT("params", "") ) void( "ProgramUniform1i64NV", "", GLuint.IN("program", ""), GLint.IN("location", ""), GLint64.IN("x", "") ) void( "ProgramUniform2i64NV", "", GLuint.IN("program", ""), GLint.IN("location", ""), GLint64.IN("x", ""), GLint64.IN("y", "") ) void( "ProgramUniform3i64NV", "", GLuint.IN("program", ""), GLint.IN("location", ""), GLint64.IN("x", ""), GLint64.IN("y", ""), GLint64.IN("z", "") ) void( "ProgramUniform4i64NV", "", GLuint.IN("program", ""), GLint.IN("location", ""), GLint64.IN("x", ""), GLint64.IN("y", ""), GLint64.IN("z", ""), GLint64.IN("w", "") ) void( "ProgramUniform1i64vNV", "", GLuint.IN("program", ""), GLint.IN("location", ""), AutoSize("value")..GLsizei.IN("count", ""), const..GLint64_p.IN("value", "") ) void( "ProgramUniform2i64vNV", "", GLuint.IN("program", ""), GLint.IN("location", ""), AutoSize(2, "value")..GLsizei.IN("count", ""), const..GLint64_p.IN("value", "") ) void( "ProgramUniform3i64vNV", "", GLuint.IN("program", ""), GLint.IN("location", ""), AutoSize(3, "value")..GLsizei.IN("count", ""), const..GLint64_p.IN("value", "") ) void( "ProgramUniform4i64vNV", "", GLuint.IN("program", ""), GLint.IN("location", ""), AutoSize(4, "value")..GLsizei.IN("count", ""), const..GLint64_p.IN("value", "") ) void( "ProgramUniform1ui64NV", "", GLuint.IN("program", ""), GLint.IN("location", ""), GLuint64.IN("x", "") ) void( "ProgramUniform2ui64NV", "", GLuint.IN("program", ""), GLint.IN("location", ""), GLuint64.IN("x", ""), GLuint64.IN("y", "") ) void( "ProgramUniform3ui64NV", "", GLuint.IN("program", ""), GLint.IN("location", ""), GLuint64.IN("x", ""), GLuint64.IN("y", ""), GLuint64.IN("z", "") ) void( "ProgramUniform4ui64NV", "", GLuint.IN("program", ""), GLint.IN("location", ""), GLuint64.IN("x", ""), GLuint64.IN("y", ""), GLuint64.IN("z", ""), GLuint64.IN("w", "") ) void( "ProgramUniform1ui64vNV", "", GLuint.IN("program", ""), GLint.IN("location", ""), AutoSize("value")..GLsizei.IN("count", ""), const..GLuint64_p.IN("value", "") ) void( "ProgramUniform2ui64vNV", "", GLuint.IN("program", ""), GLint.IN("location", ""), AutoSize(2, "value")..GLsizei.IN("count", ""), const..GLuint64_p.IN("value", "") ) void( "ProgramUniform3ui64vNV", "", GLuint.IN("program", ""), GLint.IN("location", ""), AutoSize(3, "value")..GLsizei.IN("count", ""), const..GLuint64_p.IN("value", "") ) void( "ProgramUniform4ui64vNV", "", GLuint.IN("program", ""), GLint.IN("location", ""), AutoSize(4, "value")..GLsizei.IN("count", ""), const..GLuint64_p.IN("value", "") ) }
bsd-3-clause
noemus/kotlin-eclipse
kotlin-eclipse-ui-test/testData/wordSelection/selectPrevious/TypeParameters/1.kt
1
54
fun <A, <selection>B, <caret>C</selection>> foo() { }
apache-2.0
jooby-project/jooby
tests/src/test/kotlin/i2598/Issue2598.kt
1
862
/* * Jooby https://jooby.io * Apache License Version 2.0 https://jooby.io/LICENSE.txt * Copyright 2014 Edgar Espina */ package i2598 import io.jooby.Context import io.jooby.internal.RouteAnalyzer import io.jooby.internal.asm.ClassSource import io.jooby.jetty.Jetty import io.jooby.junit.ServerTest import io.jooby.junit.ServerTestRunner import org.junit.jupiter.api.Assertions.assertEquals class Issue2598 { @ServerTest(server = [Jetty::class]) fun analyzerShouldDetectCompletableFuture(runner: ServerTestRunner) { val analyzer = RouteAnalyzer(ClassSource(javaClass.classLoader), false) val app = App2598() runner .use { app } .ready { _ -> val router = app.router val route = router.routes[0] val type = analyzer.returnType(route.handle) assertEquals(Context::class.java, type) } } }
apache-2.0
lvtanxi/Study
BootMybatis/src/test/kotlin/com/lv/BootmybatisApplicationTests.kt
1
309
package com.lv import org.junit.Test import org.junit.runner.RunWith import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.junit4.SpringRunner @RunWith(SpringRunner::class) @SpringBootTest class BootmybatisApplicationTests { @Test fun contextLoads() { } }
apache-2.0
Soya93/Extract-Refactoring
platform/testFramework/src/com/intellij/testFramework/TemporaryDirectory.kt
4
3078
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testFramework import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.* import com.intellij.util.lang.CompoundRuntimeException import org.junit.rules.ExternalResource import org.junit.runner.Description import org.junit.runners.model.Statement import java.io.IOException import java.nio.file.Path import java.nio.file.Paths import kotlin.properties.Delegates class TemporaryDirectory : ExternalResource() { private val paths = SmartList<Path>() private var sanitizedName: String by Delegates.notNull() override fun apply(base: Statement, description: Description): Statement { sanitizedName = FileUtil.sanitizeFileName(description.methodName, false) return super.apply(base, description) } override fun after() { val errors = SmartList<Throwable>() for (path in paths) { try { path.deleteRecursively() } catch (e: Throwable) { errors.add(e) } } CompoundRuntimeException.throwIfNotEmpty(errors) paths.clear() } fun newPath(directoryName: String? = null, refreshVfs: Boolean = false): Path { val path = generatePath(directoryName) if (refreshVfs) { path.refreshVfs() } return path } private fun generatePath(suffix: String?): Path { var fileName = sanitizedName if (suffix != null) { fileName += "_$suffix" } var path = generateTemporaryPath(fileName) paths.add(path) return path } fun newVirtualDirectory(directoryName: String? = null): VirtualFile { val path = generatePath(directoryName) path.createDirectories() val virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(path.systemIndependentPath) VfsUtil.markDirtyAndRefresh(false, true, true, virtualFile) return virtualFile!! } } fun generateTemporaryPath(fileName: String?): Path { val tempDirectory = Paths.get(FileUtilRt.getTempDirectory()) var path = tempDirectory.resolve(fileName) var i = 0 while (path.exists() && i < 9) { path = tempDirectory.resolve("${fileName}_$i") i++ } if (path.exists()) { throw IOException("Cannot generate unique random path") } return path } fun VirtualFile.writeChild(relativePath: String, data: String) = VfsTestUtil.createFile(this, relativePath, data)
apache-2.0
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/data/dao/response/PubplansResponse.kt
2
1308
package ru.fantlab.android.data.dao.response import com.github.kittinunf.fuel.core.ResponseDeserializable import com.google.gson.JsonParser import ru.fantlab.android.data.dao.Pageable import ru.fantlab.android.data.dao.model.Pubplans import ru.fantlab.android.provider.rest.DataManager data class PubplansResponse( val editions: Pageable<Pubplans.Object>, val publisherList: List<Pubplans.Publisher> ) { class Deserializer : ResponseDeserializable<PubplansResponse> { override fun deserialize(content: String): PubplansResponse { val jsonObject = JsonParser().parse(content).asJsonObject val items: ArrayList<Pubplans.Object> = arrayListOf() val publishers: ArrayList<Pubplans.Publisher> = arrayListOf() val array = jsonObject.getAsJsonArray("objects") array.map { items.add(DataManager.gson.fromJson(it, Pubplans.Object::class.java)) } val publishersArray = jsonObject.getAsJsonArray("publisher_list") publishersArray.map { publishers.add(DataManager.gson.fromJson(it, Pubplans.Publisher::class.java)) } val totalCount = jsonObject.getAsJsonPrimitive("total_count").asInt val lastPage = jsonObject.getAsJsonPrimitive("page_count").asInt val responses = Pageable(lastPage, totalCount, items) return PubplansResponse(responses, publishers) } } }
gpl-3.0
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/fave/dto/FaveGetExtendedItemType.kt
1
2096
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.fave.dto import com.google.gson.annotations.SerializedName import kotlin.String enum class FaveGetExtendedItemType( val value: String ) { @SerializedName("article") ARTICLE("article"), @SerializedName("clip") CLIP("clip"), @SerializedName("link") LINK("link"), @SerializedName("narrative") NARRATIVE("narrative"), @SerializedName("page") PAGE("page"), @SerializedName("podcast") PODCAST("podcast"), @SerializedName("post") POST("post"), @SerializedName("product") PRODUCT("product"), @SerializedName("video") VIDEO("video"), @SerializedName("youla_product") YOULA_PRODUCT("youla_product"); }
mit
world-federation-of-advertisers/virtual-people-common
src/test/kotlin/org/wfanet/virtualpeople/common/fieldfilter/HasFilterTest.kt
1
4067
// Copyright 2022 The Cross-Media Measurement 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.wfanet.virtualpeople.common.fieldfilter import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.wfanet.virtualpeople.common.FieldFilterProto.Op import org.wfanet.virtualpeople.common.fieldFilterProto import org.wfanet.virtualpeople.common.test.TestProto import org.wfanet.virtualpeople.common.test.testProto import org.wfanet.virtualpeople.common.test.testProtoA import org.wfanet.virtualpeople.common.test.testProtoB @RunWith(JUnit4::class) class HasFilterTest { @Test fun `filter without name should fail`() { val fieldFilter = fieldFilterProto { op = Op.HAS } val exception = assertFailsWith<IllegalStateException> { FieldFilter.create(TestProto.getDescriptor(), fieldFilter) } assertTrue(exception.message!!.contains("Name must be set")) } @Test fun `filter with invalid name should fail`() { val fieldFilter = fieldFilterProto { name = "a.b.invalid_field" op = Op.HAS } val exception = assertFailsWith<IllegalStateException> { FieldFilter.create(TestProto.getDescriptor(), fieldFilter) } assertTrue(exception.message!!.contains("The field name is invalid")) } @Test fun `filter with repeated field in the path should fail`() { val fieldFilter = fieldFilterProto { name = "repeated_proto_a.b.int32_value" op = Op.HAS } val exception = assertFailsWith<IllegalStateException> { FieldFilter.create(TestProto.getDescriptor(), fieldFilter) } assertTrue(exception.message!!.contains("Repeated field is not allowed in the path")) } @Test fun `has nonrepeated field`() { val fieldFilter = fieldFilterProto { name = "a.b.int32_value" op = Op.HAS } val filter = FieldFilter.create(TestProto.getDescriptor(), fieldFilter) val testProto1 = testProto { a = testProtoA { b = testProtoB { int32Value = 1 } } } assertTrue(filter.matches(testProto1)) assertTrue(filter.matches(testProto1.toBuilder())) val testProto2 = testProto { a = testProtoA { b = testProtoB { int64Value = 1 } } } assertFalse(filter.matches(testProto2)) assertFalse(filter.matches(testProto2.toBuilder())) val testProto3 = testProto {} assertFalse(filter.matches(testProto3)) assertFalse(filter.matches(testProto3.toBuilder())) } @Test fun `has repeated field`() { val fieldFilter = fieldFilterProto { name = "a.b.int32_values" op = Op.HAS } val filter = FieldFilter.create(TestProto.getDescriptor(), fieldFilter) val testProto1 = testProto { a = testProtoA { b = testProtoB { int32Values.add(1) } } } assertTrue(filter.matches(testProto1)) assertTrue(filter.matches(testProto1.toBuilder())) val testProto2 = testProto { a = testProtoA { b = testProtoB { int32Values.add(1) int32Values.add(2) } } } assertTrue(filter.matches(testProto2)) assertTrue(filter.matches(testProto2.toBuilder())) val testProto3 = testProto { a = testProtoA { b = testProtoB { int32Value = 1 } } } assertFalse(filter.matches(testProto3)) assertFalse(filter.matches(testProto3.toBuilder())) val testProto4 = testProto {} assertFalse(filter.matches(testProto4)) assertFalse(filter.matches(testProto4.toBuilder())) } }
apache-2.0
daniloqueiroz/nsync
src/main/kotlin/commons/Result.kt
1
299
package commons sealed class Result<T> { fun then(block: (Result<T>) -> Unit): Result<T> { block(this) return this } } data class Failure<T>(val error: Exception) : Result<T>() { val message: String? = error.message } data class Success<T>(val value: T) : Result<T>()
gpl-3.0
ligee/kotlin-jupyter
build-plugin/src/build/util/repositories.kt
1
1429
package build.util import org.gradle.api.Project import org.gradle.kotlin.dsl.maven import org.gradle.kotlin.dsl.repositories const val INTERNAL_TEAMCITY_URL = "https://buildserver.labs.intellij.net" const val PUBLIC_TEAMCITY_URL = "https://teamcity.jetbrains.com" class TeamcityProject( val url: String, val projectId: String ) val INTERNAL_KOTLIN_TEAMCITY = TeamcityProject(INTERNAL_TEAMCITY_URL, "Kotlin_KotlinDev_Artifacts") val PUBLIC_KOTLIN_TEAMCITY = TeamcityProject(PUBLIC_TEAMCITY_URL, "Kotlin_KotlinPublic_Artifacts") const val TEAMCITY_REQUEST_ENDPOINT = "guestAuth/app/rest/builds" fun Project.addAllBuildRepositories() { val kotlinVersion = rootProject.defaultVersionCatalog.versions.devKotlin repositories { mavenLocal() mavenCentral() gradlePluginPortal() // Kotlin Dev releases are published here every night maven("https://maven.pkg.jetbrains.space/kotlin/p/kotlin/dev") for (teamcity in listOf(INTERNAL_KOTLIN_TEAMCITY, PUBLIC_KOTLIN_TEAMCITY)) { val locator = "buildType:(id:${teamcity.projectId}),number:$kotlinVersion,branch:default:any/artifacts/content/maven" maven("${teamcity.url}/$TEAMCITY_REQUEST_ENDPOINT/$locator") } // Used for TeamCity build val m2LocalPath = file(".m2/repository") if (m2LocalPath.exists()) { maven(m2LocalPath.toURI()) } } }
apache-2.0
thomasvolk/worm
src/main/kotlin/net/t53k/worm/Timeout.kt
1
1226
/* * Copyright 2017 Thomas Volk * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package net.t53k.worm interface Timeout { fun start(callback: () -> Unit): Unit } object InfinityTimeout : Timeout { override fun start(callback: () -> Unit) { /* this will never run the callback */ } } class MilliSecondsTimeout(val durationMs: Long) : Timeout { override fun start(callback: () -> Unit) { Thread.sleep(durationMs) callback() } }
apache-2.0
felipebz/sonar-plsql
zpa-core/src/test/kotlin/org/sonar/plugins/plsqlopen/api/expressions/ListAggExpressionTest.kt
1
3081
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plugins.plsqlopen.api.expressions import com.felipebz.flr.tests.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.sonar.plugins.plsqlopen.api.PlSqlGrammar import org.sonar.plugins.plsqlopen.api.RuleTest class ListAggExpressionTest : RuleTest() { @BeforeEach fun init() { setRootRule(PlSqlGrammar.EXPRESSION) } @Test fun matchesSimpleListAgg() { assertThat(p).matches("listagg(foo) within group (order by bar)") } @Test fun matchesListAggAll() { assertThat(p).matches("listagg(all foo) within group (order by bar)") } @Test fun matchesListAggDistinct() { assertThat(p).matches("listagg(distinct foo) within group (order by bar)") } @Test fun matchesListAggWithDelimiter() { assertThat(p).matches("listagg(foo, ',') within group (order by bar)") } @Test fun matchesListAggWithDelimiter2() { assertThat(p).matches("listagg(foo, chr(10)) within group (order by bar)") } @Test fun matchesListAggOverflowError() { assertThat(p).matches("listagg(foo on overflow error) within group (order by bar)") } @Test fun matchesListAggOverflowTruncate() { assertThat(p).matches("listagg(foo on overflow truncate) within group (order by bar)") } @Test fun matchesListAggOverflowTruncateWithIndicator() { assertThat(p).matches("listagg(foo on overflow truncate '...') within group (order by bar)") } @Test fun matchesListAggOverflowTruncateWithCount() { assertThat(p).matches("listagg(foo on overflow truncate '...' with count) within group (order by bar)") } @Test fun matchesListAggOverflowTruncateWithoutCount() { assertThat(p).matches("listagg(foo on overflow truncate '...' without count) within group (order by bar)") } @Test fun matchesListAggPartitionBy() { assertThat(p).matches("listagg(foo) within group (order by bar) over (partition by baz)") } @Test fun matchesLongListAgg() { assertThat(p).matches("listagg(foo, ',') within group (order by bar) over (partition by baz)") } }
lgpl-3.0
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/subject/two/CleanCacheCallback.kt
1
365
package com.intfocus.template.subject.two /** * **************************************************** * author jameswong * created on: 17/12/13 下午5:28 * e-mail: [email protected] * name: * desc: * **************************************************** */ interface CleanCacheCallback { fun onCleanCacheSuccess() fun onCleanCacheFailure() }
gpl-3.0
bogerchan/National-Geography
app/src/main/java/me/boger/geographic/biz/detailpage/DetailPagePresenterImpl.kt
1
5620
package me.boger.geographic.biz.detailpage import android.content.Intent import android.graphics.Bitmap import android.net.Uri import android.os.Bundle import com.facebook.common.executors.CallerThreadExecutor import com.facebook.common.references.CloseableReference import com.facebook.datasource.DataSource import com.facebook.drawee.backends.pipeline.Fresco import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber import com.facebook.imagepipeline.image.CloseableImage import com.facebook.imagepipeline.request.ImageRequest import me.boger.geographic.R import me.boger.geographic.core.NGRumtime import me.boger.geographic.core.NGUtil import me.boger.geographic.biz.common.ContentType import me.boger.geographic.util.Timber import java.io.File import java.io.IOException import java.io.OutputStream import java.util.* /** * Created by BogerChan on 2017/6/30. */ class DetailPagePresenterImpl : IDetailPagePresenter { private var mUI: IDetailPageUI? = null private val mModel: IDetailPageModel by lazy { DetailPageModelImpl() } override fun init(ui: IDetailPageUI) { mUI = ui if (ui.hasOfflineData()) { ui.refreshData(ui.getOfflineData().picture) ui.contentType = ContentType.CONTENT } else { mModel.requestDetailPageData(ui.getDetailPageDataId(), onStart = { ui.contentType = ContentType.LOADING }, onError = { ui.contentType = ContentType.ERROR }, onComplete = { ui.contentType = ContentType.CONTENT }, onNext = { NGRumtime.favoriteNGDataSupplier.syncFavoriteState(it) ui.refreshData(it.picture) }) } } override fun shareDetailPageImage(url: String) { mUI?.showTipMessage(R.string.tip_share_img_start) fetchImage( url, File(NGRumtime.cacheImageDir, NGUtil.toMD5(url)), { val intent = Intent(Intent.ACTION_SEND) intent.type = "image/jpg" intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(it)) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK mUI?.startActivity(Intent.createChooser(intent, mUI?.getResourceString(R.string.title_share))) }, { mUI?.showTipMessage(R.string.tip_share_img_error) }) } override fun saveDetailPageImage(url: String) { mUI?.showTipMessage(R.string.tip_save_img_start) fetchImage( url, File(NGRumtime.externalAlbumDir, "${NGUtil.toMD5(url)}.jpg"), { if (mUI == null) { return@fetchImage } mUI!!.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(it))) mUI!!.showTipMessage( String.format(Locale.US, mUI!!.getResourceString(R.string.template_tip_save_img_complete), it.absolutePath)) }, { mUI?.showTipMessage(R.string.tip_share_img_error) }) } override fun setDetailPageItemFavoriteState(data: DetailPagePictureData) { val supplier = NGRumtime.favoriteNGDataSupplier if (data.favorite) { data.favorite = false if (!supplier.removeDetailPageDataToFavorite(data)) { data.favorite = true } } else { data.favorite = true if (!supplier.addDetailPageDataToFavorite(data)) { data.favorite = false } } mUI?.setFavoriteButtonState(data.favorite) } private fun fetchImage( url: String, dstFile: File, succ: (File) -> Unit, err: () -> Unit) { val imagePipline = Fresco.getImagePipeline() val dataSource = imagePipline.fetchDecodedImage(ImageRequest.fromUri(url), ImageRequest.RequestLevel.FULL_FETCH) dataSource.subscribe(object : BaseBitmapDataSubscriber() { override fun onFailureImpl(dataSource: DataSource<CloseableReference<CloseableImage>>?) { err() } override fun onNewResultImpl(bitmap: Bitmap?) { if (bitmap == null) { err() return } if (!saveBitmap(bitmap, dstFile)) { err() return } succ(dstFile) } }, CallerThreadExecutor.getInstance()) } private fun saveBitmap(bmp: Bitmap, file: File): Boolean { var stream: OutputStream? = null try { stream = file.outputStream() file.createNewFile() bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream) return true } catch (e: IOException) { Timber.e(e) return false } finally { stream?.close() } } override fun destroy() { mModel.cancelPendingCall() } override fun onSaveInstanceState(outState: Bundle?) { mModel.onSaveInstanceState(outState) } override fun restoreDataIfNeed(savedInstanceState: Bundle?) { mModel.restoreDataIfNeed(savedInstanceState) } }
apache-2.0
rhdunn/xquery-intellij-plugin
src/plugin-expath/main/uk/co/reecedunn/intellij/plugin/expath/pkg/EXPathPackageComponent.kt
1
813
/* * Copyright (C) 2019 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.expath.pkg import uk.co.reecedunn.intellij.plugin.xdm.module.path.XdmModuleType interface EXPathPackageComponent { val moduleType: XdmModuleType val file: String? }
apache-2.0